Files
2025-02-26 23:42:19 +01:00

65 lines
2.2 KiB
C#

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;
using OpenWarehouse.auth.lib.Model.Privilage;
namespace OpenWarehouse.auth.api.Controller;
[ApiController]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[Route("[controller]/[action]")]
public class Privilege(UserManager<ApplicationUser> userManager,
PrivilegeManager privilegeManager, ILogger<Privilege> logger) : ControllerBase
{
[HttpPost]
public async Task<ActionResult<List<string>>> GetUserPrivilege()
{
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
logger.LogInformation("GetUserPrivilege request received for user: {UserId}", userId);
if (userId == null)
{
logger.LogWarning("User ID not found in claims");
return BadRequest();
}
var user = await userManager.FindByIdAsync(userId);
if (user == null)
{
logger.LogWarning("User not found for ID: {UserId}", userId);
return Unauthorized("User not found");
}
var privilege = await privilegeManager.GetUserPrivilage(user);
logger.LogInformation("Privileges retrieved for user {UserId}", userId);
return Ok(privilege);
}
[HttpPost]
[HasPrivilege(GlobalPrivilage.Privilege.GlobalEditRole)]
public async Task<ActionResult> CreatePrivilage([FromBody] CreatePrivilageModel privilage)
{
logger.LogInformation("CreatePrivilege request received for privilege: {Privilege}", privilage.Privilage);
if (privilage is { Privilage: null })
{
logger.LogWarning("Invalid privilege model provided");
return BadRequest();
}
var ok = await privilegeManager.CreatePrivageAsync(privilage.Privilage);
if (ok.IsSuccessed)
{
logger.LogInformation("Privilege created successfully");
return Created();
}
else
{
logger.LogWarning("Failed to create privilege");
return BadRequest();
}
}
}