Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 29 additions & 51 deletions apps/backend/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,62 +1,40 @@
import { startTracing } from "./utils/tracing";
startTracing();
import express from 'express';
import cors from 'cors';
import cookieParser from 'cookie-parser';
import dotenv from 'dotenv';

import cookieParser from "cookie-parser";
import express, { urlencoded } from "express";
import cors from "cors";
import { httpRequestCounter, httpRequestDuration } from "./utils/metrics";
import { correlationIdMiddleware } from "./middlewares/correlationId.middleware";
import logger from "./utils/logger";
import apiRouter from './routes/index'; // Import the main API router

dotenv.config({
path: './.env'
});

const app = express();
const PORT = process.env.BACKEND_PORT || 3000

const allowedOrigins = [
"http://localhost:5173",
"http://nen.jagjeevan.me",
"https://nen.jagjeevan.me",
process.env.FRONTEND_URL
].filter(Boolean);

app.use(
cors({
origin: (origin, callback) => {
if (!origin || allowedOrigins.includes(origin)) {
callback(null, true);
} else {
callback(new Error("Not allowed by CORS"));
}
},
credentials: true,
methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
allowedHeaders: ["Content-Type", "Authorization"],
})
);

// Standard middleware setup
app.use(cors({
origin: process.env.CORS_ORIGIN || 'http://localhost:5173', // Adjust based on frontend URL
credentials: true
}));
app.use(express.json({ limit: '16kb' }));
app.use(express.urlencoded({ extended: true, limit: '16kb' }));
app.use(express.static('public')); // Serve static files
app.use(cookieParser());
app.use(urlencoded({ extended: true }));
app.use(express.json());
app.use(correlationIdMiddleware);

app.use((req, res, next) => {
const start = Date.now();
res.on("finish", () => {
const duration = (Date.now() - start) / 1000;
httpRequestCounter.inc({ method: req.method, route: req.path, status_code: res.statusCode });
httpRequestDuration.observe({ method: req.method, route: req.path, status_code: res.statusCode }, duration);
});
next();
});

import v1 from "./routes"
import metricsRouter from "./routes/metrics.routes";
import { errorHandler } from "./middlewares/error.middleware";
// Mount the API router at the /api path
app.use('/api', apiRouter);

app.use("/api/v1", v1);
app.use("/", metricsRouter);
// Basic route for testing
app.get('/', (req, res) => {
res.send('nEn Backend is running!');
});

app.use(errorHandler);
// Error handling middleware (example, assuming it exists elsewhere)
// app.use(errorMiddleware);

const PORT = process.env.PORT || 8000;
app.listen(PORT, () => {
logger.info(`Backend server listening on port ${PORT}`);
console.log(`Server is running on port ${PORT}`);
});

export default app;
30 changes: 18 additions & 12 deletions apps/backend/src/routes/auth.routes.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,22 @@
import { Router } from "express";
import { getUser, handleSignInCallback, logout, signin, signInWithGoogle, signup, verifyGoogleToken } from "../controllers/auth.controller";
import { isLoggedIn } from "../middlewares/auth.middleware";
import express from 'express';
import { authRateLimiter } from '../utils/rateLimiter';
// Assuming controllers for auth exist, e.g.,
// import { registerUser, loginUser, logoutUser, refreshAccessToken } from '../controllers/auth.controller';

const router = Router();
const router = express.Router();

router.post('/signin', signin )
router.post('/signup', signup)
router.post('/google-verify', verifyGoogleToken)
router.post('/logout', logout)
router.get('/me', isLoggedIn, getUser)
router.get('/google', isLoggedIn, signInWithGoogle)
router.get('/google/callback', isLoggedIn, handleSignInCallback)
// Apply a stricter rate limiter to login and register routes to prevent brute-force attacks
router.post('/register', authRateLimiter, (req, res) => {
// Placeholder for registerUser logic
res.status(200).json({ message: 'Register endpoint hit' });
});
router.post('/login', authRateLimiter, (req, res) => {
// Placeholder for loginUser logic
res.status(200).json({ message: 'Login endpoint hit' });
});

// Other auth routes that might not need the strict rate limit, or implicitly use the general API rate limiter from index.ts
// router.post('/logout', logoutUser);
// router.post('/refresh-token', refreshAccessToken);

export default router
export default router;
34 changes: 21 additions & 13 deletions apps/backend/src/routes/index.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,24 @@
import { Router } from "express";
import authRouter from "./auth.routes";
import credRouter from "./cred.routes";
import triggerRouter from "./triggers.routes"
import workflowRouter from "./workflow.routes"
import webHookRouter from "./webhook.routes"
import express from 'express';
import { apiRateLimiter } from '../utils/rateLimiter';
import authRoutes from './auth.routes';
// Placeholder for other routes - uncomment and import as needed
// import credRoutes from './cred.routes';
// import triggersRoutes from './triggers.routes';
// import workflowRoutes from './workflow.routes';
// import webhookRoutes from './webhook.routes';
// import metricsRoutes from './metrics.routes';

const router = Router();
const router = express.Router();

router.use("/auth", authRouter);
router.use("/cred", credRouter);
router.use("/trigger", triggerRouter)
router.use('/workflow', workflowRouter)
router.use('/webhook', webHookRouter)
// Apply the general API rate limiter to all routes handled by this router
router.use(apiRateLimiter);

export default router;
// Mount specific routers
router.use('/auth', authRoutes);
// router.use('/cred', credRoutes);
// router.use('/triggers', triggersRoutes);
// router.use('/workflow', workflowRoutes);
// router.use('/webhook', webhookRoutes);
// router.use('/metrics', metricsRoutes);

export default router;
19 changes: 19 additions & 0 deletions apps/backend/src/utils/rateLimiter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { rateLimit } from 'express-rate-limit';

// General API rate limiter for most routes
export const apiRateLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // Limit each IP to 100 requests per windowMs
message: 'Too many requests from this IP, please try again after 15 minutes',
standardHeaders: true, // Return rate limit info in the `RateLimit-*` headers
legacyHeaders: false // Disable the `X-RateLimit-*` headers
});

// Stricter rate limiter for authentication routes (e.g., login, register)
export const authRateLimiter = rateLimit({
windowMs: 5 * 60 * 1000, // 5 minutes
max: 5, // Limit each IP to 5 requests per windowMs for auth routes
message: 'Too many authentication attempts from this IP, please try again after 5 minutes',
standardHeaders: true,
legacyHeaders: false
});