This repository has been archived on 2025-03-21. You can view files and clone it, but cannot push or open issues or pull requests.
insiemesalute-3p-nx/apps/ebitemp-api/src/modules/auth/users/users-auth.service.ts

44 lines
1.5 KiB
TypeScript

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<AccountsEntity>
) {}
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,
});
}
}