Rethrow JWT error as invalid creds

This commit is contained in:
rijkvanzanten
2020-07-07 11:30:49 -04:00
parent 1ed6b8b3a8
commit 0c1fd6df41

View File

@@ -1,8 +1,9 @@
import { RequestHandler } from 'express';
import jwt from 'jsonwebtoken';
import jwt, { TokenExpiredError } from 'jsonwebtoken';
import isJWT from '../utils/is-jwt';
import database from '../database';
import asyncHandler from 'express-async-handler';
import { InvalidCredentialsException } from '../exceptions';
/**
* Verify the passed JWT and assign the user ID and role to `req`
@@ -11,12 +12,24 @@ const authenticate: RequestHandler = asyncHandler(async (req, res, next) => {
if (!req.token) return next();
if (isJWT(req.token)) {
const payload = jwt.verify(req.token, process.env.SECRET) as { id: string };
let payload: { id: string };
try {
payload = jwt.verify(req.token, process.env.SECRET) as { id: string };
} catch (err) {
if (err instanceof TokenExpiredError) {
throw new InvalidCredentialsException('Token expired.');
} else {
throw err;
}
}
const user = await database
.select('role')
.from('directus_users')
.where({ id: payload.id })
.first();
/** @TODO verify user status */
req.user = payload.id;
req.role = user.role;