Files
directus/api/src/utils/jwt.ts
Azri Kahar d0b0818cca Return 401 status code for expired tokens (#12281)
* Refresh token when it's expired & retry request

* move refresh token interceptor in autoRefresh flag

* add TOKEN_EXPIRED exception

* update interceptor condition & fix autoRefreshJob

* update docs

* revert auth drivers changes

* remove unused imports

* undo sdk auth refresh changes
2022-04-04 09:23:28 -04:00

30 lines
1.0 KiB
TypeScript

import jwt, { JsonWebTokenError, TokenExpiredError } from 'jsonwebtoken';
import { DirectusTokenPayload } from '../types';
import { InvalidTokenException, ServiceUnavailableException, TokenExpiredException } from '../exceptions';
export function verifyAccessJWT(token: string, secret: string): DirectusTokenPayload {
let payload;
try {
payload = jwt.verify(token, secret, {
issuer: 'directus',
}) as Record<string, any>;
} catch (err) {
if (err instanceof TokenExpiredError) {
throw new TokenExpiredException();
} else if (err instanceof JsonWebTokenError) {
throw new InvalidTokenException('Token invalid.');
} else {
throw new ServiceUnavailableException(`Couldn't verify token.`, { service: 'jwt' });
}
}
const { id, role, app_access, admin_access, share, share_scope } = payload;
if (role === undefined || app_access === undefined || admin_access === undefined) {
throw new InvalidTokenException('Invalid token payload.');
}
return { id, role, app_access, admin_access, share, share_scope };
}