Skip to content

Commit 06777cb

Browse files
v1 release
1 parent 63568b8 commit 06777cb

91 files changed

Lines changed: 21715 additions & 2022 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

.env.example

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,26 @@
1-
API_URL = /api/v1
2-
PORT = 3000
3-
CONNECTION_STRING =
1+
# switch between development and production
2+
NODE_ENV="development"
3+
4+
# add root domain of app
5+
APP_URL="http://localhost:5051"
6+
7+
TIMEZONE="Asia/Kolkata"
8+
9+
PORT=5051
10+
SESSION_SECRET="8ksyoursecret9gt8s"
11+
DATABASE_URL='mongodb-url'
12+
13+
ACCESS_TOKEN_SECRET=lkqjirirgjnjdsecretwteh4h4h4
14+
ACCESS_TOKEN_EXPIRY=1d
15+
16+
REFRESH_TOKEN_SECRET=lkaoiesecret84hwteh4h4h4
17+
REFRESH_TOKEN_EXPIRY=30d
18+
19+
MAIL_HOST="smtp.gmail.com"
20+
MAIL_PORT=465
21+
MAILER_USER="panditprogrammer@gmail.com"
22+
MAILER_PASSWORD=
23+
MAIL_FROM="contact@panditprogrammer.com"
24+
25+
WEB_PUSH_VAPID_PUBLIC_KEY=BGoEVxF-laeHUQC6ChgenerateByJ2udxVgUxeqRZ_yqFpKAoscwbYo1c8
26+
WEB_PUSH_VAPID_PRIVATE_KEY=ii1FzaMOkHbcpQmS-4_uy9QATBovscfOLM42gVcy2IY

