87 lines
2.7 KiB
C#
87 lines
2.7 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.Register;
|
|
using AMREZ.EOP.Domain.Entities.Authentications;
|
|
using AMREZ.EOP.Domain.Shared._Users;
|
|
using Microsoft.AspNetCore.Http;
|
|
|
|
namespace AMREZ.EOP.Application.UseCases.Authentications;
|
|
|
|
public sealed class RegisterUseCase : IRegisterUseCase
|
|
{
|
|
private readonly ITenantResolver _tenantResolver;
|
|
private readonly IUnitOfWork _uow;
|
|
private readonly IUserRepository _users;
|
|
private readonly ITenantRepository _tenants;
|
|
private readonly IPasswordHasher _hasher;
|
|
private readonly IHttpContextAccessor _http;
|
|
|
|
public RegisterUseCase(
|
|
ITenantResolver resolver,
|
|
IUnitOfWork uow,
|
|
IUserRepository users,
|
|
ITenantRepository tenants,
|
|
IPasswordHasher hasher,
|
|
IHttpContextAccessor http)
|
|
{
|
|
_tenantResolver = resolver;
|
|
_uow = uow;
|
|
_users = users;
|
|
_tenants = tenants;
|
|
_hasher = hasher;
|
|
_http = http;
|
|
}
|
|
|
|
public async Task<RegisterResponse?> ExecuteAsync(RegisterRequest 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;
|
|
|
|
var emailNorm = request.Email.Trim().ToLowerInvariant();
|
|
|
|
await _uow.BeginAsync(tenant, IsolationLevel.ReadCommitted, ct);
|
|
try
|
|
{
|
|
if (await _users.EmailExistsAsync(emailNorm, ct))
|
|
{
|
|
await _uow.RollbackAsync(ct);
|
|
return null;
|
|
}
|
|
|
|
var hash = _hasher.Hash(request.Password);
|
|
|
|
var tn = await _tenants.GetAsync(request.Tenant);
|
|
|
|
var user = new User
|
|
{
|
|
TenantId = tn.TenantId,
|
|
PasswordHash = hash,
|
|
IsActive = true,
|
|
};
|
|
|
|
user.Identities.Add(new UserIdentity
|
|
{
|
|
TenantId = tn.TenantId,
|
|
Type = IdentityType.Email,
|
|
Identifier = emailNorm,
|
|
IsPrimary = true,
|
|
VerifiedAt = null
|
|
});
|
|
|
|
await _users.AddAsync(user, ct);
|
|
await _uow.CommitAsync(ct);
|
|
|
|
return new RegisterResponse(user.Id, string.Empty, emailNorm, tenant.Id);
|
|
}
|
|
catch
|
|
{
|
|
await _uow.RollbackAsync(ct);
|
|
throw;
|
|
}
|
|
}
|
|
} |