import { Injectable } from '@nestjs/common'; import { randomUUID } from 'node:crypto'; import { CacheService } from '../../../cache/cache.service'; import { TokenManagementService } from '../../../token-management/token-management.service'; import { DateUtil } from '../../../utils'; import { State } from './login.types'; const getStateKey = (jwi: string) => `login:state:${jwi}`; @Injectable() export class StateManagerService { constructor( private readonly tokenService: TokenManagementService, private readonly cacheService: CacheService, ) {} async getNewState(): Promise { const date = DateUtil.fromDate(new Date()).addNMinutes(15); const stateObj: State = { jwi: randomUUID(), exp: date.seconds, tfa: false, } await this.cacheService.set(getStateKey(stateObj.jwi), new Date().toISOString(), date.toDate().getTime()); return this.tokenService.createToken(stateObj); } updateState(state: State, dto: { tfa?: boolean } = {}): string { return this.tokenService.createToken({ ...state, ...dto }); } async isStateActive(jwi: string): Promise { return this.cacheService.exists(getStateKey(jwi)); } }