-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathUpdateUserClaims.cs
More file actions
124 lines (109 loc) · 5.87 KB
/
Copy pathUpdateUserClaims.cs
File metadata and controls
124 lines (109 loc) · 5.87 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
using LantanaGroup.Link.Account.Application.Commands.AuditEvent;
using LantanaGroup.Link.Account.Application.Interfaces.Factories.User;
using LantanaGroup.Link.Account.Application.Interfaces.Persistence;
using LantanaGroup.Link.Account.Domain.Entities;
using LantanaGroup.Link.Account.Infrastructure;
using LantanaGroup.Link.Account.Infrastructure.Logging;
using LantanaGroup.Link.Shared.Application.Interfaces;
using LantanaGroup.Link.Shared.Application.Models;
using LantanaGroup.Link.Shared.Application.Models.Configs;
using LantanaGroup.Link.Shared.Application.Models.Kafka;
using Link.Authorization.Infrastructure;
using Microsoft.Extensions.Options;
using System.Diagnostics;
using System.Security.Claims;
namespace LantanaGroup.Link.Account.Application.Commands.User
{
public class UpdateUserClaims : IUpdateUserClaims
{
private readonly ILogger<UpdateUserClaims> _logger;
private readonly IUserRepository _userRepository;
private readonly ILinkUserModelFactory _userModelFactory;
private readonly ICreateAuditEvent _createAuditEvent;
private readonly IOptions<CacheSettings> _cacheSettings;
private readonly IServiceScopeFactory _serviceScopeFactory;
private readonly ICacheService _cache;
public UpdateUserClaims(ILogger<UpdateUserClaims> logger, IUserRepository userRepository, ICacheService cache, ILinkUserModelFactory userModelFactory, ICreateAuditEvent createAuditEvent)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_userRepository = userRepository ?? throw new ArgumentNullException(nameof(userRepository));
_userModelFactory = userModelFactory ?? throw new ArgumentNullException(nameof(userModelFactory));
_createAuditEvent = createAuditEvent ?? throw new ArgumentNullException(nameof(createAuditEvent));
_cache = cache ?? throw new ArgumentNullException(nameof(cache));
}
public async Task<bool> Execute(ClaimsPrincipal? requestor, Guid userId, List<string> claims, CancellationToken cancellationToken = default)
{
using Activity? activity = ServiceActivitySource.Instance.StartActivity("UpdateClaims:Execute");
try
{
var user = await _userRepository.GetUserAsync(userId, cancellationToken: cancellationToken) ?? throw new ApplicationException($"User with id {userId} not found");
var currentClaims = user.Claims;
var addedClaims = claims.Except(currentClaims.Select(c => c.ClaimValue));
var removedClaims = currentClaims.Select(c => c.ClaimValue).Except(claims);
if (addedClaims.Any() && removedClaims.Any() && requestor is not null)
{
user.LastModifiedBy = requestor?.Claims.FirstOrDefault(c => c.Type == "sub")?.Value;
}
foreach (var claim in addedClaims)
{
if (!string.IsNullOrEmpty(claim))
{
var newClaim = new Claim(LinkAuthorizationConstants.LinkSystemClaims.LinkPermissions, claim);
var outcome = await _userRepository.AddClaimToUserAsync(user.Id, newClaim, cancellationToken);
if (outcome)
{
_logger.LogUserClaimAssignment(user.Id.ToString(), newClaim.Type, newClaim.Value, requestor?.Claims.FirstOrDefault(c => c.Type == "sub")?.Value ?? "Unknown");
}
}
}
foreach (var claim in removedClaims)
{
var userClaim = currentClaims.FirstOrDefault(c => c.ClaimValue == claim);
if (userClaim is not null && !string.IsNullOrEmpty(userClaim.ClaimValue))
{
var removedClaim = new Claim(LinkAuthorizationConstants.LinkSystemClaims.LinkPermissions, userClaim.ClaimValue);
var outcome = await _userRepository.RemoveClaimFromUserAsync(user.Id, removedClaim, cancellationToken);
if (outcome)
{
_logger.LogUserClaimRemoval(user.Id.ToString(), removedClaim.Type, removedClaim.Value, requestor?.Claims.FirstOrDefault(c => c.Type == "sub")?.Value ?? "Unknown");
}
}
}
//Capture changes
List<PropertyChangeModel> changes = [];
if (addedClaims.Any() || removedClaims.Any())
{
changes.Add(new PropertyChangeModel("Claims", string.Join(",", currentClaims), string.Join(",", claims)));
}
//generate audit event
var auditMessage = new AuditEventMessage
{
Action = AuditEventType.Update,
EventDate = DateTime.UtcNow,
UserId = user.LastModifiedBy,
User = requestor?.Identity?.Name ?? string.Empty,
Resource = typeof(LinkUser).Name,
PropertyChanges = changes,
Notes = $"Role ({user.Id}) updated by '{user.LastModifiedBy}'."
};
_ = Task.Run(() => _createAuditEvent.Execute(auditMessage, cancellationToken));
//clear user cache if cache is enabled
var userKey = $"user:{user.Email}";
try
{
await _cache.RemoveAsync(userKey, cancellationToken);
}
catch (Exception ex)
{
_logger.LogCacheException(userKey, ex.Message);
}
return true;
}
catch (Exception)
{
activity?.SetStatus(ActivityStatusCode.Error);
throw;
}
}
}
}