express-api-cli
Version:
Cli tool for generating an express project. Instead of wasting extra time creating your project structure, start building right away
30 lines (27 loc) • 745 B
JavaScript
import HttpStatus from 'http-status-codes';
import jwt from 'jsonwebtoken';
/**
* 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, res, next) => {
try {
let bearerToken = req.header('Authorization');
if (!bearerToken)
throw {
code: HttpStatus.BAD_REQUEST,
message: 'Authorization token is required'
};
bearerToken = bearerToken.split(' ')[1];
const { user } = await jwt.verify(bearerToken, 'your-secret-key');
res.locals.user = user;
res.locals.token = bearerToken;
next();
} catch (error) {
next(error);
}
};