51 lines
2.0 KiB
C#
51 lines
2.0 KiB
C#
using System.Data;
|
|
using AMREZ.EOP.Abstractions.Applications.Tenancy;
|
|
using AMREZ.EOP.Abstractions.Applications.UseCases.Authentications;
|
|
using AMREZ.EOP.Abstractions.Infrastructures.Common;
|
|
using AMREZ.EOP.Abstractions.Infrastructures.Repositories;
|
|
using AMREZ.EOP.Abstractions.Security;
|
|
using AMREZ.EOP.Contracts.DTOs.Authentications.Login;
|
|
using Microsoft.AspNetCore.Http;
|
|
|
|
namespace AMREZ.EOP.Application.UseCases.Authentications;
|
|
|
|
public sealed class LoginUseCase : ILoginUseCase
|
|
{
|
|
private readonly ITenantResolver _tenantResolver;
|
|
private readonly IUserRepository _users;
|
|
private readonly IPasswordHasher _hasher;
|
|
private readonly IHttpContextAccessor _http;
|
|
private readonly IUnitOfWork _uow;
|
|
|
|
public LoginUseCase(ITenantResolver r, IUserRepository u, IPasswordHasher h, IHttpContextAccessor http, IUnitOfWork uow)
|
|
{ _tenantResolver = r; _users = u; _hasher = h; _http = http; _uow = uow; }
|
|
|
|
public async Task<LoginResponse?> ExecuteAsync(LoginRequest request, CancellationToken ct = default)
|
|
{
|
|
var http = _http.HttpContext ?? throw new InvalidOperationException("No HttpContext");
|
|
var tenant = _tenantResolver.Resolve(http, request);
|
|
if (tenant is null) return null;
|
|
|
|
await _uow.BeginAsync(tenant, IsolationLevel.ReadCommitted, ct);
|
|
try
|
|
{
|
|
var email = request.Email.Trim().ToLowerInvariant();
|
|
var user = await _users.FindActiveByEmailAsync(email, ct);
|
|
if (user is null || !_hasher.Verify(request.Password, user.PasswordHash))
|
|
{
|
|
await _uow.RollbackAsync(ct);
|
|
return null;
|
|
}
|
|
|
|
await _uow.CommitAsync(ct);
|
|
|
|
// NOTE: ไม่ใช้ DisplayName ใน Entity แล้ว — ส่งกลับเป็นค่าว่าง/ไปดึงจาก HR ฝั่ง API
|
|
return new LoginResponse(user.Id, string.Empty, email, tenant.Id);
|
|
}
|
|
catch
|
|
{
|
|
await _uow.RollbackAsync(ct);
|
|
throw;
|
|
}
|
|
}
|
|
} |