Files
ERP_Distribution/Distribution/Infra/Authorization/CurrentUserService.cs
T
Kalana B. Thilakarathna 0052725b88 feat: add user and role view sheets with detailed information display
- Created UserViewSheet component to display user details including username, full name, role, status, and timestamps.
- Created RoleViewSheet component to display role details including name, level, status, creation date, and associated permissions.
- Introduced permissions configuration in a new permissions.ts file, defining categories and permission codes for better management.
- Implemented middleware for authentication, ensuring access control for protected routes.
2026-10-18 23:11:01 +05:30

48 lines
1.8 KiB
C#

using System.Security.Claims;
using Distribution.Data;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
namespace Distribution.Infra.Authorization;
public class CurrentUserService(IHttpContextAccessor http, AppDBContext db, IMemoryCache cache) : ICurrentUserService
{
private ClaimsPrincipal? User => http.HttpContext?.User;
public bool IsAuthenticated => User?.Identity?.IsAuthenticated ?? false;
public Guid? UserId => Guid.TryParse(User?.FindFirst("UserId")?.Value, out var id) ? id : null;
public Guid? RoleId => Guid.TryParse(User?.FindFirst("RoleId")?.Value, out var id) ? id : null;
public async Task<string?> GetUsernameAsync()
{
if (UserId is not { } id) return null;
var key = $"user_rolename_{id}";
if (cache.TryGetValue(key, out string? cached)) return cached;
var user = await db.Users.AsNoTracking().FirstOrDefaultAsync(u => u.Id == id);
cache.Set(key, user?.Username, TimeSpan.FromMinutes(10));
return user?.Username;
}
public async Task<string?> GetRoleCodeAsync()
{
if (RoleId is not { } id) return null;
var key = $"role_name_{id}";
if (cache.TryGetValue(key, out string? cached)) return cached;
var role = await db.Roles.AsNoTracking().FirstOrDefaultAsync(r => r.Id == id);
cache.Set(key, role?.Name, TimeSpan.FromMinutes(10));
return role?.Name;
}
public async Task<int> GetRoleLevelAsync()
{
if (RoleId is not { } id) return 0;
var key = $"role_level_{id}";
if (cache.TryGetValue(key, out int cached)) return cached;
var role = await db.Roles.AsNoTracking().FirstOrDefaultAsync(r => r.Id == id);
var level = role?.Level ?? 0;
cache.Set(key, level, TimeSpan.FromMinutes(10));
return level;
}
}