import jwt from 'jsonwebtoken' /** * Represents the response of a JWT validation. * @typedef {Object} JWTValidationResponse * @property {boolean} isValid - Indicates whether the JWT is valid or not. * @property {jwt.JwtPayload} [decodedToken] - The decoded JWT payload if the JWT is valid. * @property {boolean} [isExpired] - Indicates whether the JWT is expired or not, only present if isValid is false. */ type JWTValidationResponse = | { isValid: true; decodedToken: jwt.JwtPayload } | { isValid: false isExpired?: boolean } /** * Represents a JSON Web Token (JWT) utility class. */ export default class JWT { /** * The secret key used for generating and verifying tokens. * @type {string} */ private readonly tokenSecret: string /** * The default expiration time for a cache entry. * @type {string} */ private readonly defaultExpiration?: string /** * Constructs a new instance of the class. * @param {string} tokenSecret - The secret used to sign the tokens. * @param {string} [defaultExpiration] - The default expiration time for the tokens. * @returns None */ constructor(tokenSecret: string, defaultExpiration?: string) { this.tokenSecret = tokenSecret this.defaultExpiration = defaultExpiration } /** * Creates a JSON Web Token (JWT) using the provided data and options. * @param {object} data - The data to be included in the token payload. * @param {string} [expiration] - The expiration time for the token. If not provided, the default expiration time will be used. * @param {string} [overrideToken] - An optional token secret to override the default token secret. * @param {any} [opts] - Additional options to be passed to the jwt.sign() function. * @returns {string} - The generated JWT. */ public createToken( data: object, expiration?: string, overrideToken?: string, opts?: any ): string { const exp = expiration || this.defaultExpiration return jwt.sign( data, overrideToken || this.tokenSecret, exp ? { expiresIn: exp, ...(opts || {}) } : opts || {} ) } /** * Validates a JSON Web Token (JWT) and returns the validation response. * @param {string} token - The JWT to validate. * @returns {JWTValidationResponse} - The validation response object. */ public validateToken(token: string): JWTValidationResponse { try { // Check if is valid const isValid = jwt.verify(token, this.tokenSecret) if (isValid) { const payload = jwt.decode(token, { json: true }) if (payload) return { isValid: true, decodedToken: payload } } } catch (err) { console.error(err) if (err instanceof jwt.TokenExpiredError) return { isValid: false, isExpired: true } } return { isValid: false } } }