Evo.Auth/apps/api/src/auth/auth.service.ts
2022-11-28 19:46:51 +03:00

58 lines
1.5 KiB
TypeScript

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.LDAP_DOMAIN,
displayName,
department,
position: title,
mail,
domainName: `${process.env.LDAP_DOMAIN}\\${username}`,
};
await this.usersCache.addUser(username, user);
const payload: TokenPayload = {
username,
domain: process.env.LDAP_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);
}
}