mirror of
https://github.com/QuotifyTeam/QuotifyBE.git
synced 2025-12-16 11:00:06 +01:00
feat: helper functions for checking roles and a demo endpoint
This commit is contained in:
@@ -98,4 +98,31 @@ public class AuthController : ControllerBase
|
||||
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) });
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -14,6 +14,78 @@ public class GeneralUseHelpers(ApplicationDbContext db, IConfiguration appsettin
|
||||
private readonly ApplicationDbContext _db = db;
|
||||
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)
|
||||
{
|
||||
return await _db.Users.FirstOrDefaultAsync(e => e.Email == email);
|
||||
@@ -37,7 +109,6 @@ public class GeneralUseHelpers(ApplicationDbContext db, IConfiguration appsettin
|
||||
var claims = new[]
|
||||
{
|
||||
new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
|
||||
// new Claim(ClaimTypes.Role, )
|
||||
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
|
||||
};
|
||||
|
||||
|
||||
@@ -109,13 +109,12 @@ public class QuotesController : ControllerBase
|
||||
[HttpPost("new")]
|
||||
[Authorize]
|
||||
[EnableCors]
|
||||
[ProducesResponseType(201)] // ? FIXME
|
||||
[ProducesResponseType(201)]
|
||||
[ProducesResponseType(typeof(ErrorDTO), 400)]
|
||||
[ProducesResponseType(typeof(ErrorDTO), 403)]
|
||||
public async Task<IActionResult> CreateQuote([FromBody] CreateQuoteDTO request)
|
||||
{
|
||||
// Get user ID from claims
|
||||
// FIXME
|
||||
var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
|
||||
if (userIdClaim == null || !int.TryParse(userIdClaim, out int userId))
|
||||
// https://stackoverflow.com/a/47708867
|
||||
|
||||
@@ -59,6 +59,7 @@ builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
||||
// Add services to the container.
|
||||
builder.Services.AddAuthorization();
|
||||
builder.Services.AddSingleton(builder.Configuration);
|
||||
builder.Services.AddHttpContextAccessor();
|
||||
builder.Services.AddScoped<GeneralUseHelpers>();
|
||||
|
||||
builder.Services.AddControllers();
|
||||
|
||||
Reference in New Issue
Block a user