UNPKG

@nxtoai/jwtette

Version:

JWT authentication package for NxtoAI microservices

43 lines (35 loc) 1.76 kB
import { Injectable } from '@nestjs/common'; import { GatiService } from '@nxtoai/gati'; @Injectable() export class JwtHelper { private readonly TOKEN_PREFIX = 'token:'; private readonly USER_TOKEN_PREFIX = 'user_token:'; private readonly TOKEN_EXPIRY = 24 * 60 * 60; // 24 hours in seconds constructor(private readonly gati: GatiService) {} async cacheToken(token: string, userid: string): Promise<void> { await this.gati.put(`${this.TOKEN_PREFIX}${token}`, { value: userid }, { ttl: this.TOKEN_EXPIRY }); await this.gati.put(`${this.USER_TOKEN_PREFIX}${userid}`, { value: token }, { ttl: this.TOKEN_EXPIRY }); } async getTokenUser(token: string): Promise<string | null> { const cachedUser = await this.gati.get(`${this.TOKEN_PREFIX}${token}`); return cachedUser?.value && typeof cachedUser.value === 'string' ? cachedUser.value : null; } async getUserToken(userid: string): Promise<string | null> { const cachedToken = await this.gati.get(`${this.USER_TOKEN_PREFIX}${userid}`); return cachedToken?.value && typeof cachedToken.value === 'string' ? cachedToken.value : null; } async invalidateToken(token: string): Promise<void> { const userid = await this.getTokenUser(token); if (userid) { await this.gati.remove(`${this.USER_TOKEN_PREFIX}${userid}`); } await this.gati.remove(`${this.TOKEN_PREFIX}${token}`); } async invalidateUserToken(userid: string): Promise<void> { const token = await this.getUserToken(userid); if (token) { await this.gati.remove(`${this.TOKEN_PREFIX}${token}`); } await this.gati.remove(`${this.USER_TOKEN_PREFIX}${userid}`); } }