-
Notifications
You must be signed in to change notification settings - Fork 1
/
AssignRolesAuthorizationRequirement.cs
73 lines (52 loc) · 2.4 KB
/
AssignRolesAuthorizationRequirement.cs
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
// ====================================================
// More Templates: https://www.ebenmonney.com/templates
// Email: [email protected]
// ====================================================
using Microsoft.AspNetCore.Authorization;
using System;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
namespace Erpmi.Security
{
public class AssignRolesAuthorizationRequirement : IAuthorizationRequirement
{
}
public class AssignRolesAuthorizationHandler : AuthorizationHandler<AssignRolesAuthorizationRequirement, Tuple<string[], string[]>>
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, AssignRolesAuthorizationRequirement requirement, Tuple<string[], string[]> newAndCurrentRoles)
{
if (!GetIsRolesChanged(newAndCurrentRoles.Item1, newAndCurrentRoles.Item2))
{
context.Succeed(requirement);
}
else if (context.User.HasClaim(ClaimTypes.Permission, Permissions.AssignRoles))
{
if (context.User.HasClaim(ClaimTypes.Permission, Permissions.ViewRoles)) // If user has ViewRoles permission, then he can assign any roles
context.Succeed(requirement);
else if (GetIsUserInAllAddedRoles(context.User, newAndCurrentRoles.Item1, newAndCurrentRoles.Item2)) // Else user can only assign roles they're part of
context.Succeed(requirement);
}
return Task.CompletedTask;
}
private bool GetIsRolesChanged(string[] newRoles, string[] currentRoles)
{
if (newRoles == null)
newRoles = new string[] { };
if (currentRoles == null)
currentRoles = new string[] { };
bool roleAdded = newRoles.Except(currentRoles).Any();
bool roleRemoved = currentRoles.Except(newRoles).Any();
return roleAdded || roleRemoved;
}
private bool GetIsUserInAllAddedRoles(ClaimsPrincipal contextUser, string[] newRoles, string[] currentRoles)
{
if (newRoles == null)
newRoles = new string[] { };
if (currentRoles == null)
currentRoles = new string[] { };
var addedRoles = newRoles.Except(currentRoles);
return addedRoles.All(role => contextUser.IsInRole(role));
}
}
}