UNPKG

express-api-cli

Version:

Cli tool for generating an express project. Instead of wasting extra time creating your project structure, start building right away

36 lines (33 loc) 921 B
/* eslint-disable @typescript-eslint/no-explicit-any */ import HttpStatus from 'http-status-codes'; import jwt from 'jsonwebtoken'; import { Request, Response, NextFunction } from 'express'; /** * Middleware to authenticate if user has a valid Authorization token * Authorization: Bearer <token> * * @param {Object} req * @param {Object} res * @param {Function} next */ export const userAuth = async ( req: Request, res: Response, next: NextFunction ): Promise<void> => { try { let bearerToken = req.header('Authorization'); if (!bearerToken) throw { code: HttpStatus.BAD_REQUEST, message: 'Authorization token is required' }; bearerToken = bearerToken.split(' ')[1]; const { user }: any = await jwt.verify(bearerToken, 'your-secret-key'); res.locals.user = user; res.locals.token = bearerToken; next(); } catch (error) { next(error); } };