2020-10-25 16:15:06 +01:00
|
|
|
|
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;
|
2020-10-25 16:15:06 +01:00
|
|
|
|
using static Birdmap.Common.PasswordHelper;
|
2020-10-21 17:04:54 +02:00
|
|
|
|
|
2020-10-24 23:23:22 +02:00
|
|
|
|
namespace Birdmap.BLL.Services
|
2020-10-21 17:04:54 +02:00
|
|
|
|
{
|
|
|
|
|
public class AuthService : IAuthService
|
|
|
|
|
{
|
2020-10-25 16:15:06 +01:00
|
|
|
|
private readonly IUserService _userService;
|
2020-10-21 17:04:54 +02:00
|
|
|
|
|
2020-10-25 16:15:06 +01:00
|
|
|
|
public AuthService(IUserService userService)
|
2020-10-21 17:04:54 +02:00
|
|
|
|
{
|
2020-10-25 16:15:06 +01:00
|
|
|
|
_userService = userService;
|
2020-10-21 17:04:54 +02:00
|
|
|
|
}
|
|
|
|
|
|
2020-10-24 23:23:22 +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.");
|
|
|
|
|
|
2020-10-24 23:23:22 +02:00
|
|
|
|
return AuthenticateUserInternalAsync(username, password);
|
|
|
|
|
}
|
|
|
|
|
|
2020-10-25 16:15:06 +01:00
|
|
|
|
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);
|
|
|
|
|
}
|
|
|
|
|
|
2020-10-24 23:23:22 +02:00
|
|
|
|
private async Task<User> AuthenticateUserInternalAsync(string username, string password)
|
|
|
|
|
{
|
2020-10-25 16:15:06 +01:00
|
|
|
|
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;
|
|
|
|
|
}
|
|
|
|
|
|
2020-10-25 16:15:06 +01:00
|
|
|
|
private Task<User> RegisterUserInternalAsync(string username, string password)
|
2020-10-21 17:04:54 +02:00
|
|
|
|
{
|
2020-10-25 16:15:06 +01:00
|
|
|
|
CreatePasswordHash(password, out var hash, out var salt);
|
|
|
|
|
var user = new User
|
2020-10-21 17:04:54 +02:00
|
|
|
|
{
|
2020-10-25 16:15:06 +01:00
|
|
|
|
Name = username,
|
2020-10-21 17:04:54 +02:00
|
|
|
|
PasswordHash = hash,
|
|
|
|
|
PasswordSalt = salt,
|
2020-10-25 16:15:06 +01:00
|
|
|
|
Role = Roles.User,
|
|
|
|
|
};
|
2020-10-21 17:04:54 +02:00
|
|
|
|
|
2020-10-25 16:15:06 +01:00
|
|
|
|
return _userService.CreateUserAsync(user);
|
2020-10-21 17:04:54 +02:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|