aboutsummaryrefslogtreecommitdiffstats
path: root/code/api/src/Services/UserService.cs
blob: 8b925be9ba61f7dbb405a68911c5e1d01b11639b (plain) (blame)
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
using IOL.GreatOffice.Api.Data.Database.Queues;
using Microsoft.Extensions.Localization;

namespace IOL.GreatOffice.Api.Services;

public class UserService
{
    private readonly PasswordResetService _passwordResetService;
    private readonly MailService _mailService;
    private readonly ILogger<UserService> _logger;
    private readonly IStringLocalizer<SharedResources> _localizer;
    private readonly MainAppDatabase _database;
    private string EmailValidationUrl;

    public UserService(PasswordResetService passwordResetService, MailService mailService, IStringLocalizer<SharedResources> localizer, VaultService vaultService, MainAppDatabase database) {
        _passwordResetService = passwordResetService;
        _mailService = mailService;
        _localizer = localizer;
        _database = database;
        var configuration = vaultService.GetCurrentAppConfiguration();
        EmailValidationUrl = configuration.CANONICAL_BACKEND_URL + "/validate";
    }

    public async Task LogInUser(HttpContext httpContext, User user, bool persist = false) {
        var claims = new List<Claim> {
            new(AppClaims.USER_ID, user.Id.ToString()),
            new(AppClaims.NAME, user.Username),
        };

        var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
        var principal = new ClaimsPrincipal(identity);
        var authenticationProperties = new AuthenticationProperties {
            AllowRefresh = true,
            IssuedUtc = DateTimeOffset.UtcNow,
        };

        if (persist) {
            authenticationProperties.ExpiresUtc = DateTimeOffset.UtcNow.AddMonths(6);
            authenticationProperties.IsPersistent = true;
        }

        await httpContext.SignInAsync(principal, authenticationProperties);
        await _passwordResetService.DeleteRequestsForUserAsync(user.Id);
        _logger.LogInformation("Logged in user {0}", user.Id);
    }

    public async Task LogOutUser(HttpContext httpContext) {
        await httpContext.SignOutAsync();
        _logger.LogInformation("Logged out user {0}", httpContext.User.FindFirst(AppClaims.USER_ID));
    }

    public async Task SendValidationEmail(User user) {
        var email = new MailService.PostmarkEmail() {
            To = user.Username,
            Subject = _localizer["Greatoffice Email Validation"],
            TextBody = _localizer["""
Hello, {0}.

Validate your email address by opening this link in a browser {1}
""", user.DisplayName(), EmailValidationUrl + "?email=" + user.Username]
        };
        var queueItem = new ValidationEmail() {
            UserId = user.Id,
            Id = Guid.NewGuid()
        };
        await _mailService.SendMail(email);
        queueItem.EmailSentAt = DateTime.UtcNow;
        _database.ValidationEmails.Add(queueItem);
        await _database.SaveChangesAsync();
    }
}