UserRoleAccessPermissionHelper.cs
2.58 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
using System.Text.Json;
using FoodLabeling.Application.Contracts.Constants;
using SqlSugar;
using Volo.Abp.Users;
namespace FoodLabeling.Application.Helpers;
/// <summary>
/// 当前用户角色上的「访问权限」勾选项(Role.AccessPermissionCodesJson)。
/// </summary>
public static class UserRoleAccessPermissionHelper
{
public static async Task<List<string>> ResolveMergedAccessPermissionCodesAsync(
ISqlSugarClient db,
Guid userId)
{
var jsonRows = await db.Ado.SqlQueryAsync<string?>(
@"SELECT r.AccessPermissionCodesJson
FROM UserRole ur
INNER JOIN Role r ON ur.RoleId = r.Id
WHERE ur.UserId = @UserId AND r.IsDeleted = 0 AND r.State = 1
AND r.AccessPermissionCodesJson IS NOT NULL AND TRIM(r.AccessPermissionCodesJson) <> ''",
new { UserId = userId });
var merged = new HashSet<string>(StringComparer.Ordinal);
foreach (var json in jsonRows)
{
foreach (var code in DeserializeAccessPermissionCodes(json))
{
merged.Add(code);
}
}
return merged.OrderBy(x => x, StringComparer.Ordinal).ToList();
}
public static bool HasManagePeoplePermission(IReadOnlyList<string> codes) =>
codes.Any(c => string.Equals(c.Trim(), RoleAccessPermissionCodes.ManagePeople, StringComparison.Ordinal));
public static bool HasAllKnownAccessPermissions(IReadOnlyList<string> codes)
{
if (codes.Count == 0)
{
return false;
}
var set = new HashSet<string>(codes.Select(x => x.Trim()), StringComparer.Ordinal);
return RoleAccessPermissionCodes.All.All(set.Contains);
}
public static bool CanManageRegionAndLocationByAccessPermissions(IReadOnlyList<string> codes) =>
HasManagePeoplePermission(codes) || HasAllKnownAccessPermissions(codes);
private static List<string> DeserializeAccessPermissionCodes(string? json)
{
if (string.IsNullOrWhiteSpace(json))
{
return new List<string>();
}
try
{
var raw = JsonSerializer.Deserialize<List<string>>(json);
if (raw is null)
{
return new List<string>();
}
return raw
.Select(x => x?.Trim() ?? "")
.Where(x => x.Length > 0 && RoleAccessPermissionCodes.IsKnown(x))
.Distinct(StringComparer.Ordinal)
.ToList();
}
catch
{
return new List<string>();
}
}
}