Files
Core_Be/Services/PermissionService.cs
Dhananjaya99 bffc9b1686 first commit
2026-09-28 11:44:26 +05:30

64 lines
2.8 KiB
C#

using Fitness_core_BE.Helpers;
using Fitness_core_BE.Interfaces;
using Fitness_core_BE.Interfaces.Services;
using Microsoft.AspNetCore.Http;
namespace Fitness_core_BE.Services
{
public class PermissionService : IPermissionService
{
private readonly UserRoleHelper _userRoleHelper;
private readonly IStaffRepository _staffRepository;
private readonly IGymRoleRepository _gymRoleRepository;
private readonly INavItemRepository _navItemRepository;
public PermissionService(
UserRoleHelper userRoleHelper,
IStaffRepository staffRepository,
IGymRoleRepository gymRoleRepository,
INavItemRepository navItemRepository)
{
_userRoleHelper = userRoleHelper;
_staffRepository = staffRepository;
_gymRoleRepository = gymRoleRepository;
_navItemRepository = navItemRepository;
}
public async Task<PermissionContext> GetPermissionContextAsync(HttpContext httpContext)
{
var userId = DataExtractor.GetUserIdFromContext(httpContext);
// Owner check first: the gym owner always has full access and never touches
// GymRole/GymRolePermission at all.
var clientId = await _userRoleHelper.GetOwnedClientId(userId);
if (clientId.HasValue)
{
var allKeys = (await _navItemRepository.GetActiveNavItemsOrdered())
.Select(n => n.Key)
.ToHashSet();
return new PermissionContext(IsOwner: true, ClientId: clientId, StaffId: null, AllowedNavKeys: allKeys);
}
var staffId = await _userRoleHelper.GetStaffId(userId);
if (staffId.HasValue)
{
var staff = await _staffRepository.GetStaffById(staffId.Value);
if (staff?.FKGymRoleId is Guid gymRoleId && staff.GymRole?.IsActive == true)
{
var keys = (await _gymRoleRepository.GetPermissionKeys(gymRoleId)).ToHashSet();
return new PermissionContext(IsOwner: false, ClientId: null, StaffId: staffId, AllowedNavKeys: keys);
}
// Staff with no role assigned yet: dashboard only, not zero -- so forgetting
// to assign a role (the create-staff flow makes it optional) leaves someone
// with a blank-but-working dashboard instead of a fully broken login.
return new PermissionContext(IsOwner: false, ClientId: null, StaffId: staffId, AllowedNavKeys: new HashSet<string> { "dashboard" });
}
// Neither owner nor staff (e.g. Customer/Admin token hitting a client-scoped endpoint).
return new PermissionContext(IsOwner: false, ClientId: null, StaffId: null, AllowedNavKeys: new HashSet<string>());
}
}
}