mirror of
https://github.com/QuotifyTeam/QuotifyBE.git
synced 2025-12-16 14:20:06 +01:00
feat: helper functions for checking roles and a demo endpoint
This commit is contained in:
@@ -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())
|
||||
};
|
||||
|
||||
|
||||
Reference in New Issue
Block a user