UNPKG

@bitblit/ratchet-common

Version:

Common tools for general use

36 lines 1.68 kB
import { Logger } from '../logger/logger.js'; import { DurationRatchet } from '../lang/duration-ratchet.js'; export class JwtPayloadExpirationRatchet { static EXPIRED_FLAG_NAME = '__jwtServiceExpiredFlag'; static processPayloadExpiration(payload, expiredHandling) { if (payload) { const nowSeconds = Math.floor(Date.now() / 1000); const expSeconds = payload?.exp && payload.exp > nowSeconds * 100 ? Math.floor(payload.exp / 1000) : payload?.exp; const nbfSeconds = payload?.nbf && payload.nbf > nowSeconds * 100 ? Math.floor(payload.nbf / 1000) : payload?.nbf; if ((expSeconds && nowSeconds >= expSeconds) || (nbfSeconds && nowSeconds <= nbfSeconds)) { const age = nowSeconds - expSeconds; Logger.debug('JWT token expired or before NBF : on %d, %s ago', payload.exp, DurationRatchet.formatMsDuration(age * 1000)); switch (expiredHandling) { case 1: throw new Error('JWT Token was expired'); case 2: payload[JwtPayloadExpirationRatchet.EXPIRED_FLAG_NAME] = true; break; default: payload = null; break; } } } return payload; } static hasExpiredFlag(ob) { return ob && ob[JwtPayloadExpirationRatchet.EXPIRED_FLAG_NAME] === true; } static removeExpiredFlag(ob) { if (ob) { delete ob[JwtPayloadExpirationRatchet.EXPIRED_FLAG_NAME]; } } } //# sourceMappingURL=jwt-payload-expiration-ratchet.js.map