feat: helper functions for checking roles and a demo endpoint

This commit is contained in:
2025-07-17 13:48:12 +02:00
parent 2350935e8a
commit abebb84c69
4 changed files with 101 additions and 3 deletions

View File

@@ -98,4 +98,31 @@ public class AuthController : ControllerBase
return Ok(new string[] { "value1", "value2" }); return Ok(new string[] { "value1", "value2" });
} }
// GET /api/v1/auth/user_role
/// <summary>
/// [AUTHED] Get user role as a string
/// </summary>
/// <remarks>
/// Authed endpoint used to check human-readable user role.
/// Authed endpoints expect Authorization header, e.g.:
/// Authorization: bearer {jwt}</remarks>
/// <returns>Json containing single field "role"</returns>
/// <response code="200">Returned on request with valid credentials</response>
/// <response code="400">Returned on request with JWT whose user could not be found (sanity check)</response>
[HttpGet("user_role")]
[Authorize]
[EnableCors]
[ProducesResponseType(200)]
[ProducesResponseType(typeof(ErrorDTO), 400)]
public IActionResult GetUserRole()
{
// Get user from token
User? u = guhf.GetUserFromToken(Request.Headers.Authorization!);
if (u == null)
return BadRequest(new ErrorDTO { Status = "error", Error_msg = "User not found" });
// Return the role as a string
return Ok(new { Role = guhf.UserRoleAsStr(u) });
}
} }

View File

@@ -14,6 +14,78 @@ public class GeneralUseHelpers(ApplicationDbContext db, IConfiguration appsettin
private readonly ApplicationDbContext _db = db; private readonly ApplicationDbContext _db = db;
private readonly IConfiguration _appsettings = appsettings; private readonly IConfiguration _appsettings = appsettings;
// Allows to check whether the user is of role present in roles.
// Example:
// For user with role 0,
// - IsUser(["Manager"], req) yields false
// - IsUser(["Admin"], req) yields true
// - IsUser(["Admin", "Manager"], req) yields true because the user is an admin
public bool IsUser(string[] roles, HttpRequest req)
{
// Get the user to read its roles
User? user = GetUserFromToken(req.Headers.Authorization!);
if (user == null) {
return false;
}
foreach (var role in roles)
{
if (string.IsNullOrEmpty(role))
{
continue;
}
switch (role)
{
case "Admin":
if (user.Role == 0)
return true;
break;
case "Manager":
if (user.Role == 1)
return true;
break;
case "Pracownik":
if (user.Role == 2)
return true;
break;
default:
continue;
}
}
return false;
}
public string UserRoleAsStr(User user)
{
switch (user.Role)
{
case 0:
return "Admin";
case 1:
return "Manager";
case 2:
return "Pracownik";
default:
return "Unknown role";
}
}
public User? GetUserFromToken(string token)
{
if (token.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
{
token = token.Substring("Bearer ".Length).Trim();
}
var handler = new JwtSecurityTokenHandler();
var jwtSecurityToken = handler.ReadJwtToken(token);
if (int.TryParse(jwtSecurityToken.Subject, out int userId))
{
return _db.Users.FirstOrDefault(u => u.Id == userId);
}
return null;
}
async public Task<User?> GetUserFromEmail(string email) async public Task<User?> GetUserFromEmail(string email)
{ {
return await _db.Users.FirstOrDefaultAsync(e => e.Email == email); return await _db.Users.FirstOrDefaultAsync(e => e.Email == email);
@@ -37,7 +109,6 @@ public class GeneralUseHelpers(ApplicationDbContext db, IConfiguration appsettin
var claims = new[] var claims = new[]
{ {
new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString()), new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
// new Claim(ClaimTypes.Role, )
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()) new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
}; };

View File

@@ -109,13 +109,12 @@ public class QuotesController : ControllerBase
[HttpPost("new")] [HttpPost("new")]
[Authorize] [Authorize]
[EnableCors] [EnableCors]
[ProducesResponseType(201)] // ? FIXME [ProducesResponseType(201)]
[ProducesResponseType(typeof(ErrorDTO), 400)] [ProducesResponseType(typeof(ErrorDTO), 400)]
[ProducesResponseType(typeof(ErrorDTO), 403)] [ProducesResponseType(typeof(ErrorDTO), 403)]
public async Task<IActionResult> CreateQuote([FromBody] CreateQuoteDTO request) public async Task<IActionResult> CreateQuote([FromBody] CreateQuoteDTO request)
{ {
// Get user ID from claims // Get user ID from claims
// FIXME
var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier)?.Value; var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (userIdClaim == null || !int.TryParse(userIdClaim, out int userId)) if (userIdClaim == null || !int.TryParse(userIdClaim, out int userId))
// https://stackoverflow.com/a/47708867 // https://stackoverflow.com/a/47708867

View File

@@ -59,6 +59,7 @@ builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
// Add services to the container. // Add services to the container.
builder.Services.AddAuthorization(); builder.Services.AddAuthorization();
builder.Services.AddSingleton(builder.Configuration); builder.Services.AddSingleton(builder.Configuration);
builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped<GeneralUseHelpers>(); builder.Services.AddScoped<GeneralUseHelpers>();
builder.Services.AddControllers(); builder.Services.AddControllers();