aboutsummaryrefslogtreecommitdiffstats
path: root/code/api/src/Services/UserService.cs
blob: 9c6132cfcd7a161dfae18720482ca652d0a6aef0 (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
namespace IOL.GreatOffice.Api.Services;

public class UserService
{
    private readonly PasswordResetService _passwordResetService;
    private readonly ILogger<UserService> _logger;

    public UserService(PasswordResetService passwordResetService, ILogger<UserService> logger) {
        _passwordResetService = passwordResetService;
        _logger = logger;
    }

    public async Task LogInUserAsync(HttpContext httpContext, User user, bool persist = false) {
        var identity = new ClaimsIdentity(user.DefaultClaims(), 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 {userId}", user.Id);
    }

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