Skip to content

Commit

Permalink
[Hotfix][Duy] Allow admin to create staff
Browse files Browse the repository at this point in the history
  • Loading branch information
duykasama committed Mar 20, 2024
1 parent 3faaced commit f906f02
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 2 deletions.
19 changes: 19 additions & 0 deletions Domus.Service/Exceptions/RoleNotFoundException.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
using Domus.Common.Exceptions;

namespace Domus.Service.Exceptions;

public class RoleNotFoundException : ArgumentException, INotFoundException
{
private readonly string? _customMessage;
public override string Message => _customMessage ?? Message;

public RoleNotFoundException(string customMessage)
{
_customMessage = customMessage;
}

public RoleNotFoundException()
{
_customMessage = "Role not found";
}
}
22 changes: 20 additions & 2 deletions Domus.Service/Implementations/UserService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,30 @@ public async Task<ServiceActionResult> CreateUser(CreateUserRequest request)
throw new UserAlreadyExistsException("The username is already in use");
if (!Regex.IsMatch(request.Password, PasswordConstants.PasswordPattern))
throw new PasswordTooWeakException(PasswordConstants.PasswordPatternErrorMessage);
if (!string.IsNullOrEmpty(request.Role) && await _roleManager.RoleExistsAsync(request.Role))
throw new RoleNotFoundException();

var user = _mapper.Map<DomusUser>(request);

var result = await _userManager.CreateAsync(user, request.Password);
await EnsureRoleExistsAsync(UserRoleConstants.CLIENT);
await _userManager.AddToRoleAsync(user, UserRoleConstants.CLIENT);
if (string.IsNullOrEmpty(request.Role))
{
await EnsureRoleExistsAsync(UserRoleConstants.CLIENT);
await _userManager.AddToRoleAsync(user, UserRoleConstants.CLIENT);
}
else if (request.Role == UserRoleConstants.STAFF)
{
await EnsureRoleExistsAsync(UserRoleConstants.CLIENT);
await EnsureRoleExistsAsync(UserRoleConstants.STAFF);
await _userManager.AddToRoleAsync(user, UserRoleConstants.CLIENT);
await _userManager.AddToRoleAsync(user, UserRoleConstants.STAFF);
}
else
{
await EnsureRoleExistsAsync(request.Role);
await _userManager.AddToRoleAsync(user, request.Role);
}

if (result.Succeeded)
{
var returnedUser = await _userRepository.GetAsync(u => u.Email == request.Email);
Expand Down
2 changes: 2 additions & 0 deletions Domus.Service/Models/Requests/Users/CreateUserRequest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,6 @@ public class CreateUserRequest
[Required]
[MatchesPattern(PasswordConstants.PasswordPattern, PasswordConstants.PasswordPatternErrorMessage)]
public string Password { get; set; } = null!;

public string? Role { get; set; }
}

0 comments on commit f906f02

Please sign in to comment.