.gitignore

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,12 @@
1-
/node_modules
1+
node_modules
2+
23
.env
3-
package-lock.json
4+
5+
.env.production
6+
public/uploads
7+
8+
backups
9+
public/*.txt
10+
.logs
11+
12+
firebase.json

app.js

Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
1+
import cookieParser from "cookie-parser";
2+
import cors from "cors"
3+
import express from "express"
4+
import helmet from "helmet";
5+
import session from "express-session";
6+
import { API_PREFIX, APP_NAME } from "./src/constants.js";
7+
import webPush from 'web-push';
8+
import { globalAuthCheck } from "./src/middlewares/authMiddleware.js";
9+
10+
11+
12+
13+
const app = express();
14+
15+
16+
// 1. Core Express Settings & Trust Proxy (Highest Priority)
17+
// These don't directly process requests but configure Express's behavior
18+
app.set('view engine', 'ejs');
19+
app.set('trust proxy', 1); // Essential when behind a reverse proxy like Nginx
20+
21+
// 2. Security & Basic Request Parsing (Early - before anything else relies on parsed data)
22+
// These should generally come before most other middleware to apply security
23+
// and parse basic request components like cookies and body.
24+
25+
app.use(helmet({
26+
contentSecurityPolicy: false // Reconsider enabling this if possible for better security
27+
}));
28+
29+
app.use(cors({
30+
origin: process.env.CORS_ORIGIN,
31+
credentials: true
32+
}));
33+
34+
app.use(cookieParser()); // Parses cookies from the request headers
35+
36+
// 3. Session Middleware (Relies on cookies, so comes after cookieParser)
37+
app.use(
38+
session({
39+
secret: process.env.SESSION_SECRET,
40+
resave: false,
41+
saveUninitialized: false,
42+
cookie: {
43+
secure: process.env.NODE_ENV === "production",
44+
httpOnly: true,
45+
maxAge: 15 * 24 * 60 * 60 * 1000,
46+
sameSite: 'Strict',
47+
},
48+
})
49+
);
50+
51+
52+
53+
// 4. Body Parsers (Relies on raw request body, comes after session if session needs body)
54+
// These should come before any routes or middleware that need to access req.body
55+
app.use(express.json({
56+
limit: "100mb" // Adjust as needed, 200MB is very large
57+
}));
58+
app.use(express.urlencoded({ extended: true, limit: "20kb" }));
59+
60+
// 5. Static File Serving (Critical: Should come *before* any authentication or rate limiting
61+
// if you want public assets to be served without those checks)
62+
app.use(express.static("public"));
63+
64+
// Your custom full URL middleware (doesn't change req/res much, so flexible)
65+
app.use((req, res, next) => {
66+
var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
67+
// You might want to actually *do* something with fullUrl here, like logging it
68+
next();
69+
});
70+
71+
72+
73+
// 8. Global Variable/Local Setup (Can be flexible, but often useful before auth or routes)
74+
// This middleware populates res.locals, which is good to have before rendering views
75+
// or if subsequent middleware/routes might use these locals.
76+
app.use((req, res, next) => {
77+
res.locals.websiteName = APP_NAME;
78+
res.locals.request = req;
79+
res.locals.data = {};
80+
res.locals.messages = {};
81+
res.locals.message = { text: null, type: null };
82+
res.locals.fields = {};
83+
res.locals.ogData = null;
84+
85+
86+
const path = req.originalUrl.split('?')[0];
87+
const cleanedPath = path.replace(/\/p\/[a-f0-9]{24}/, '');
88+
const titleParts = cleanedPath.replace(/^\/+/, '').split('/');
89+
const generatedTitle = titleParts
90+
.map(part => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase())
91+
.join(' ') || APP_NAME;
92+
res.locals.websiteTitle = generatedTitle;
93+
94+
next();
95+
});
96+
97+
// 9. Global Authentication/Authorization (Should come before routes that require auth)
98+
// This is where globalAuthCheck fits well. It runs for all requests that haven't
99+
// been handled by static files, before they hit your specific API or page routes.
100+
app.use(globalAuthCheck);
101+
102+
// log the requests
103+
104+
// 10. Web Push Setup (This is a setup, not a middleware, so placement doesn't affect request flow)
105+
// It only sets up details for future web push operations, not processing incoming requests.
106+
webPush.setVapidDetails(
107+
'mailto:panditprogrammer@gmail.com',
108+
process.env.WEB_PUSH_VAPID_PUBLIC_KEY,
109+
process.env.WEB_PUSH_VAPID_PRIVATE_KEY
110+
);
111+
112+
113+
114+
115+
//--------------- routes -----------------
116+
import userRouter from "./src/routes/userRoutes.js";
117+
import utilityRouter from "./src/routes/utilityRoutes.js";
118+
import notificationRouter from "./src/routes/notificationRoutes.js";
119+
import pagesRouter from "./src/routes/pagesRoutes.js";
120+
import postRouter from "./src/routes/postRoutes.js";
121+
import friendRequestRouter from "./src/routes/friendRequestRoutes.js";
122+
import chatMessageRouter from "./src/routes/chatMessageRoutes.js";
123+
124+
app.use(`/`, pagesRouter);
125+
126+
// Register routes
127+
app.use(`/users`, userRouter);
128+
app.use(`/notifications`, notificationRouter);
129+
130+
131+
// api for mobile
132+
app.use(`${API_PREFIX}/friend-requests`, friendRequestRouter);
133+
app.use(`${API_PREFIX}/chats`, chatMessageRouter);
134+
135+
app.use(`${API_PREFIX}/posts`, postRouter);
136+
app.use(`${API_PREFIX}/users`, userRouter);
137+
app.use(`${API_PREFIX}/utilities`, utilityRouter);
138+
app.use(`${API_PREFIX}/notifications`, notificationRouter);
139+
140+
141+
142+
143+
// app.use(errorHandler);
144+
export default app;

helpers/errorHander.js

Lines changed: 0 additions & 16 deletions
This file was deleted.

helpers/jwt.js

Lines changed: 0 additions & 30 deletions
This file was deleted.

index.js

Lines changed: 35 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -1,74 +1,50 @@
1-
const express = require("express");
2-
const server = express();
1+
import dotenv from "dotenv";
2+
import connectDatabase from "./src/database/connection.js";
3+
import app from "./app.js";
4+
import { createServer } from "http"; // Import createServer for Socket.io
5+
import { Server } from "socket.io"; // Import Socket.io
6+
import socketController from "./src/socket/socketController.js";
7+
import firebaseInit from "./src/config/firebase.js";
8+
import databaseSeeder from "./src/database/databaseSeeder.js";
39

4-
require("dotenv/config");
5-
const port = process.env.PORT || 3000;
6-
// const api_url = process.env.API_URL;
710

8-
// ==================== Middlewares ==========================
9-
// for cors policy (allow all origins)
10-
const cors = require("cors");
11-
server.use(cors());
12-
server.options("*",cors());
1311

14-
// middleware for json
15-
const bodyParser = require("body-parser");
16-
server.use(bodyParser.json());
1712

18-
// for http request log
19-
const morgan = require("morgan");
20-
server.use(morgan("tiny"))
21-
22-
// for json auth
23-
const authJwt = require("./helpers/jwt");
24-
server.use(authJwt());
25-
26-
// for static files (publish a folder)
27-
server.use("/public/uploads",express.static(__dirname+"/public/uploads"));
28-
server.use("/",express.static(__dirname+"/public/"));
29-
30-
31-
// Error handling (any type of error will send this response ) : it's a global error handling
32-
const errorHanlder = require("./helpers/errorHander");
33-
server.use((error,req,res,next) => {
34-
errorHanlder(error,req,res,next);
13+
dotenv.config({
14+
path: "./.env"
3515
});
3616

17+
const port = process.env.PORT;
3718

38-
// product router
39-
const productRouter = require("./routers/products");
40-
server.use("/products",productRouter);
19+
// If database is connected, start the Express server and Socket.io
20+
connectDatabase().then(async () => {
21+
// await databaseSeeder();
4122

42-
// category router
43-
const categoryRouter = require("./routers/categories");
44-
server.use("/categories", categoryRouter);
23+
// init firebase
24+
await firebaseInit();
4525

46-
// order router
47-
const orderRouter = require("./routers/orders");
48-
server.use("/orders", orderRouter);
4926

50-
// user router
51-
const userRouter = require("./routers/users");
52-
server.use("/users",userRouter);
53-
// ==================== Middlewares ends ==========================
27+
const httpServer = createServer(app);
28+
// Attach socket.io to the HTTP server
29+
const io = new Server(httpServer, {
30+
cors: {
31+
origin: "*", // Allow all origins for simplicity (change for production)
32+
methods: ["GET", "POST"],
33+
credentials: true
34+
}
35+
});
5436

37+
// init
38+
socketController(io);
5539

40+
await databaseSeeder();
5641

42+
// Start the server on port 5050
43+
httpServer.listen(port, () => {
44+
console.log(`Server running on http://localhost:${port}`);
45+
});
5746

5847

59-
// mongoDB database connection with mongoose
60-
const mongoose = require("mongoose");
61-
62-
// connect with database
63-
mongoose.connect(process.env.CONNECTION_STRING, {
64-
dbName: "nodeapidb"
65-
})
66-
.then(() => {
67-
console.log("MongoDB Connected!");
68-
}).catch((error) => {
69-
console.log(error);
70-
})
71-
72-
server.listen(port, () => {
73-
console.log(`server is running http://localhost:${port}`);
74-
});
48+
}).catch((error) => {
49+
console.log("MongoDB connection Failed: ", error);
50+
});

models/category.js

Lines changed: 0 additions & 19 deletions
This file was deleted.

models/order-item.js

Lines changed: 0 additions & 24 deletions
This file was deleted.

0 commit comments

Comments
 (0)