42 lines
No EOL
1.2 KiB
C#
42 lines
No EOL
1.2 KiB
C#
using SurveyBackend.Core.Models;
|
|
using SurveyBackend.Core.Services;
|
|
using SurveyBackend.Infrastructure.Helpers;
|
|
|
|
namespace SurveyBackend.Infrastructure.Services;
|
|
|
|
public class AuthorizationService
|
|
{
|
|
private readonly IUserService _userService;
|
|
private readonly IPasswordHasher _passwordHasher;
|
|
|
|
public AuthorizationService(IUserService userService, IPasswordHasher passwordHasher)
|
|
{
|
|
_userService = userService;
|
|
_passwordHasher = passwordHasher;
|
|
}
|
|
|
|
public async Task<string?> LogInUser(string email, string password)
|
|
{
|
|
var user = await _userService.GetUserByEmail(email);
|
|
if (user is null || !_passwordHasher.Verify(password, user.Password))
|
|
{
|
|
return null;
|
|
}
|
|
|
|
var token = TokenHelper.GetAuthToken(user);
|
|
return token;
|
|
}
|
|
|
|
public async Task RegisterUser(User user)
|
|
{
|
|
var existingUser = await _userService.GetUserByEmail(user.Email);
|
|
if (existingUser is not null)
|
|
{
|
|
throw new Exception("Email already exists");
|
|
}
|
|
|
|
user.Password = _passwordHasher.HashPassword(user.Password);
|
|
|
|
await _userService.CreateUserAsync(user);
|
|
}
|
|
} |