birbmap/Birdmap.BLL/Services/AuthService.cs

61 lines
1.9 KiB
C#
Raw Normal View History

using Birdmap.BLL.Interfaces;
using Birdmap.DAL.Entities;
2020-10-21 17:04:54 +02:00
using System;
using System.Security.Authentication;
using System.Threading.Tasks;
using static Birdmap.Common.PasswordHelper;
2020-10-21 17:04:54 +02:00
namespace Birdmap.BLL.Services
2020-10-21 17:04:54 +02:00
{
public class AuthService : IAuthService
{
private readonly IUserService _userService;
2020-10-21 17:04:54 +02:00
public AuthService(IUserService userService)
2020-10-21 17:04:54 +02:00
{
_userService = userService;
2020-10-21 17:04:54 +02:00
}
public Task<User> AuthenticateUserAsync(string username, string password)
2020-10-21 17:04:54 +02:00
{
if (string.IsNullOrWhiteSpace(username) || string.IsNullOrEmpty(password))
throw new ArgumentException("Username or password cannot be null or empty.");
return AuthenticateUserInternalAsync(username, password);
}
public Task<User> RegisterUserAsync(string username, string password)
{
if (string.IsNullOrWhiteSpace(username) || string.IsNullOrEmpty(password))
throw new ArgumentException("Username or password cannot be null or empty.");
return RegisterUserInternalAsync(username, password);
}
private async Task<User> AuthenticateUserInternalAsync(string username, string password)
{
var user = await _userService.GetUserAsync(username)
2020-10-21 17:04:54 +02:00
?? throw new AuthenticationException();
if (!VerifyPasswordHash(password, user.PasswordHash, user.PasswordSalt))
throw new AuthenticationException();
return user;
}
private Task<User> RegisterUserInternalAsync(string username, string password)
2020-10-21 17:04:54 +02:00
{
CreatePasswordHash(password, out var hash, out var salt);
var user = new User
2020-10-21 17:04:54 +02:00
{
Name = username,
2020-10-21 17:04:54 +02:00
PasswordHash = hash,
PasswordSalt = salt,
Role = Roles.User,
};
2020-10-21 17:04:54 +02:00
return _userService.CreateUserAsync(user);
2020-10-21 17:04:54 +02:00
}
}
}