File size: 1,477 Bytes
72f2be7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
using Microsoft.EntityFrameworkCore;
using System.Security.Claims;
using TaskTrackingSystem.Database.AppDbContextModels;

namespace TaskTrackingSystem.WebApi.Infrastructure;

public class PermissionAuthorizationService
{
    private readonly AppDbContext _db;

    public PermissionAuthorizationService(AppDbContext db)
    {
        _db = db;
    }

    public async Task<bool> CanAccessAsync(ClaimsPrincipal user, string apiName, string actionName)
    {
        if (user.Identity?.IsAuthenticated != true)
        {
            return false;
        }

        var roleId = await ResolveRoleIdAsync(user);
        if (roleId <= 0)
        {
            return false;
        }

        return await _db.RolePermissions
            .AnyAsync(rp =>
                rp.RoleId == roleId &&
                !rp.IsDeleted &&
                !rp.Permission.IsDeleted &&
                rp.Permission.ApiName == apiName &&
                rp.Permission.ActionName == actionName);
    }

    private async Task<long> ResolveRoleIdAsync(ClaimsPrincipal user)
    {
        var roleId = user.GetRoleId();
        if (roleId > 0)
        {
            return roleId;
        }

        var roleName = user.GetRoleName();
        if (string.IsNullOrWhiteSpace(roleName))
        {
            return 0;
        }

        return await _db.Roles
            .Where(r => r.Name == roleName && r.IsDeleted != true)
            .Select(r => r.Id)
            .FirstOrDefaultAsync();
    }
}