major functionalities are fixed
This commit is contained in:
26
apps/Backend/src/middlewares/auth.middleware.ts
Normal file
26
apps/Backend/src/middlewares/auth.middleware.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import jwt from 'jsonwebtoken';
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
|
||||
const JWT_SECRET = process.env.JWT_SECRET || 'your-jwt-secret'; // Secret used for signing JWTs
|
||||
|
||||
export function authenticateJWT(req: Request, res: Response, next: NextFunction): void{
|
||||
|
||||
// Check the Authorization header for the Bearer token
|
||||
const token = req.header('Authorization')?.split(' ')[1]; // Extract token from Authorization header
|
||||
|
||||
if (!token) {
|
||||
res.status(401).send("Access denied. No token provided.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Verify JWT
|
||||
jwt.verify(token, JWT_SECRET, (err, decoded) => {
|
||||
if (err) {
|
||||
return res.status(403).send("Forbidden. Invalid token.");
|
||||
}
|
||||
|
||||
// Attach the decoded user data to the request object
|
||||
req.user = decoded as Express.User;
|
||||
next(); // Proceed to the next middleware or route handler
|
||||
});
|
||||
}
|
||||
6
apps/Backend/src/middlewares/error.middleware.ts
Normal file
6
apps/Backend/src/middlewares/error.middleware.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
|
||||
export const errorHandler = (err: any, _req: Request, res: Response, _next: NextFunction) => {
|
||||
console.error(err);
|
||||
res.status(err.status || 500).json({ message: err.message || 'Internal Server Error' });
|
||||
};
|
||||
33
apps/Backend/src/middlewares/logger.middleware.ts
Normal file
33
apps/Backend/src/middlewares/logger.middleware.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
|
||||
function log(message: string) {
|
||||
console.log(`[${new Date().toISOString()}] ${message}`);
|
||||
}
|
||||
|
||||
export function apiLogger(req: Request, res: Response, next: NextFunction) {
|
||||
const start = Date.now();
|
||||
const path = req.path;
|
||||
let capturedJsonResponse: Record<string, any> | undefined = undefined;
|
||||
|
||||
const originalResJson = res.json;
|
||||
res.json = function (bodyJson, ...args) {
|
||||
capturedJsonResponse = bodyJson;
|
||||
return originalResJson.apply(res, [bodyJson, ...args]);
|
||||
};
|
||||
|
||||
res.on("finish", () => {
|
||||
const duration = Date.now() - start;
|
||||
if (path.startsWith("/api")) {
|
||||
let logLine = `${req.method} ${path} ${res.statusCode} in ${duration}ms`;
|
||||
if (capturedJsonResponse) {
|
||||
logLine += ` :: ${JSON.stringify(capturedJsonResponse)}`;
|
||||
}
|
||||
if (logLine.length > 80) {
|
||||
logLine = logLine.slice(0, 79) + "…";
|
||||
}
|
||||
log(logLine);
|
||||
}
|
||||
});
|
||||
|
||||
next();
|
||||
}
|
||||
Reference in New Issue
Block a user