40 lines
1.3 KiB
TypeScript
40 lines
1.3 KiB
TypeScript
import type { FastifyInstance } from 'fastify';
|
|
|
|
export interface AccessTokenPayload {
|
|
sub: string; // user id
|
|
email: string;
|
|
isSuperAdmin: boolean;
|
|
}
|
|
|
|
export interface RefreshTokenPayload {
|
|
sub: string; // user id
|
|
type: 'refresh';
|
|
}
|
|
|
|
const ACCESS_TOKEN_EXPIRY = '15m';
|
|
const REFRESH_TOKEN_EXPIRY = '7d';
|
|
|
|
export function signAccessToken(app: FastifyInstance, payload: AccessTokenPayload): string {
|
|
const signer = (app as any).jwt?.sign;
|
|
if (typeof signer !== 'function') {
|
|
throw new Error('JWT signer is not configured');
|
|
}
|
|
return signer(payload, { expiresIn: ACCESS_TOKEN_EXPIRY });
|
|
}
|
|
|
|
export function signRefreshToken(app: FastifyInstance, payload: RefreshTokenPayload): string {
|
|
const signer = (app as any).jwt?.refresh?.sign ?? (app as any).jwt?.jwtRefresh?.sign;
|
|
if (typeof signer !== 'function') {
|
|
throw new Error('Refresh JWT signer is not configured');
|
|
}
|
|
return signer(payload, { expiresIn: REFRESH_TOKEN_EXPIRY });
|
|
}
|
|
|
|
export function verifyRefreshToken(app: FastifyInstance, token: string): RefreshTokenPayload {
|
|
const verifier = (app as any).jwt?.refresh?.verify ?? (app as any).jwt?.jwtRefresh?.verify;
|
|
if (typeof verifier !== 'function') {
|
|
throw new Error('Refresh JWT verifier is not configured');
|
|
}
|
|
return verifier(token) as RefreshTokenPayload;
|
|
}
|