41 lines
1.4 KiB
TypeScript
41 lines
1.4 KiB
TypeScript
import jwt from 'jsonwebtoken';
|
|
import { config } from '../config.js';
|
|
|
|
export interface TokenPayload {
|
|
sub: string;
|
|
tv: number;
|
|
type: 'access' | 'refresh';
|
|
}
|
|
|
|
export const REFRESH_COOKIE = 'fitos_refresh';
|
|
/**
|
|
* Panel admina dzieli z aplikacją użytkownika tę samą domenę (różne porty),
|
|
* a cookies ignorują porty — bez własnej nazwy admin i SPA nadpisywałyby
|
|
* sobie nawzajem odświeżany token (podmiana tożsamości między panelami).
|
|
*/
|
|
export const REFRESH_COOKIE_ADMIN = 'fitos_admin_refresh';
|
|
|
|
export function signAccessToken(userId: string, tokenVersion: number): string {
|
|
return jwt.sign({ sub: userId, tv: tokenVersion, type: 'access' }, config.jwt.accessSecret, {
|
|
expiresIn: config.jwt.accessTtlSec,
|
|
});
|
|
}
|
|
|
|
export function signRefreshToken(userId: string, tokenVersion: number): string {
|
|
return jwt.sign({ sub: userId, tv: tokenVersion, type: 'refresh' }, config.jwt.refreshSecret, {
|
|
expiresIn: config.jwt.refreshTtlSec,
|
|
});
|
|
}
|
|
|
|
export function verifyAccessToken(token: string): TokenPayload {
|
|
const payload = jwt.verify(token, config.jwt.accessSecret) as TokenPayload;
|
|
if (payload.type !== 'access') throw new Error('invalid token type');
|
|
return payload;
|
|
}
|
|
|
|
export function verifyRefreshToken(token: string): TokenPayload {
|
|
const payload = jwt.verify(token, config.jwt.refreshSecret) as TokenPayload;
|
|
if (payload.type !== 'refresh') throw new Error('invalid token type');
|
|
return payload;
|
|
}
|