registration and authorization

This commit is contained in:
Вячеслав 2025-04-17 01:06:08 +05:00
parent 2b5f468b84
commit 4423dc360f
12 changed files with 136 additions and 6 deletions

View file

@ -13,7 +13,7 @@ public class ApplicationDbContext : SurveyDbContext
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
Database.EnsureCreated();
}
protected override void OnModelCreating(ModelBuilder modelBuilder)

View file

@ -41,4 +41,9 @@ public class UserRepository : IUserRepository
_context.Users.Remove(entity);
await _context.SaveChangesAsync();
}
public async Task<User?> GetUserByEmail(string email)
{
return await _context.Users.FirstOrDefaultAsync(u => u.Email == email);
}
}

View file

@ -0,0 +1,42 @@
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);
}
}

View file

@ -1,7 +0,0 @@
namespace SurveyBackend.Infrastructure.Services;
public interface IPasswordHasher
{
public string HashPassword(string password);
public bool Verify(string password, string hashedPassword);
}

View file

@ -1,4 +1,5 @@
using System.Security.Cryptography;
using SurveyBackend.Core.Services;
namespace SurveyBackend.Infrastructure.Services;

View file

@ -0,0 +1,25 @@
using SurveyBackend.Core.Models;
using SurveyBackend.Core.Repositories;
using SurveyBackend.Core.Services;
namespace SurveyBackend.Infrastructure.Services;
public class UserService : IUserService
{
private readonly IUserRepository _userRepository;
public UserService(IUserRepository userRepository)
{
_userRepository = userRepository;
}
public async Task<User?> GetUserByEmail(string email)
{
return await _userRepository.GetUserByEmail(email);
}
public async Task CreateUserAsync(User user)
{
await _userRepository.AddAsync(user);
}
}