homelab-personal-cloud/core/src/http/mvc/login/state-manager.service.ts

41 lines
1.2 KiB
TypeScript

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<string> {
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<boolean> {
return this.cacheService.exists(getStateKey(jwi));
}
}