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

@@ -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())
};