This repository has been archived by the owner on Dec 21, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
ActivateCopilotAccountCommand.cs
70 lines (60 loc) · 2.48 KB
/
ActivateCopilotAccountCommand.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
// This file is a part of MaaCopilotServer project.
// MaaCopilotServer belongs to the MAA organization.
// Licensed under the AGPL-3.0 license.
using System.ComponentModel.DataAnnotations;
using System.Text.Json.Serialization;
using MaaCopilotServer.Application.Common.Helpers;
using MaaCopilotServer.Domain.Enums;
using Microsoft.EntityFrameworkCore;
namespace MaaCopilotServer.Application.CopilotUser.Commands.ActivateCopilotAccount;
/// <summary>
/// The DTO for the ActivateCopilotAccount command.
/// </summary>
public record ActivateCopilotAccountCommand : IRequest<MaaApiResponse>
{
/// <summary>
/// Account activation token.
/// </summary>
[Required]
[JsonPropertyName("token")]
public string? Token { get; set; }
}
public class ActivateCopilotAccountCommandHandler : IRequestHandler<ActivateCopilotAccountCommand, MaaApiResponse>
{
private readonly ApiErrorMessage _apiErrorMessage;
private readonly IMaaCopilotDbContext _dbContext;
public ActivateCopilotAccountCommandHandler(
IMaaCopilotDbContext dbContext,
ApiErrorMessage apiErrorMessage)
{
_dbContext = dbContext;
_apiErrorMessage = apiErrorMessage;
}
public async Task<MaaApiResponse> Handle(ActivateCopilotAccountCommand request,
CancellationToken cancellationToken)
{
// Get token entity
var token = await _dbContext.CopilotTokens.FirstOrDefaultAsync(x => x.Token == request.Token,
cancellationToken);
// If token is null OR token is not valid now OR token is not for UserActivation, return a bad request response.
if (token is null || token.ValidBefore < DateTimeOffset.UtcNow || token.Type != TokenType.UserActivation)
{
return MaaApiResponseHelper.BadRequest(
_apiErrorMessage.TokenInvalid);
}
// Find user defined in token entity
var user = _dbContext.CopilotUsers.FirstOrDefault(x => x.EntityId == token.ResourceId);
if (user is null)
{
return MaaApiResponseHelper.InternalError(
string.Format(_apiErrorMessage.UserWithIdNotFound!, token.ResourceId.ToString()));
}
// Activate user and delete the token
user.ActivateUser(user.EntityId);
token.Delete(user.EntityId);
_dbContext.CopilotUsers.Update(user);
_dbContext.CopilotTokens.Remove(token);
await _dbContext.SaveChangesAsync(cancellationToken);
return MaaApiResponseHelper.Ok();
}
}