import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import * as argon2 from 'argon2'; import { Repository } from 'typeorm'; import { AccountsEntity } from '../../database/connections/ebitemp-api/entities'; import { EBITEMP_API_DATASOURCE } from '../../database/connections/ebitemp-api/database.constants'; @Injectable() export class UsersAuthService { constructor( @InjectRepository(AccountsEntity, EBITEMP_API_DATASOURCE) private readonly accountsRepository: Repository ) {} async getUserById(accountId: number) { return await this.accountsRepository.findOne({ relations: { profili: { ruolo: true } }, where: { id: accountId }, }); } async getUserByUsername(username: string) { return await this.accountsRepository.findOne({ relations: { profili: { ruolo: true } }, where: { username: username }, }); } async getUserByIdAndRefreshTokenPair(accountId: number, refreshToken: string) { const accountById = await this.getUserById(accountId); if (!accountById?.ultimoHashRefreshToken) return null; const isRefreshTokenMatching = await argon2.verify(accountById.ultimoHashRefreshToken, refreshToken); return isRefreshTokenMatching ? accountById : null; } async setCurrentRefreshTokenHash(accountId: number, refreshToken: string | null) { const hash = refreshToken ? await argon2.hash(refreshToken) : null; await this.accountsRepository.update(accountId, { ultimoHashRefreshToken: hash, }); } }