import { Injectable } from '@nestjs/common'; import { JwtService } from '@nestjs/jwt'; import { LdapService } from '../ldap/ldap.service'; import { UsersCache } from '../users/users.cache'; import type { DecodedToken, TokenPayload } from './types/jwt'; @Injectable() export class AuthService { constructor( private readonly ldapService: LdapService, private readonly usersCache: UsersCache, private readonly jwtService: JwtService ) {} public async login(login: string, password: string) { const { displayName, department, title, mail, sAMAccountName: username, } = await this.ldapService.authenticate(login, password); const user = { username, domain: process.env.domain, displayName, department, position: title, mail, domainName: `${process.env.domain}\\${username}`, }; await this.usersCache.addUser(username, user); const payload: TokenPayload = { username, domain: process.env.domain, }; return this.jwtService.sign(payload); } public async logout(token: string) { const { username } = this.jwtService.decode(token) as DecodedToken; await this.usersCache.deleteUser(username); } public checkToken(token: string) { this.jwtService.verify(token); } public refreshToken(token: string) { const { exp, iat, ...payload } = this.jwtService.decode(token) as DecodedToken; return this.jwtService.sign(payload); } }