feat: add sample endpoint to test JWT
This commit is contained in:
@@ -4,10 +4,17 @@ import jwt from 'jsonwebtoken';
|
||||
import { DEFAULT_TOKEN_LIFETIME } from '../schemas/authSchema';
|
||||
import * as env from './env';
|
||||
|
||||
type JwtStatus = {
|
||||
export type JwtDecoded = {
|
||||
sub: number;
|
||||
role: number;
|
||||
iat: number;
|
||||
exp: number;
|
||||
};
|
||||
|
||||
export type JwtStatus = {
|
||||
valid: boolean;
|
||||
expired: boolean;
|
||||
decoded: string | jwt.JwtPayload | null;
|
||||
decoded: JwtDecoded | null; // null if decoding failed
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -52,7 +59,7 @@ export function signJwt(
|
||||
*/
|
||||
export function verifyJwt(
|
||||
token: string,
|
||||
keyName: 'accessTokenPublicKey' | 'refreshTokenPublicKey'
|
||||
keyName: 'accessTokenPrivateKey' | 'refreshTokenPrivateKey'
|
||||
): JwtStatus {
|
||||
|
||||
// refresh tokens aren't (yet) supported
|
||||
@@ -64,18 +71,21 @@ export function verifyJwt(
|
||||
const secret: string = env.getString(keyName, true)!;
|
||||
|
||||
try {
|
||||
const decoded: string | jwt.JwtPayload = jwt.verify(token, secret);
|
||||
const decoded: jwt.JwtPayload | string = jwt.verify(token, secret);
|
||||
|
||||
// TODO: Can this be done better, smarter?
|
||||
|
||||
return {
|
||||
valid: true,
|
||||
expired: false,
|
||||
decoded,
|
||||
decoded: decoded as unknown as JwtDecoded
|
||||
};
|
||||
} catch (e: any) {
|
||||
console.error('JWT verify error:', e);
|
||||
return {
|
||||
valid: false,
|
||||
valid: e.message !== 'jwt malformed',
|
||||
expired: e.message === 'jwt expired',
|
||||
decoded: null,
|
||||
decoded: null
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user