import jwt, { Secret, JwtPayload } from 'jsonwebtoken'; import { Request, Response, NextFunction } from 'express'; import Config from '../../config' export const SECRET_KEY: Secret = process.env.JWT_PRIVATE_KEY || ""; export interface CustomJWTRequest extends Request { token?: string | JwtPayload | TokenData; } export type TokenData = { userId: string, username: string, admin: boolean } export const authorize = async (req: Request, res: Response, next: NextFunction) => { try { const authHeader = req.headers.authorization; const token = authHeader?.split(" ")[1]; if (!token) { throw new Error(); } const decoded = jwt.verify(token, SECRET_KEY); (req as CustomJWTRequest).token = decoded; next(); } catch (err) { console.log(err) res.status(401).send('Please authenticate'); } };