| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253 |
- import { Request, Response, NextFunction } from 'express';
- import jwt from 'jsonwebtoken';
- export interface JwtPayload {
- userId: string;
- email: string;
- role: string;
- }
- declare global {
- namespace Express {
- interface Request {
- user?: JwtPayload;
- }
- }
- }
- export function authMiddleware(req: Request, res: Response, next: NextFunction): void {
- const authHeader = req.headers.authorization;
- const token =
- authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : req.cookies?.token;
- if (!token) {
- res.status(401).json({ error: 'No token provided' });
- return;
- }
- try {
- const secret = process.env.JWT_SECRET || 'fallback-secret';
- const payload = jwt.verify(token, secret) as JwtPayload;
- req.user = payload;
- next();
- } catch {
- res.status(401).json({ error: 'Invalid or expired token' });
- }
- }
- export function optionalAuth(req: Request, res: Response, next: NextFunction): void {
- const authHeader = req.headers.authorization;
- const token =
- authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : req.cookies?.token;
- if (token) {
- try {
- const secret = process.env.JWT_SECRET || 'fallback-secret';
- const payload = jwt.verify(token, secret) as JwtPayload;
- req.user = payload;
- } catch {
- // ignore invalid token for optional auth
- }
- }
- next();
- }
|