1- // src/middlewares/authMiddleware.ts
21import { Request , Response , NextFunction } from "express" ;
32import jwt from "jsonwebtoken" ;
4- import { User } from "../models/user.model ";
3+ const SECRET_KEY = process . env . JWT_SECRET || "your_secret_key ";
54
6- const JWT_SECRET = process . env . JWT_SECRET || "secretkey" ;
7-
8- export interface AuthRequest extends Request {
5+ export interface AuthenticatedRequest extends Request {
96 user ?: any ;
107}
118
12- export const protect = async ( req : AuthRequest , res : Response , next : NextFunction ) => {
13- let token ;
14-
15- if ( req . headers . authorization && req . headers . authorization . startsWith ( "Bearer" ) ) {
16- token = req . headers . authorization . split ( " " ) [ 1 ] ;
9+ export const authenticate = ( req : AuthenticatedRequest , res : Response , next : NextFunction ) => {
10+ const authHeader = req . headers . authorization ;
11+ if ( ! authHeader || ! authHeader . startsWith ( "Bearer " ) ) {
12+ return res . status ( 401 ) . json ( { message : "Unauthorized" } ) ;
1713 }
18-
19- if ( ! token ) return res . status ( 401 ) . json ( { message : "Not authorized, no token" } ) ;
20-
14+ const token = authHeader . split ( " " ) [ 1 ] ;
2115 try {
22- const decoded = jwt . verify ( token , JWT_SECRET ) as { id : string } ;
23- req . user = await User . findById ( decoded . id ) . select ( "-password" ) ;
16+ const decoded = jwt . verify ( token , SECRET_KEY ) ;
17+ req . user = decoded ;
2418 next ( ) ;
2519 } catch ( error ) {
26- res . status ( 401 ) . json ( { message : "Not authorized, token failed " } ) ;
20+ return res . status ( 401 ) . json ( { message : "Invalid token" } ) ;
2721 }
2822} ;
23+
24+ // For legacy support in /api/users route expecting 'protect'
25+ export const protect = authenticate ;
26+
27+ // Role-based guard
28+ export const authorizeRole = ( role : string ) => {
29+ return ( req : AuthenticatedRequest , res : Response , next : NextFunction ) => {
30+ if ( ! req . user ) {
31+ return res . status ( 401 ) . json ( { error : 'Not authenticated' } ) ;
32+ }
33+ if ( req . user . role !== role ) {
34+ return res . status ( 403 ) . json ( { error : 'Forbidden' } ) ;
35+ }
36+ next ( ) ;
37+ } ;
38+ } ;
0 commit comments