using Lagerbestand.Models; namespace Lagerbestand.Services; /// /// Simple session service to hold current user state. /// Registered as Scoped - one instance per circuit/connection. /// public class UserSessionService { public AppUser? CurrentUser { get; private set; } public bool IsAuthenticated => CurrentUser != null && CurrentUser.IsActive; public bool IsAdmin => CurrentUser?.Role == UserRole.Admin; /// /// Worker role - has access to tire operations (checkin/checkout) and inventory list only /// public bool IsWorker => CurrentUser?.Role == UserRole.Worker; /// /// Check if user is Worker or Admin (for tire operations access) /// public bool IsWorkerOrAdmin => CurrentUser?.Role == UserRole.Admin || CurrentUser?.Role == UserRole.Worker; public string DisplayName => CurrentUser?.DisplayName ?? CurrentUser?.Username ?? string.Empty; public string Username => CurrentUser?.Username ?? string.Empty; public Guid? UserId => CurrentUser?.Id; public UserRole? Role => CurrentUser?.Role; public string RoleName => CurrentUser?.Role switch { UserRole.Admin => "Administrator", UserRole.Worker => "Mitarbeiter", UserRole.User => "Benutzer", _ => string.Empty }; public event Action? OnChange; public void SetUser(AppUser user) { CurrentUser = user; NotifyStateChanged(); } public void ClearUser() { CurrentUser = null; NotifyStateChanged(); } /// /// Updates the current user data without triggering OnChange. /// Useful for refreshing user data after profile updates. /// public void UpdateUser(AppUser user) { if (CurrentUser?.Id == user.Id) { CurrentUser = user; NotifyStateChanged(); } } /// /// Checks if the current user has at least the specified role level. /// Admin > Worker > User /// public bool HasMinimumRole(UserRole minimumRole) { if (CurrentUser == null || !CurrentUser.IsActive) return false; return (int)CurrentUser.Role >= (int)minimumRole; } /// /// Checks if the current user can manage the specified user. /// Users can only be managed by admins or by themselves for limited operations. /// public bool CanManageUser(Guid targetUserId) { if (!IsAuthenticated) return false; // Admins can manage everyone if (IsAdmin) return true; // Users can only manage themselves (limited) return CurrentUser?.Id == targetUserId; } /// /// Checks if the current user can delete the specified user. /// Only admins can delete users, and they cannot delete themselves. /// public bool CanDeleteUser(Guid targetUserId) { if (!IsAdmin) return false; // Admins cannot delete themselves return CurrentUser?.Id != targetUserId; } private void NotifyStateChanged() => OnChange?.Invoke(); }