survey-webapp/SurveyBackend/SurveyBackend.Services/Services/AuthorizationService.cs
shept 55e82425a9 say NO to try-catch in controllers
- added ExceptionsMiddleware.cs
- added more Exception types
- removed all exceptions logic in controllers
2025-04-18 15:15:32 +05:00

43 lines
No EOL
1.3 KiB
C#

using SurveyBackend.Core.Models;
using SurveyBackend.Core.Services;
using SurveyBackend.Services.Exceptions;
using SurveyBackend.Services.Helpers;
namespace SurveyBackend.Services.Services;
public class AuthorizationService : IAuthorizationService
{
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 (!_passwordHasher.Verify(password, user.Password))
{
throw new UnauthorizedException("Password is incorrect.");
}
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 ConflictException("Email already exists");
}
user.Password = _passwordHasher.HashPassword(user.Password);
await _userService.CreateUserAsync(user);
}
}