marco.pms.api/Marco.Pms.Services/Service/PermissionServices.cs

73 lines
3.0 KiB
C#

using Marco.Pms.DataAccess.Data;
using Marco.Pms.Model.Employees;
using Marco.Pms.Model.Entitlements;
using Marco.Pms.Services.Helpers;
using MarcoBMS.Services.Helpers;
using Microsoft.EntityFrameworkCore;
namespace Marco.Pms.Services.Service
{
public class PermissionServices
{
private readonly ApplicationDbContext _context;
private readonly RolesHelper _rolesHelper;
private readonly CacheUpdateHelper _cache;
public PermissionServices(ApplicationDbContext context, RolesHelper rolesHelper, CacheUpdateHelper cache)
{
_context = context;
_rolesHelper = rolesHelper;
_cache = cache;
}
public async Task<bool> HasPermission(Guid featurePermissionId, Guid employeeId)
{
var featurePermissionIds = await _cache.GetPermissions(employeeId);
if (featurePermissionIds == null)
{
List<FeaturePermission> featurePermission = await _rolesHelper.GetFeaturePermissionByEmployeeId(employeeId);
featurePermissionIds = featurePermission.Select(fp => fp.Id).ToList();
}
var hasPermission = featurePermissionIds.Contains(featurePermissionId);
return hasPermission;
}
public async Task<bool> HasPermissionAny(List<Guid> featurePermissionIds, Guid employeeId)
{
var allFeaturePermissionIds = await _cache.GetPermissions(employeeId);
if (allFeaturePermissionIds == null)
{
List<FeaturePermission> featurePermission = await _rolesHelper.GetFeaturePermissionByEmployeeId(employeeId);
allFeaturePermissionIds = featurePermission.Select(fp => fp.Id).ToList();
}
var hasPermission = featurePermissionIds.Any(f => allFeaturePermissionIds.Contains(f));
return hasPermission;
}
public async Task<bool> HasProjectPermission(Employee LoggedInEmployee, Guid projectId)
{
var employeeId = LoggedInEmployee.Id;
var projectIds = await _cache.GetProjects(employeeId);
if (projectIds == null)
{
var hasPermission = await HasPermission(PermissionsMaster.ManageProject, employeeId);
if (hasPermission)
{
var projects = await _context.Projects.Where(c => c.TenantId == LoggedInEmployee.TenantId).ToListAsync();
projectIds = projects.Select(p => p.Id).ToList();
}
else
{
var allocation = await _context.ProjectAllocations.Where(c => c.EmployeeId == employeeId && c.IsActive).ToListAsync();
if (!allocation.Any())
{
return false;
}
projectIds = allocation.Select(c => c.ProjectId).Distinct().ToList();
}
await _cache.AddProjects(LoggedInEmployee.Id, projectIds);
}
return projectIds.Contains(projectId);
}
}
}