-
Notifications
You must be signed in to change notification settings - Fork 1
/
UserAccountAuthorizationRequirement.cs
77 lines (57 loc) · 2.65 KB
/
UserAccountAuthorizationRequirement.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
74
75
76
77
// ====================================================
// More Templates: https://www.ebenmonney.com/templates
// Email: [email protected]
// ====================================================
using Microsoft.AspNetCore.Authorization;
using System.Collections.Generic;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
namespace Erpmi.Security
{
public class UserAccountAuthorizationRequirement : IAuthorizationRequirement
{
public UserAccountAuthorizationRequirement(string operationName)
{
this.OperationName = operationName;
}
public string OperationName { get; private set; }
}
public class ViewUserAuthorizationHandler : AuthorizationHandler<UserAccountAuthorizationRequirement, int>
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, UserAccountAuthorizationRequirement requirement, int targetUserId)
{
if (context.User == null || requirement.OperationName != AccountManagementOperations.ReadOperationName)
return Task.CompletedTask;
if (context.User.HasClaim(ClaimTypes.Permission, Permissions.ViewUsers) || GetIsSameUser(context.User, targetUserId))
context.Succeed(requirement);
return Task.CompletedTask;
}
private bool GetIsSameUser(ClaimsPrincipal user, int targetUserId)
{
if (targetUserId <= 0)
return false;
return Utilities.GetUserId(user) == targetUserId;
}
}
public class ManageUserAuthorizationHandler : AuthorizationHandler<UserAccountAuthorizationRequirement, int>
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, UserAccountAuthorizationRequirement requirement, int targetUserId)
{
if (context.User == null ||
(requirement.OperationName != AccountManagementOperations.CreateOperationName &&
requirement.OperationName != AccountManagementOperations.UpdateOperationName &&
requirement.OperationName != AccountManagementOperations.DeleteOperationName))
return Task.CompletedTask;
if (context.User.HasClaim(ClaimTypes.Permission, Permissions.ManageUsers) || GetIsSameUser(context.User, targetUserId))
context.Succeed(requirement);
return Task.CompletedTask;
}
private bool GetIsSameUser(ClaimsPrincipal user, int targetUserId)
{
if (targetUserId <= 0)
return false;
return Utilities.GetUserId(user) == targetUserId;
}
}
}