mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 11:11:10 +00:00
Adds authorization roles administrator dashboard
This commit is contained in:
1 parent
290af03c83
commit
1df31515fb
191 files changed
+6189
-806
No files matched your search
+11
-11
@@ -46,22 +46,22 @@ public class ChangePasswordCommandHandler : IRequestHandler<ChangePasswordComman
|
||||
public async ValueTask<ErrorOr<ChangePasswordResponse>> Handle(ChangePasswordCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
|
||||
ErrorOr<UserEntity?> resultSelectUser = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken).ConfigureAwait(false);
|
||||
if (resultSelectUser.IsError)
|
||||
return resultSelectUser.Errors;
|
||||
else if (resultSelectUser.Value is null)
|
||||
ErrorOr<UserEntity?> getUserResult = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken).ConfigureAwait(false);
|
||||
if (getUserResult.IsError)
|
||||
return getUserResult.Errors;
|
||||
else if (getUserResult.Value is null)
|
||||
return Errors.Authentication.UsernameDoesNotExist;
|
||||
// validate if the current password is correct
|
||||
if (!_hashService.CheckStringAgainstHash(request.CurrentPassword!, Uri.UnescapeDataString(resultSelectUser.Value.Password!)))
|
||||
if (!_hashService.CheckStringAgainstHash(request.CurrentPassword!, Uri.UnescapeDataString(getUserResult.Value.Password!)))
|
||||
return Errors.Authentication.InvalidCurrentPassword;
|
||||
resultSelectUser.Value.Password = Uri.EscapeDataString(_hashService.HashString(request.NewPassword!));
|
||||
getUserResult.Value.Password = Uri.EscapeDataString(_hashService.HashString(request.NewPassword!));
|
||||
// if the password change was initiated via a password reset, remote the temporary password that was generated in the process
|
||||
resultSelectUser.Value.TempPassword = null;
|
||||
resultSelectUser.Value.TempPasswordCreated = null;
|
||||
getUserResult.Value.TempPassword = null;
|
||||
getUserResult.Value.TempPasswordCreated = null;
|
||||
// update the user
|
||||
ErrorOr<Updated> resultUpdateUser = await userRepository.UpdateAsync(resultSelectUser.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (resultUpdateUser.IsError)
|
||||
return resultUpdateUser.Errors;
|
||||
ErrorOr<Updated> updateUserResult = await userRepository.UpdateAsync(getUserResult.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (updateUserResult.IsError)
|
||||
return updateUserResult.Errors;
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
return new ChangePasswordResponse(true);
|
||||
}
|
||||
|
||||
+12
-12
@@ -56,29 +56,29 @@ public class RecoverPasswordCommandHandler : IRequestHandler<RecoverPasswordComm
|
||||
{
|
||||
// check if any users already exists
|
||||
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
|
||||
ErrorOr<UserEntity?> resultSelectUser = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken).ConfigureAwait(false);
|
||||
if (resultSelectUser.IsError)
|
||||
return resultSelectUser.Errors;
|
||||
else if (resultSelectUser.Value is null)
|
||||
ErrorOr<UserEntity?> getUserResult = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken).ConfigureAwait(false);
|
||||
if (getUserResult.IsError)
|
||||
return getUserResult.Errors;
|
||||
else if (getUserResult.Value is null)
|
||||
return Errors.Authentication.UsernameDoesNotExist;
|
||||
else if (resultSelectUser.Value.TempPassword is not null) // if a temp password is present, a password request was already requested
|
||||
else if (getUserResult.Value.TempPassword is not null) // if a temp password is present, a password request was already requested
|
||||
return Errors.Authentication.PasswordResetAlreadyRequested;
|
||||
// check if the user uses TOTP
|
||||
bool usesTotp = !string.IsNullOrEmpty(resultSelectUser.Value.TotpSecret);
|
||||
bool usesTotp = !string.IsNullOrEmpty(getUserResult.Value.TotpSecret);
|
||||
if (!usesTotp)
|
||||
return Errors.Authentication.InvalidTotpCode;
|
||||
if (usesTotp && string.IsNullOrEmpty(request.TotpCode))
|
||||
return Errors.Authentication.InvalidTotpCode;
|
||||
else if (usesTotp && !string.IsNullOrEmpty(request.TotpCode)) // and if they do, validate it
|
||||
if (!_totpTokenGenerator.ValidateToken(Convert.FromBase64String(_cryptographyService.Decrypt(resultSelectUser.Value.TotpSecret!)), request.TotpCode))
|
||||
if (!_totpTokenGenerator.ValidateToken(Convert.FromBase64String(_cryptographyService.Decrypt(getUserResult.Value.TotpSecret!)), request.TotpCode))
|
||||
return Errors.Authentication.InvalidTotpCode;
|
||||
// hash the new password and assign it to a temporary password that will be valid 15 minutes
|
||||
resultSelectUser.Value.TempPassword = Uri.EscapeDataString(_hashService.HashString("Abcd123$")); // TODO: replace with random password generator
|
||||
resultSelectUser.Value.TempPasswordCreated = DateTime.UtcNow;
|
||||
getUserResult.Value.TempPassword = Uri.EscapeDataString(_hashService.HashString("Abcd123$")); // TODO: replace with random password generator
|
||||
getUserResult.Value.TempPasswordCreated = DateTime.UtcNow;
|
||||
// update the user
|
||||
ErrorOr<Updated> resultUpdateUser = await userRepository.UpdateAsync(resultSelectUser.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (resultUpdateUser.IsError)
|
||||
return resultUpdateUser.Errors;
|
||||
ErrorOr<Updated> updateUserResult = await userRepository.UpdateAsync(getUserResult.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (updateUserResult.IsError)
|
||||
return updateUserResult.Errors;
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
return new RecoverPasswordResponse(true);
|
||||
}
|
||||
|
||||
+7
-7
@@ -65,10 +65,10 @@ public class RegisterUserCommandHandler : IRequestHandler<RegisterUserCommand, E
|
||||
{
|
||||
// check if any users already exists (admin account is only set once!)
|
||||
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
|
||||
ErrorOr<UserEntity?> resultSelectUser = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken).ConfigureAwait(false);
|
||||
if (resultSelectUser.IsError)
|
||||
return resultSelectUser.Errors;
|
||||
else if (resultSelectUser.Value is not null)
|
||||
ErrorOr<UserEntity?> getUserRResult = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken).ConfigureAwait(false);
|
||||
if (getUserRResult.IsError)
|
||||
return getUserRResult.Errors;
|
||||
else if (getUserRResult.Value is not null)
|
||||
return Errors.Authentication.UsernameAlreadyExists;
|
||||
string? totpSecret = null;
|
||||
Guid id = Guid.NewGuid();
|
||||
@@ -94,9 +94,9 @@ public class RegisterUserCommandHandler : IRequestHandler<RegisterUserCommand, E
|
||||
user.TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(secret));
|
||||
}
|
||||
// insert the user
|
||||
ErrorOr<Created> resultInsertUser = await userRepository.InsertAsync(user, cancellationToken).ConfigureAwait(false);
|
||||
if (resultInsertUser.IsError)
|
||||
return resultInsertUser.Errors;
|
||||
ErrorOr<Created> insertUserResult = await userRepository.InsertAsync(user, cancellationToken).ConfigureAwait(false);
|
||||
if (insertUserResult.IsError)
|
||||
return insertUserResult.Errors;
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
// TODO: insert the default admin profile preferences when they are implemented
|
||||
// if 2FA was enabled, the TOTP secret needs to be delivered to the client unhashed, so it can be displayed
|
||||
|
||||
+15
-15
@@ -65,29 +65,29 @@ public class LoginUserQueryHandler : IRequestHandler<LoginUserQuery, ErrorOr<Log
|
||||
{
|
||||
// check if any users already exists
|
||||
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
|
||||
ErrorOr<UserEntity?> resultSelectUser = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken).ConfigureAwait(false);
|
||||
if (resultSelectUser.IsError)
|
||||
return resultSelectUser.Errors;
|
||||
else if (resultSelectUser.Value is null)
|
||||
ErrorOr<UserEntity?> getUserResult = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken).ConfigureAwait(false);
|
||||
if (getUserResult.IsError)
|
||||
return getUserResult.Errors;
|
||||
else if (getUserResult.Value is null)
|
||||
return Errors.Authentication.InvalidUsernameOrPassword;
|
||||
// validate that the password is correct
|
||||
if (!_hashService.CheckStringAgainstHash(request.Password!, Uri.UnescapeDataString(resultSelectUser.Value.Password!)))
|
||||
if (!_hashService.CheckStringAgainstHash(request.Password!, Uri.UnescapeDataString(getUserResult.Value.Password!)))
|
||||
{
|
||||
// if a password reset was requested, a temp password is being used - if the hash check failed against the regular password, try against the temp one too
|
||||
if (resultSelectUser.Value.TempPassword is not null)
|
||||
if (getUserResult.Value.TempPassword is not null)
|
||||
{
|
||||
// the temporary password should only be valid for 15 minutes, if its obsolete, remove it and return error
|
||||
if (resultSelectUser.Value.TempPasswordCreated!.Value.AddMinutes(15) < _dateTimeProvider.UtcNow)
|
||||
if (getUserResult.Value.TempPasswordCreated!.Value.AddMinutes(15) < _dateTimeProvider.UtcNow)
|
||||
{
|
||||
resultSelectUser.Value.TempPassword = null;
|
||||
resultSelectUser.Value.TempPasswordCreated = null;
|
||||
await userRepository.UpdateAsync(resultSelectUser.Value, cancellationToken);
|
||||
getUserResult.Value.TempPassword = null;
|
||||
getUserResult.Value.TempPasswordCreated = null;
|
||||
await userRepository.UpdateAsync(getUserResult.Value, cancellationToken);
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken);
|
||||
return Errors.Authentication.TempPasswordExpired;
|
||||
}
|
||||
else // temporary password is still valid, validate password against it
|
||||
{
|
||||
if (!_hashService.CheckStringAgainstHash(request.Password!, Uri.UnescapeDataString(resultSelectUser.Value.TempPassword!)))
|
||||
if (!_hashService.CheckStringAgainstHash(request.Password!, Uri.UnescapeDataString(getUserResult.Value.TempPassword!)))
|
||||
return Errors.Authentication.InvalidUsernameOrPassword;
|
||||
}
|
||||
}
|
||||
@@ -95,14 +95,14 @@ public class LoginUserQueryHandler : IRequestHandler<LoginUserQuery, ErrorOr<Log
|
||||
return Errors.Authentication.InvalidUsernameOrPassword;
|
||||
}
|
||||
// create the JWT token
|
||||
string token = _jwtTokenGenerator.GenerateToken(resultSelectUser.Value.Id.ToString(), resultSelectUser.Value.Username);
|
||||
string token = _jwtTokenGenerator.GenerateToken(getUserResult.Value.Id.ToString(), getUserResult.Value.Username);
|
||||
// check if the user uses TOTP
|
||||
bool usesTotp = !string.IsNullOrEmpty(resultSelectUser.Value.TotpSecret);
|
||||
bool usesTotp = !string.IsNullOrEmpty(getUserResult.Value.TotpSecret);
|
||||
if (usesTotp && string.IsNullOrEmpty(request.TotpCode))
|
||||
return Errors.Authentication.InvalidTotpCode;
|
||||
else if (usesTotp && !string.IsNullOrEmpty(request.TotpCode)) // and if they do, validate it
|
||||
if (!_totpTokenGenerator.ValidateToken(Convert.FromBase64String(_cryptographyService.Decrypt(resultSelectUser.Value.TotpSecret!)), request.TotpCode))
|
||||
if (!_totpTokenGenerator.ValidateToken(Convert.FromBase64String(_cryptographyService.Decrypt(getUserResult.Value.TotpSecret!)), request.TotpCode))
|
||||
return Errors.Authentication.InvalidTotpCode;
|
||||
return new LoginResponse(resultSelectUser.Value.Id, resultSelectUser.Value.Username, token, usesTotp);
|
||||
return new LoginResponse(getUserResult.Value.Id, getUserResult.Value.Username, token, usesTotp);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -15,4 +15,4 @@ namespace Lumina.Application.Core.UsersManagement.Authorization.Queries.GetAutho
|
||||
[DebuggerDisplay("UserId: {UserId}")]
|
||||
public record GetAuthorizationQuery(
|
||||
Guid? UserId
|
||||
) : IRequest<ErrorOr<GetAuthorizationResponse>>;
|
||||
) : IRequest<ErrorOr<AuthorizationResponse>>;
|
||||
+10
-11
@@ -6,7 +6,6 @@ using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Mapping.Authorization;
|
||||
using Lumina.Contracts.Responses.Authorization;
|
||||
using Lumina.Domain.Common.Enums.Authorization;
|
||||
using Mediator;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
@@ -18,13 +17,13 @@ namespace Lumina.Application.Core.UsersManagement.Authorization.Queries.GetAutho
|
||||
/// <summary>
|
||||
/// Handler for the query to retrieve the authorization roles and permissions of an account.
|
||||
/// </summary>
|
||||
public class GetAuthorizationQueryHandler : IRequestHandler<GetAuthorizationQuery, ErrorOr<GetAuthorizationResponse>>
|
||||
public class GetAuthorizationQueryHandler : IRequestHandler<GetAuthorizationQuery, ErrorOr<AuthorizationResponse>>
|
||||
{
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AuthorizationService"/> class.
|
||||
/// Initializes a new instance of the <see cref="GetAuthorizationQueryHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
@@ -40,22 +39,22 @@ public class GetAuthorizationQueryHandler : IRequestHandler<GetAuthorizationQuer
|
||||
/// <param name="request">The request to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="ErrorOr{TValue}"/> containing either a <see cref="GetAuthorizationResponse"/>, or an error message.
|
||||
/// An <see cref="ErrorOr{TValue}"/> containing either a <see cref="AuthorizationResponse"/>, or an error message.
|
||||
/// </returns>
|
||||
public async ValueTask<ErrorOr<GetAuthorizationResponse>> Handle(GetAuthorizationQuery request, CancellationToken cancellationToken)
|
||||
public async ValueTask<ErrorOr<AuthorizationResponse>> Handle(GetAuthorizationQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
// first, check if the Id of the user for whom to get the permission list is different from the Id currently making the request
|
||||
if (_currentUserService.UserId != request.UserId)
|
||||
{
|
||||
// if it is, get the role of the current user, and see if they are Admin
|
||||
ErrorOr<UserAuthorizationEntity> resultGetCurrentUserPermission = await _authorizationService.GetUserAuthorizationAsync(_currentUserService.UserId!.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (resultGetCurrentUserPermission.IsError)
|
||||
return resultGetCurrentUserPermission.Errors;
|
||||
ErrorOr<UserAuthorizationEntity> getCurrentUserPermissionResult = await _authorizationService.GetUserAuthorizationAsync(_currentUserService.UserId!.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getCurrentUserPermissionResult.IsError)
|
||||
return getCurrentUserPermissionResult.Errors;
|
||||
// if the current user is not an Admin, and the account for whom they request the permissions list is not theirs, deny the request
|
||||
if (!resultGetCurrentUserPermission.Value.Roles.Any(role => role == AuthorizationRole.Admin))
|
||||
if (!getCurrentUserPermissionResult.Value.Roles.Any(role => role == "Admin"))
|
||||
return Errors.Authorization.NotAuthorized;
|
||||
}
|
||||
ErrorOr<UserAuthorizationEntity> resultGetUserPermission = await _authorizationService.GetUserAuthorizationAsync(request.UserId!.Value, cancellationToken).ConfigureAwait(false);
|
||||
return resultGetUserPermission.Match(value => ErrorOrFactory.From(value.ToResponse()), errors => errors);
|
||||
ErrorOr<UserAuthorizationEntity> getUserPermissionResult = await _authorizationService.GetUserAuthorizationAsync(request.UserId!.Value, cancellationToken).ConfigureAwait(false);
|
||||
return getUserPermissionResult.Match(value => ErrorOrFactory.From(value.ToResponse()), errors => errors);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user