add role api
This commit is contained in:
@@ -0,0 +1,72 @@
|
||||
using AuthHex.Models.IOs;
|
||||
using AuthHex.Services.RoleManager;
|
||||
|
||||
namespace AuthHex.Services.FunctionHandler
|
||||
{
|
||||
public class RoleManager
|
||||
{
|
||||
public readonly Dictionary<string, Func<object, HttpContext, Task<object>>> _functionHandler;
|
||||
|
||||
public RoleManager(RoleManagerService roleManagerService)
|
||||
{
|
||||
_functionHandler = new()
|
||||
{
|
||||
{ "createRole", roleManagerService.CreateRole },
|
||||
{ "getRole", roleManagerService.GetRole },
|
||||
{ "listRoles", async (payload, context) => await roleManagerService.ListRoles(context) },
|
||||
{ "updateRole", roleManagerService.UpdateRole },
|
||||
{ "deleteRole", roleManagerService.DeleteRole }
|
||||
};
|
||||
}
|
||||
|
||||
public async Task<ApiResponse> Execute(ApiRequest request, HttpContext httpContext)
|
||||
{
|
||||
if (!_functionHandler.TryGetValue(request.FunctionName, out var handler))
|
||||
{
|
||||
return new ApiResponse
|
||||
{
|
||||
StatusCode = 404,
|
||||
Message = $"Function '{request.FunctionName}' not found.",
|
||||
Data = null
|
||||
};
|
||||
}
|
||||
try
|
||||
{
|
||||
var results = await handler(request.Payload, httpContext);
|
||||
return new ApiResponse
|
||||
{
|
||||
StatusCode = 200,
|
||||
Message = "success",
|
||||
Data = results
|
||||
};
|
||||
}
|
||||
catch (KeyNotFoundException ex)
|
||||
{
|
||||
return new ApiResponse
|
||||
{
|
||||
StatusCode = 400,
|
||||
Message = ex.Message,
|
||||
Data = null
|
||||
};
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
return new ApiResponse
|
||||
{
|
||||
StatusCode = 400,
|
||||
Message = ex.Message,
|
||||
Data = null
|
||||
};
|
||||
}
|
||||
catch (ArgumentException ex)
|
||||
{
|
||||
return new ApiResponse
|
||||
{
|
||||
StatusCode = 500,
|
||||
Message = ex.Message,
|
||||
Data = null
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ namespace AuthHex.Services.FunctionHandler
|
||||
{ "refreshToken", UserManagerService.RefreshToken },
|
||||
{ "getUserDetails", UserManagerService.GetUserDetails },
|
||||
{ "getUserSessions", async (payload, context) => await UserManagerService.GetUserSessions(context) },
|
||||
{ "listUserTypes", async (payload, context) => await UserManagerService.ListUserTypes(context) },
|
||||
{ "ChangeUserStatus", UserManagerService.ChangeUserStatus},
|
||||
{"LockUserAccount" , UserManagerService.LockUserAccount },
|
||||
{"ChangeUserPassword" , UserManagerService.ChangeUserPassword },
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
using System.Text.Json;
|
||||
using AuthHex.Infra.UoW;
|
||||
using AuthHex.Interfaces;
|
||||
using AuthHex.Models;
|
||||
using Core_Archi.Helpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace AuthHex.Services.RoleManager;
|
||||
|
||||
public class RoleManagerService
|
||||
{
|
||||
private readonly IRoleManageRepository _repository;
|
||||
private readonly IUnitOfWork _uow;
|
||||
|
||||
public RoleManagerService(IRoleManageRepository repository, IUnitOfWork uow)
|
||||
{
|
||||
_repository = repository;
|
||||
_uow = uow;
|
||||
}
|
||||
|
||||
public async Task<object> CreateRole(object payload, HttpContext httpContext)
|
||||
{
|
||||
await _uow.BeginAsync();
|
||||
try
|
||||
{
|
||||
var data = DeserializePayload.Deserialize(payload);
|
||||
|
||||
var code = data.ContainsKey("code") ? data["code"].GetString() : null;
|
||||
var name = data.ContainsKey("name") ? data["name"].GetString() : null;
|
||||
var isSystemRole = data.ContainsKey("isSystemRole")
|
||||
&& data["isSystemRole"].ValueKind != JsonValueKind.Null
|
||||
&& data["isSystemRole"].GetBoolean();
|
||||
|
||||
if (string.IsNullOrWhiteSpace(code))
|
||||
throw new ArgumentException("code is required");
|
||||
|
||||
var role = new Role
|
||||
{
|
||||
RoleId = Guid.NewGuid(),
|
||||
Code = code,
|
||||
Name = string.IsNullOrWhiteSpace(name) ? code : name,
|
||||
IsSystemRole = isSystemRole,
|
||||
CreatedAt = DateTime.UtcNow
|
||||
};
|
||||
|
||||
await _repository.AddRoleAsync(role);
|
||||
await _uow.CommitAsync();
|
||||
|
||||
return ToDto(role);
|
||||
}
|
||||
catch
|
||||
{
|
||||
await _uow.RollbackAsync();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<object> GetRole(object payload, HttpContext httpContext)
|
||||
{
|
||||
var data = DeserializePayload.Deserialize(payload);
|
||||
|
||||
if (!data.ContainsKey("roleId") || !Guid.TryParse(data["roleId"].GetString(), out var roleId))
|
||||
throw new ArgumentException("Invalid roleId");
|
||||
|
||||
var role = await _repository.GetRoleByIdAsync(roleId)
|
||||
?? throw new KeyNotFoundException("Role not found");
|
||||
|
||||
return ToDto(role);
|
||||
}
|
||||
|
||||
public async Task<object> ListRoles(HttpContext httpContext)
|
||||
{
|
||||
var roles = await _repository.ListRolesAsync();
|
||||
return roles.Select(ToDto).ToList();
|
||||
}
|
||||
|
||||
public async Task<object> UpdateRole(object payload, HttpContext httpContext)
|
||||
{
|
||||
await _uow.BeginAsync();
|
||||
try
|
||||
{
|
||||
var data = DeserializePayload.Deserialize(payload);
|
||||
|
||||
if (!data.ContainsKey("roleId") || !Guid.TryParse(data["roleId"].GetString(), out var roleId))
|
||||
throw new ArgumentException("Invalid roleId");
|
||||
|
||||
var role = await _repository.GetRoleByIdAsync(roleId)
|
||||
?? throw new KeyNotFoundException("Role not found");
|
||||
|
||||
if (data.ContainsKey("code"))
|
||||
{
|
||||
var code = data["code"].GetString();
|
||||
if (string.IsNullOrWhiteSpace(code))
|
||||
throw new ArgumentException("code cannot be empty");
|
||||
role.Code = code;
|
||||
}
|
||||
|
||||
if (data.ContainsKey("name"))
|
||||
role.Name = data["name"].GetString();
|
||||
|
||||
if (data.ContainsKey("isSystemRole") && data["isSystemRole"].ValueKind != JsonValueKind.Null)
|
||||
role.IsSystemRole = data["isSystemRole"].GetBoolean();
|
||||
|
||||
await _uow.CommitAsync();
|
||||
|
||||
return ToDto(role);
|
||||
}
|
||||
catch
|
||||
{
|
||||
await _uow.RollbackAsync();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<object> DeleteRole(object payload, HttpContext httpContext)
|
||||
{
|
||||
await _uow.BeginAsync();
|
||||
try
|
||||
{
|
||||
var data = DeserializePayload.Deserialize(payload);
|
||||
|
||||
if (!data.ContainsKey("roleId") || !Guid.TryParse(data["roleId"].GetString(), out var roleId))
|
||||
throw new ArgumentException("Invalid roleId");
|
||||
|
||||
var role = await _repository.GetRoleByIdAsync(roleId)
|
||||
?? throw new KeyNotFoundException("Role not found");
|
||||
|
||||
if (await _repository.RoleInUseAsync(roleId))
|
||||
throw new InvalidOperationException("ROLE_IN_USE: role is assigned to one or more users");
|
||||
|
||||
await _repository.DeleteRoleAsync(role);
|
||||
await _uow.CommitAsync();
|
||||
|
||||
return new { message = "Role deleted successfully" };
|
||||
}
|
||||
catch
|
||||
{
|
||||
await _uow.RollbackAsync();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private static object ToDto(Role role) => new
|
||||
{
|
||||
role.RoleId,
|
||||
role.Code,
|
||||
role.Name,
|
||||
role.IsSystemRole,
|
||||
role.CreatedAt
|
||||
};
|
||||
}
|
||||
@@ -94,8 +94,10 @@ public class UserManagerService
|
||||
data["password"] = JsonDocument.Parse($"\"{Guid.NewGuid().ToString().Substring(0, 8)}\"").RootElement;
|
||||
}
|
||||
|
||||
var PasswordHash = data.ContainsKey("password") ? PasswordHasher.Hash(data["password"].GetString()!) : null;
|
||||
var RawPassword = data["password"].GetString()!;
|
||||
var PasswordHash = PasswordHasher.Hash(RawPassword);
|
||||
|
||||
var sendCredentialsEmail = !data.ContainsKey("sendCredentialsEmail") || data["sendCredentialsEmail"].GetBoolean();
|
||||
|
||||
// Create User object
|
||||
User user = new User
|
||||
@@ -113,7 +115,7 @@ public class UserManagerService
|
||||
IsLocked = false,
|
||||
EmailVerified = false,
|
||||
MobileNumberVerified = false,
|
||||
//PasswordHash = PasswordHash
|
||||
PasswordHash = PasswordHash
|
||||
|
||||
};
|
||||
|
||||
@@ -151,6 +153,30 @@ public class UserManagerService
|
||||
|
||||
await _uow.CommitAsync();
|
||||
|
||||
if (sendCredentialsEmail && !string.IsNullOrWhiteSpace(Email))
|
||||
{
|
||||
try
|
||||
{
|
||||
await _thirdPartyService.EmailConfiguration(
|
||||
Email,
|
||||
RawPassword,
|
||||
"Your ERP System Account",
|
||||
$@"
|
||||
<html>
|
||||
<body style='font-family: Arial, sans-serif;'>
|
||||
<h2>Your ERP System account has been created</h2>
|
||||
<p>Username: <strong>{WebUtility.HtmlEncode(UserName ?? Email)}</strong></p>
|
||||
<p>Temporary password: <strong>{{code}}</strong></p>
|
||||
<p>Please log in and change your password as soon as possible.</p>
|
||||
</body>
|
||||
</html>");
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Best-effort: account creation already committed; do not fail the request on email delivery issues.
|
||||
}
|
||||
}
|
||||
|
||||
return new
|
||||
{
|
||||
AccessToken = jwtToken,
|
||||
@@ -544,6 +570,17 @@ public class UserManagerService
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<object> ListUserTypes(HttpContext httpContext)
|
||||
{
|
||||
var userTypes = await _dbContext.UserType.OrderBy(t => t.Code).ToListAsync();
|
||||
return userTypes.Select(t => new
|
||||
{
|
||||
t.UserTypeId,
|
||||
t.Code,
|
||||
t.Description
|
||||
}).ToList();
|
||||
}
|
||||
|
||||
public async Task<object> GetUserSessions(HttpContext httpContext)
|
||||
{
|
||||
try
|
||||
|
||||
Reference in New Issue
Block a user