Result classes can derive when new instance is created.

This commit is contained in:
max
2024-10-14 03:20:44 +02:00
parent 0fed89e140
commit 17f69824eb
5 changed files with 93 additions and 29 deletions

View File

@@ -1,5 +1,6 @@
using DotBased.ASP.Auth.Domains;
using DotBased.ASP.Auth.Domains.Auth;
using DotBased.ASP.Auth.Domains.Identity;
using DotBased.Extensions;
using DotBased.Logging;
@@ -7,22 +8,44 @@ namespace DotBased.ASP.Auth.Services;
public class AuthService
{
public AuthService(AuthDataCache dataCache)
public AuthService(IAuthDataRepository authDataRepository, AuthDataCache dataCache)
{
_authDataRepository = authDataRepository;
_dataCache = dataCache;
_logger = LogService.RegisterLogger(typeof(AuthService));
}
private readonly IAuthDataRepository _authDataRepository;
private readonly AuthDataCache _dataCache;
private readonly ILogger _logger;
public async Task<Result<AuthenticationStateModel>> LoginAsync(LoginModel login)
{
if (login.UserName.IsNullOrWhiteSpace())
return Result<AuthenticationStateModel>.Failed("Username argument is empty!");
//var userResult = await _dataProvider.GetUserAsync(string.Empty, login.Email, login.UserName);
//TODO: validate user password and create a session state
return Result<AuthenticationStateModel>.Failed("");
UserModel? user = null;
Result<UserModel> usrResult;
if (!login.UserName.IsNullOrWhiteSpace())
{
usrResult = await _authDataRepository.GetUserAsync(string.Empty, string.Empty, login.UserName);
if (usrResult is { Success: true, Value: not null })
user = usrResult.Value;
}
else if (!login.Email.IsNullOrWhiteSpace())
{
usrResult = await _authDataRepository.GetUserAsync(string.Empty, login.Email, string.Empty);
if (usrResult is { Success: true, Value: not null })
user = usrResult.Value;
}
else
return Result<AuthenticationStateModel>.Failed("Username & Email is empty, cannot login!");
if (user == null || !usrResult.Success)
return new Result<AuthenticationStateModel>(usrResult);
if (user.PasswordHash != login.Password) //TODO: Hash password and compare
return Result<AuthenticationStateModel>.Failed("Login failed, invalid password.");
var state = new AuthenticationStateModel(user);
await _authDataRepository.CreateAuthenticationStateAsync(state);
return Result<AuthenticationStateModel>.Ok(state);
}
public async Task<Result> Logout(string state)