-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathChangeNameUseCase.cs
More file actions
54 lines (45 loc) · 1.91 KB
/
Copy pathChangeNameUseCase.cs
File metadata and controls
54 lines (45 loc) · 1.91 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
using Dfe.SignIn.Base.Framework;
using Dfe.SignIn.Core.Contracts.Audit;
using Dfe.SignIn.Core.Contracts.Users;
using Dfe.SignIn.Gateways.EntityFramework;
using Microsoft.EntityFrameworkCore;
namespace Dfe.SignIn.Core.UseCases.Users;
/// <summary>
/// An interactor to change the job title of a user.
/// </summary>
public sealed class ChangeNameUseCase(
DbDirectoriesContext unitOfWork,
IInteractionDispatcher interaction
) : Interactor<ChangeNameRequest, ChangeNameResponse>
{
/// <inheritdoc/>
public override async Task<ChangeNameResponse> InvokeAsync(
InteractionContext<ChangeNameRequest> context,
CancellationToken cancellationToken = default)
{
context.ThrowIfHasValidationErrors();
var user = await unitOfWork.Users
.Where(x => x.Sub == context.Request.UserId)
.FirstOrDefaultAsync(cancellationToken) ?? throw UserNotFoundException.FromUserId(context.Request.UserId);
if (user.FirstName == context.Request.FirstName && user.LastName == context.Request.LastName) {
return new ChangeNameResponse();
}
if (user.FirstName != context.Request.FirstName) {
var normalisedFirstName = context.Request.FirstName.NormalizeWhitespace();
user.FirstName = normalisedFirstName;
}
if (user.LastName != context.Request.LastName) {
var normalisedLastName = context.Request.LastName.NormalizeWhitespace();
user.LastName = normalisedLastName;
}
await unitOfWork.SaveChangesAsync(cancellationToken);
await interaction.DispatchAsync(
new WriteToAuditRequest {
EventCategory = AuditEventCategoryNames.ChangeJobTitle,
Message = $"Successfully changed users name to {user.FirstName} {user.LastName}",
UserId = context.Request.UserId,
}
);
return new ChangeNameResponse();
}
}