mirror of
https://github.com/directus/directus.git
synced 2026-04-25 03:00:53 -04:00
Rethrow JWT error as invalid creds
This commit is contained in:
@@ -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;
|
||||
|
||||
Reference in New Issue
Block a user