using Nuuru.Server.Auth;
using Nuuru.Server.Extensions;
namespace Nuuru.Server.Services
{
///
/// Provides access to the current user's identity and permissions.
/// Scoped per-request, allows services to check user context without parameter drilling.
///
public interface ICurrentUserContext
{
///
/// The current user's ID, or null if not authenticated.
///
Guid? UserId { get; }
///
/// Whether there is an authenticated user.
///
bool IsAuthenticated { get; }
///
/// Check if the current user has a specific permission.
/// Returns false if not authenticated.
///
bool HasPermission(string permission);
}
///
/// HTTP implementation that reads from HttpContext.User.
///
public class HttpCurrentUserContext : ICurrentUserContext
{
private readonly IHttpContextAccessor _httpContextAccessor;
private Guid? _cachedUserId;
private bool _userIdCached;
public HttpCurrentUserContext(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public Guid? UserId
{
get
{
if (!_userIdCached)
{
_cachedUserId = _httpContextAccessor.HttpContext?.User?.GetUserId();
_userIdCached = true;
}
return _cachedUserId;
}
}
public bool IsAuthenticated => _httpContextAccessor.HttpContext?.User?.Identity?.IsAuthenticated ?? false;
public bool HasPermission(string permission)
{
return _httpContextAccessor.HttpContext?.User?.HasPermission(permission) ?? false;
}
}
///
/// System context for background jobs or non-HTTP scenarios.
/// Defaults to no user with no permissions.
///
public class AnonymousUserContext : ICurrentUserContext
{
public Guid? UserId => null;
public bool IsAuthenticated => false;
public bool HasPermission(string permission) => false;
}
///
/// System context with elevated permissions for background jobs.
///
public class SystemUserContext : ICurrentUserContext
{
public Guid? UserId => null;
public bool IsAuthenticated => false;
public bool HasPermission(string permission) => true; // System has all permissions
}
}