Fixes
This commit is contained in:
@@ -1,8 +1,9 @@
|
|||||||
using AipsCore.Domain.Models.User;
|
using AipsCore.Domain.Models.User;
|
||||||
|
using AipsCore.Domain.Models.User.External;
|
||||||
|
|
||||||
namespace AipsCore.Application.Abstract.UserContext;
|
namespace AipsCore.Application.Abstract.UserContext;
|
||||||
|
|
||||||
public interface ITokenProvider
|
public interface ITokenProvider
|
||||||
{
|
{
|
||||||
string Generate(User user, IList<string> roles);
|
string Generate(User user, IList<UserRole> roles);
|
||||||
}
|
}
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
namespace AipsCore.Application.Authentication;
|
|
||||||
|
|
||||||
public record Token(string Value);
|
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
using AipsCore.Domain.Models.User;
|
||||||
|
|
||||||
|
namespace AipsCore.Application.Common.Authentication;
|
||||||
|
|
||||||
|
public interface IAuthService
|
||||||
|
{
|
||||||
|
Task SignUpWithPasswordAsync(User user, string password, CancellationToken cancellationToken = default);
|
||||||
|
Task<LoginResult> LoginWithEmailAndPasswordAsync(string email, string password, CancellationToken cancellationToken = default);
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
using AipsCore.Domain.Models.User;
|
||||||
|
using AipsCore.Domain.Models.User.External;
|
||||||
|
|
||||||
|
namespace AipsCore.Application.Common.Authentication;
|
||||||
|
|
||||||
|
public record LoginResult(User User, IList<UserRole> Roles);
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
namespace AipsCore.Application.Common.Authentication;
|
||||||
|
|
||||||
|
public record Token(string Value);
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
using AipsCore.Application.Abstract.Command;
|
using AipsCore.Application.Abstract.Command;
|
||||||
using AipsCore.Application.Authentication;
|
using AipsCore.Application.Common.Authentication;
|
||||||
|
|
||||||
namespace AipsCore.Application.Models.User.Command.LogIn;
|
namespace AipsCore.Application.Models.User.Command.LogIn;
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
using AipsCore.Application.Abstract.Command;
|
using AipsCore.Application.Abstract.Command;
|
||||||
using AipsCore.Application.Abstract.UserContext;
|
using AipsCore.Application.Abstract.UserContext;
|
||||||
using AipsCore.Application.Authentication;
|
using AipsCore.Application.Common.Authentication;
|
||||||
using AipsCore.Domain.Abstract;
|
using AipsCore.Domain.Abstract;
|
||||||
using AipsCore.Domain.Models.User.External;
|
using AipsCore.Domain.Models.User.External;
|
||||||
|
|
||||||
@@ -10,18 +10,18 @@ public class LogInUserCommandHandler : ICommandHandler<LogInUserCommand, Token>
|
|||||||
{
|
{
|
||||||
private readonly IUserRepository _userRepository;
|
private readonly IUserRepository _userRepository;
|
||||||
private readonly ITokenProvider _tokenProvider;
|
private readonly ITokenProvider _tokenProvider;
|
||||||
private readonly IUnitOfWork _unitOfWork;
|
private readonly IAuthService _authService;
|
||||||
|
|
||||||
public LogInUserCommandHandler(IUserRepository userRepository, ITokenProvider tokenProvider, IUnitOfWork unitOfWork)
|
public LogInUserCommandHandler(IUserRepository userRepository, ITokenProvider tokenProvider, IAuthService authService)
|
||||||
{
|
{
|
||||||
_userRepository = userRepository;
|
_userRepository = userRepository;
|
||||||
_tokenProvider = tokenProvider;
|
_tokenProvider = tokenProvider;
|
||||||
_unitOfWork = unitOfWork;
|
_authService = authService;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<Token> Handle(LogInUserCommand command, CancellationToken cancellationToken = default)
|
public async Task<Token> Handle(LogInUserCommand command, CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
var loginResult = await _userRepository.LoginWithEmailAndPasswordAsync(command.Email, command.Password, cancellationToken);
|
var loginResult = await _authService.LoginWithEmailAndPasswordAsync(command.Email, command.Password, cancellationToken);
|
||||||
|
|
||||||
return new Token(_tokenProvider.Generate(loginResult.User, loginResult.Roles));
|
return new Token(_tokenProvider.Generate(loginResult.User, loginResult.Roles));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
using AipsCore.Application.Abstract.Command;
|
using AipsCore.Application.Abstract.Command;
|
||||||
|
using AipsCore.Application.Common.Authentication;
|
||||||
using AipsCore.Domain.Abstract;
|
using AipsCore.Domain.Abstract;
|
||||||
using AipsCore.Domain.Models.User.External;
|
using AipsCore.Domain.Models.User.External;
|
||||||
using AipsCore.Domain.Models.User.ValueObjects;
|
using AipsCore.Domain.Models.User.ValueObjects;
|
||||||
@@ -8,19 +9,19 @@ namespace AipsCore.Application.Models.User.Command.SignUp;
|
|||||||
public class SignUpUserCommandHandler : ICommandHandler<SignUpUserCommand, UserId>
|
public class SignUpUserCommandHandler : ICommandHandler<SignUpUserCommand, UserId>
|
||||||
{
|
{
|
||||||
private readonly IUserRepository _userRepository;
|
private readonly IUserRepository _userRepository;
|
||||||
private readonly IUnitOfWork _unitOfWork;
|
private readonly IAuthService _authService;
|
||||||
|
|
||||||
public SignUpUserCommandHandler(IUserRepository userRepository, IUnitOfWork unitOfWork)
|
public SignUpUserCommandHandler(IUserRepository userRepository, IAuthService authService)
|
||||||
{
|
{
|
||||||
_userRepository = userRepository;
|
_userRepository = userRepository;
|
||||||
_unitOfWork = unitOfWork;
|
_authService = authService;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<UserId> Handle(SignUpUserCommand command, CancellationToken cancellationToken = default)
|
public async Task<UserId> Handle(SignUpUserCommand command, CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
var user = Domain.Models.User.User.Create(command.Email, command.Username);
|
var user = Domain.Models.User.User.Create(command.Email, command.Username);
|
||||||
|
|
||||||
await _userRepository.SignUpWithPasswordAsync(user, command.Password, cancellationToken);
|
await _authService.SignUpWithPasswordAsync(user, command.Password, cancellationToken);
|
||||||
|
|
||||||
return user.Id;
|
return user.Id;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,5 @@ namespace AipsCore.Domain.Models.User.External;
|
|||||||
|
|
||||||
public interface IUserRepository : IAbstractRepository<User, UserId>
|
public interface IUserRepository : IAbstractRepository<User, UserId>
|
||||||
{
|
{
|
||||||
Task SignUpWithPasswordAsync(User user, string password, CancellationToken cancellationToken = default);
|
|
||||||
Task<LoginResult> LoginWithEmailAndPasswordAsync(string email, string password, CancellationToken cancellationToken = default);
|
|
||||||
}
|
}
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
namespace AipsCore.Domain.Models.User.External;
|
|
||||||
|
|
||||||
public record LoginResult(User User, IList<string> Roles);
|
|
||||||
@@ -17,10 +17,8 @@ public record UserRole
|
|||||||
|
|
||||||
public static IEnumerable<UserRole> All() => [User, Admin];
|
public static IEnumerable<UserRole> All() => [User, Admin];
|
||||||
|
|
||||||
public static UserRole FromString(string name)
|
public static UserRole? FromString(string name)
|
||||||
{
|
{
|
||||||
var role = All().FirstOrDefault(r => r.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
|
return All().FirstOrDefault(r => r.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
|
||||||
|
|
||||||
return role ?? throw new ValidationException(UserErrors.RoleDoesNotExist(name));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
namespace AipsCore.Domain.Models.User.Options;
|
||||||
|
|
||||||
|
public static partial class UserOptionsDefaults
|
||||||
|
{
|
||||||
|
public const int PasswordRequiredLength = 8;
|
||||||
|
public const bool PasswordRequireDigit = true;
|
||||||
|
public const bool PasswordRequireLowercase = true;
|
||||||
|
public const bool PasswordRequireUppercase = true;
|
||||||
|
public const bool PasswordRequireNonAlphanumeric = true;
|
||||||
|
|
||||||
|
public const bool UserRequireUniqueEmail = true;
|
||||||
|
}
|
||||||
@@ -7,18 +7,10 @@ namespace AipsCore.Domain.Models.User.Validation;
|
|||||||
|
|
||||||
public class UserErrors : AbstractErrors<User, UserId>
|
public class UserErrors : AbstractErrors<User, UserId>
|
||||||
{
|
{
|
||||||
public static ValidationError LoginErrorUserNotFoundByEmail(string email)
|
public static ValidationError InvalidCredentials()
|
||||||
{
|
{
|
||||||
string code = "login_error_user_not_found_by_email";
|
string code = "invalid_credentials";
|
||||||
string message = $"User with email '{email}' not found";
|
string message = "Invalid credentials";
|
||||||
|
|
||||||
return CreateValidationError(code, message);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static ValidationError LoginErrorIncorrectPassword()
|
|
||||||
{
|
|
||||||
string code = "login_error_incorrect_password";
|
|
||||||
string message = $"Incorrect password provided";
|
|
||||||
|
|
||||||
return CreateValidationError(code, message);
|
return CreateValidationError(code, message);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,20 +6,65 @@ public static class ConfigurationEnvExtensions
|
|||||||
{
|
{
|
||||||
private const string DbConnStringKey = "DB_CONN_STRING";
|
private const string DbConnStringKey = "DB_CONN_STRING";
|
||||||
|
|
||||||
public static string GetEnvConnectionString(this IConfiguration configuration)
|
private const string JwtIssuer = "JWT_ISSUER";
|
||||||
{
|
private const string JwtAudience = "JWT_AUDIENCE";
|
||||||
return configuration.GetEnvForSure(DbConnStringKey);
|
private const string JwtKey = "JWT_KEY";
|
||||||
}
|
private const string JwtExpirationMinutes = "JWT_EXPIRATION_MINUTES";
|
||||||
|
|
||||||
private static string GetEnvForSure(this IConfiguration configuration, string key)
|
extension(IConfiguration configuration)
|
||||||
{
|
{
|
||||||
var value = configuration[key];
|
public string GetEnvConnectionString()
|
||||||
|
|
||||||
if (value is null)
|
|
||||||
{
|
{
|
||||||
throw new ConfigurationException(key);
|
return configuration.GetEnvForSure(DbConnStringKey);
|
||||||
}
|
}
|
||||||
|
|
||||||
return value;
|
public string GetEnvJwtIssuer()
|
||||||
|
{
|
||||||
|
return configuration.GetEnvForSure(JwtIssuer);
|
||||||
|
}
|
||||||
|
|
||||||
|
public string GetEnvJwtAudience()
|
||||||
|
{
|
||||||
|
return configuration.GetEnvForSure(JwtAudience);
|
||||||
|
}
|
||||||
|
|
||||||
|
public string GetEnvJwtKey()
|
||||||
|
{
|
||||||
|
return configuration.GetEnvForSure(JwtKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
public int GetEnvJwtExpirationMinutes()
|
||||||
|
{
|
||||||
|
return configuration.GetEnvInt(configuration.GetEnvOrDefault(JwtExpirationMinutes, "60"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private string GetEnvForSure(string key)
|
||||||
|
{
|
||||||
|
var value = configuration[key];
|
||||||
|
|
||||||
|
if (value is null)
|
||||||
|
{
|
||||||
|
throw new ConfigurationException(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
private string GetEnvOrDefault(string key, string defaultValue)
|
||||||
|
{
|
||||||
|
return configuration.GetValue(key, defaultValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
private int GetEnvInt(string value)
|
||||||
|
{
|
||||||
|
if (int.TryParse(value, out var result))
|
||||||
|
{
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
throw new ConfigurationException($"Value '{value}' is not a valid integer.");
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
16
dotnet/AipsCore/Infrastructure/DI/StartupExtensions.cs
Normal file
16
dotnet/AipsCore/Infrastructure/DI/StartupExtensions.cs
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
using AipsCore.Infrastructure.Persistence.Db;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
|
||||||
|
namespace AipsCore.Infrastructure.DI;
|
||||||
|
|
||||||
|
public static class StartupExtensions
|
||||||
|
{
|
||||||
|
public static async Task InitializeInfrastructureAsync(this IServiceProvider services)
|
||||||
|
{
|
||||||
|
using var scope = services.CreateScope();
|
||||||
|
|
||||||
|
var serviceProvider = scope.ServiceProvider;
|
||||||
|
|
||||||
|
await DbInitializer.SeedRolesAsync(serviceProvider);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,8 @@
|
|||||||
using System.Text;
|
using System.Text;
|
||||||
using AipsCore.Application.Abstract.UserContext;
|
using AipsCore.Application.Abstract.UserContext;
|
||||||
|
using AipsCore.Application.Common.Authentication;
|
||||||
|
using AipsCore.Domain.Models.User.Options;
|
||||||
|
using AipsCore.Infrastructure.DI.Configuration;
|
||||||
using AipsCore.Infrastructure.Persistence.Authentication;
|
using AipsCore.Infrastructure.Persistence.Authentication;
|
||||||
using AipsCore.Infrastructure.Persistence.Db;
|
using AipsCore.Infrastructure.Persistence.Db;
|
||||||
using AipsCore.Infrastructure.Persistence.User;
|
using AipsCore.Infrastructure.Persistence.User;
|
||||||
@@ -17,10 +20,10 @@ public static class UserContextRegistrationExtension
|
|||||||
{
|
{
|
||||||
var jwtSettings = new JwtSettings
|
var jwtSettings = new JwtSettings
|
||||||
{
|
{
|
||||||
Issuer = configuration["JWT_ISSUER"]!,
|
Issuer = configuration.GetEnvJwtIssuer(),
|
||||||
Audience = configuration["JWT_AUDIENCE"]!,
|
Audience = configuration.GetEnvJwtAudience(),
|
||||||
Key = configuration["JWT_KEY"]!,
|
Key = configuration.GetEnvJwtKey(),
|
||||||
ExpirationMinutes = int.Parse(configuration["JWT_EXPIRATION_MINUTES"] ?? "60")
|
ExpirationMinutes = configuration.GetEnvJwtExpirationMinutes()
|
||||||
};
|
};
|
||||||
|
|
||||||
services.AddSingleton(jwtSettings);
|
services.AddSingleton(jwtSettings);
|
||||||
@@ -29,13 +32,13 @@ public static class UserContextRegistrationExtension
|
|||||||
|
|
||||||
services.AddIdentityCore<User>(options =>
|
services.AddIdentityCore<User>(options =>
|
||||||
{
|
{
|
||||||
options.Password.RequiredLength = 8;
|
options.Password.RequiredLength = UserOptionsDefaults.PasswordRequiredLength;
|
||||||
options.Password.RequireDigit = true;
|
options.Password.RequireDigit = UserOptionsDefaults.PasswordRequireDigit;
|
||||||
options.Password.RequireLowercase = true;
|
options.Password.RequireLowercase = UserOptionsDefaults.PasswordRequireLowercase;
|
||||||
options.Password.RequireUppercase = true;
|
options.Password.RequireUppercase = UserOptionsDefaults.PasswordRequireUppercase;
|
||||||
options.Password.RequireNonAlphanumeric = true;
|
options.Password.RequireNonAlphanumeric = UserOptionsDefaults.PasswordRequireNonAlphanumeric;
|
||||||
|
|
||||||
options.User.RequireUniqueEmail = true;
|
options.User.RequireUniqueEmail = UserOptionsDefaults.UserRequireUniqueEmail;
|
||||||
})
|
})
|
||||||
.AddRoles<IdentityRole<Guid>>()
|
.AddRoles<IdentityRole<Guid>>()
|
||||||
.AddEntityFrameworkStores<AipsDbContext>()
|
.AddEntityFrameworkStores<AipsDbContext>()
|
||||||
@@ -62,6 +65,7 @@ public static class UserContextRegistrationExtension
|
|||||||
|
|
||||||
services.AddTransient<IUserContext, HttpUserContext>();
|
services.AddTransient<IUserContext, HttpUserContext>();
|
||||||
services.AddTransient<ITokenProvider, JwtTokenProvider>();
|
services.AddTransient<ITokenProvider, JwtTokenProvider>();
|
||||||
|
services.AddTransient<IAuthService, EfAuthService>();
|
||||||
|
|
||||||
return services;
|
return services;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,64 @@
|
|||||||
|
using AipsCore.Application.Common.Authentication;
|
||||||
|
using AipsCore.Domain.Common.Validation;
|
||||||
|
using AipsCore.Domain.Models.User.External;
|
||||||
|
using AipsCore.Domain.Models.User.Validation;
|
||||||
|
using AipsCore.Infrastructure.Persistence.User.Mappers;
|
||||||
|
using Microsoft.AspNetCore.Identity;
|
||||||
|
|
||||||
|
namespace AipsCore.Infrastructure.Persistence.Authentication;
|
||||||
|
|
||||||
|
public class EfAuthService : IAuthService
|
||||||
|
{
|
||||||
|
private readonly UserManager<User.User> _userManager;
|
||||||
|
|
||||||
|
public EfAuthService(UserManager<User.User> userManager)
|
||||||
|
{
|
||||||
|
_userManager = userManager;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task SignUpWithPasswordAsync(Domain.Models.User.User user, string password, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
var entity = user.MapToEntity();
|
||||||
|
|
||||||
|
var result = await _userManager.CreateAsync(entity, password);
|
||||||
|
|
||||||
|
if (!result.Succeeded)
|
||||||
|
{
|
||||||
|
var errors = string.Join(", ", result.Errors.Select(e => e.Description));
|
||||||
|
throw new Exception($"User registration failed: {errors}");
|
||||||
|
}
|
||||||
|
|
||||||
|
await _userManager.AddToRoleAsync(entity, UserRole.User.Name);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<LoginResult> LoginWithEmailAndPasswordAsync(string email, string password, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
var entity = await _userManager.FindByEmailAsync(email);
|
||||||
|
|
||||||
|
if (entity is null)
|
||||||
|
{
|
||||||
|
throw new ValidationException(UserErrors.InvalidCredentials());
|
||||||
|
}
|
||||||
|
|
||||||
|
var isPasswordValid = await _userManager.CheckPasswordAsync(entity, password);
|
||||||
|
|
||||||
|
if (!isPasswordValid)
|
||||||
|
{
|
||||||
|
throw new ValidationException(UserErrors.InvalidCredentials());
|
||||||
|
}
|
||||||
|
|
||||||
|
var roles = new List<UserRole>();
|
||||||
|
var rolesNames = await _userManager.GetRolesAsync(entity);
|
||||||
|
|
||||||
|
foreach (var roleName in rolesNames)
|
||||||
|
{
|
||||||
|
var role = UserRole.FromString(roleName);
|
||||||
|
|
||||||
|
if (role is null) throw new Exception($"Role {roleName} not found");
|
||||||
|
|
||||||
|
roles.Add(role);
|
||||||
|
}
|
||||||
|
|
||||||
|
return new LoginResult(entity.MapToModel(), roles);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@ using System.IdentityModel.Tokens.Jwt;
|
|||||||
using System.Security.Claims;
|
using System.Security.Claims;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using AipsCore.Application.Abstract.UserContext;
|
using AipsCore.Application.Abstract.UserContext;
|
||||||
|
using AipsCore.Domain.Models.User.External;
|
||||||
using Microsoft.IdentityModel.Tokens;
|
using Microsoft.IdentityModel.Tokens;
|
||||||
|
|
||||||
namespace AipsCore.Infrastructure.Persistence.Authentication;
|
namespace AipsCore.Infrastructure.Persistence.Authentication;
|
||||||
@@ -15,7 +16,7 @@ public class JwtTokenProvider : ITokenProvider
|
|||||||
_jwtSettings = jwtSettings;
|
_jwtSettings = jwtSettings;
|
||||||
}
|
}
|
||||||
|
|
||||||
public string Generate(Domain.Models.User.User user, IList<string> roles)
|
public string Generate(Domain.Models.User.User user, IList<UserRole> roles)
|
||||||
{
|
{
|
||||||
var claims = new List<Claim>
|
var claims = new List<Claim>
|
||||||
{
|
{
|
||||||
@@ -25,7 +26,7 @@ public class JwtTokenProvider : ITokenProvider
|
|||||||
|
|
||||||
foreach (var role in roles)
|
foreach (var role in roles)
|
||||||
{
|
{
|
||||||
claims.Add(new Claim(ClaimTypes.Role, role));
|
claims.Add(new Claim(ClaimTypes.Role, role.Name));
|
||||||
}
|
}
|
||||||
|
|
||||||
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettings.Key));
|
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettings.Key));
|
||||||
|
|||||||
@@ -0,0 +1,39 @@
|
|||||||
|
namespace AipsCore.Infrastructure.Persistence.User.Mappers;
|
||||||
|
|
||||||
|
public static class UserMappers
|
||||||
|
{
|
||||||
|
public static Domain.Models.User.User MapToModel(this User entity)
|
||||||
|
{
|
||||||
|
return Domain.Models.User.User.Create(
|
||||||
|
entity.Id.ToString(),
|
||||||
|
entity.Email!,
|
||||||
|
entity.UserName!,
|
||||||
|
entity.CreatedAt,
|
||||||
|
entity.DeletedAt
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static User MapToEntity(this Domain.Models.User.User model)
|
||||||
|
{
|
||||||
|
return new User
|
||||||
|
{
|
||||||
|
Id = new Guid(model.Id.IdValue),
|
||||||
|
Email = model.Email.EmailValue,
|
||||||
|
NormalizedEmail = model.Email.EmailValue.ToUpperInvariant(),
|
||||||
|
UserName = model.Username.UsernameValue,
|
||||||
|
NormalizedUserName = model.Username.UsernameValue.ToUpperInvariant(),
|
||||||
|
CreatedAt = model.CreatedAt.CreatedAtValue,
|
||||||
|
DeletedAt = model.DeletedAt.DeletedAtValue
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void UpdateEntity(this User entity, Domain.Models.User.User model)
|
||||||
|
{
|
||||||
|
entity.Email = model.Email.EmailValue;
|
||||||
|
entity.NormalizedEmail = model.Email.EmailValue.ToUpperInvariant();
|
||||||
|
entity.UserName = model.Username.UsernameValue;
|
||||||
|
entity.NormalizedUserName = model.Username.UsernameValue.ToUpperInvariant();
|
||||||
|
entity.CreatedAt = model.CreatedAt.CreatedAtValue;
|
||||||
|
entity.DeletedAt = model.DeletedAt.DeletedAtValue;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,88 +4,31 @@ using AipsCore.Domain.Models.User.Validation;
|
|||||||
using AipsCore.Domain.Models.User.ValueObjects;
|
using AipsCore.Domain.Models.User.ValueObjects;
|
||||||
using AipsCore.Infrastructure.Persistence.Abstract;
|
using AipsCore.Infrastructure.Persistence.Abstract;
|
||||||
using AipsCore.Infrastructure.Persistence.Db;
|
using AipsCore.Infrastructure.Persistence.Db;
|
||||||
|
using AipsCore.Infrastructure.Persistence.User.Mappers;
|
||||||
using Microsoft.AspNetCore.Identity;
|
using Microsoft.AspNetCore.Identity;
|
||||||
|
|
||||||
namespace AipsCore.Infrastructure.Persistence.User;
|
namespace AipsCore.Infrastructure.Persistence.User;
|
||||||
|
|
||||||
public class UserRepository : AbstractRepository<Domain.Models.User.User, UserId, User>, IUserRepository
|
public class UserRepository : AbstractRepository<Domain.Models.User.User, UserId, User>, IUserRepository
|
||||||
{
|
{
|
||||||
private readonly UserManager<User> _userManager;
|
|
||||||
|
|
||||||
public UserRepository(AipsDbContext context, UserManager<User> userManager)
|
public UserRepository(AipsDbContext context, UserManager<User> userManager)
|
||||||
: base(context)
|
: base(context)
|
||||||
{
|
{
|
||||||
_userManager = userManager;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
protected override Domain.Models.User.User MapToModel(User entity)
|
protected override Domain.Models.User.User MapToModel(User entity)
|
||||||
{
|
{
|
||||||
return Domain.Models.User.User.Create(
|
return entity.MapToModel();
|
||||||
entity.Id.ToString(),
|
|
||||||
entity.Email,
|
|
||||||
entity.UserName,
|
|
||||||
entity.CreatedAt,
|
|
||||||
entity.DeletedAt
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
protected override User MapToEntity(Domain.Models.User.User model)
|
protected override User MapToEntity(Domain.Models.User.User model)
|
||||||
{
|
{
|
||||||
return new User
|
return model.MapToEntity();
|
||||||
{
|
|
||||||
Id = new Guid(model.Id.IdValue),
|
|
||||||
Email = model.Email.EmailValue,
|
|
||||||
NormalizedEmail = model.Email.EmailValue.ToUpperInvariant(),
|
|
||||||
UserName = model.Username.UsernameValue,
|
|
||||||
NormalizedUserName = model.Username.UsernameValue.ToUpperInvariant(),
|
|
||||||
CreatedAt = model.CreatedAt.CreatedAtValue,
|
|
||||||
DeletedAt = model.DeletedAt.DeletedAtValue
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
protected override void UpdateEntity(User entity, Domain.Models.User.User model)
|
protected override void UpdateEntity(User entity, Domain.Models.User.User model)
|
||||||
{
|
{
|
||||||
entity.Email = model.Email.EmailValue;
|
entity.UpdateEntity(model);
|
||||||
entity.NormalizedEmail = model.Email.EmailValue.ToUpperInvariant();
|
|
||||||
entity.UserName = model.Username.UsernameValue;
|
|
||||||
entity.NormalizedUserName = model.Username.UsernameValue.ToUpperInvariant();
|
|
||||||
entity.CreatedAt = model.CreatedAt.CreatedAtValue;
|
|
||||||
entity.DeletedAt = model.DeletedAt.DeletedAtValue;
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task SignUpWithPasswordAsync(Domain.Models.User.User user, string password, CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
var entity = MapToEntity(user);
|
|
||||||
|
|
||||||
var result = await _userManager.CreateAsync(entity, password);
|
|
||||||
|
|
||||||
if (!result.Succeeded)
|
|
||||||
{
|
|
||||||
var errors = string.Join(", ", result.Errors.Select(e => e.Description));
|
|
||||||
throw new Exception($"User registration failed: {errors}");
|
|
||||||
}
|
|
||||||
|
|
||||||
await _userManager.AddToRoleAsync(entity, UserRole.User.Name);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task<LoginResult> LoginWithEmailAndPasswordAsync(string email, string password, CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
var entity = await _userManager.FindByEmailAsync(email);
|
|
||||||
|
|
||||||
if (entity is null)
|
|
||||||
{
|
|
||||||
throw new ValidationException(UserErrors.LoginErrorUserNotFoundByEmail(email));
|
|
||||||
}
|
|
||||||
|
|
||||||
var isPasswordValid = await _userManager.CheckPasswordAsync(entity, password);
|
|
||||||
|
|
||||||
if (!isPasswordValid)
|
|
||||||
{
|
|
||||||
throw new ValidationException(UserErrors.LoginErrorIncorrectPassword());
|
|
||||||
}
|
|
||||||
|
|
||||||
var roles = await _userManager.GetRolesAsync(entity);
|
|
||||||
|
|
||||||
return new LoginResult(MapToModel(entity), roles);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
using AipsCore.Application.Abstract;
|
using AipsCore.Application.Abstract;
|
||||||
using AipsCore.Application.Authentication;
|
using AipsCore.Application.Common.Authentication;
|
||||||
using AipsCore.Application.Models.User.Command.LogIn;
|
using AipsCore.Application.Models.User.Command.LogIn;
|
||||||
using AipsCore.Application.Models.User.Command.SignUp;
|
using AipsCore.Application.Models.User.Command.SignUp;
|
||||||
using AipsCore.Application.Models.User.Query.GetUser;
|
using AipsCore.Application.Models.User.Query.GetUser;
|
||||||
|
|||||||
@@ -16,10 +16,7 @@ builder.Services.AddAips(builder.Configuration);
|
|||||||
|
|
||||||
var app = builder.Build();
|
var app = builder.Build();
|
||||||
|
|
||||||
using (var scope = app.Services.CreateScope())
|
await app.Services.InitializeInfrastructureAsync();
|
||||||
{
|
|
||||||
await DbInitializer.SeedRolesAsync(scope.ServiceProvider);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Configure the HTTP request pipeline.
|
// Configure the HTTP request pipeline.
|
||||||
if (app.Environment.IsDevelopment())
|
if (app.Environment.IsDevelopment())
|
||||||
|
|||||||
Reference in New Issue
Block a user