diff options
| author | ivarlovlie <git@ivarlovlie.no> | 2022-12-21 23:37:23 +0100 |
|---|---|---|
| committer | ivarlovlie <git@ivarlovlie.no> | 2022-12-21 23:37:23 +0100 |
| commit | 82ade3c31fb17b662feec59e9e654ceb66edbb7a (patch) | |
| tree | 26443c41c55d2cd2ae46fdd0d663aca84b779ffe /code/api/Services | |
| parent | e60703aadca7d423c0fbfb189d5ef439fc1df072 (diff) | |
| download | storage-82ade3c31fb17b662feec59e9e654ceb66edbb7a.tar.xz storage-82ade3c31fb17b662feec59e9e654ceb66edbb7a.zip | |
feat: Add initial schema and start login
Diffstat (limited to 'code/api/Services')
| -rw-r--r-- | code/api/Services/Admin/UserService.cs | 53 |
1 files changed, 53 insertions, 0 deletions
diff --git a/code/api/Services/Admin/UserService.cs b/code/api/Services/Admin/UserService.cs new file mode 100644 index 0000000..94a64ef --- /dev/null +++ b/code/api/Services/Admin/UserService.cs @@ -0,0 +1,53 @@ +using System.Security.Claims; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authentication.Cookies; + +namespace I2R.Storage.Api.Services.Admin; + +public class UserService +{ + private readonly AppDatabase _database; + private readonly ILogger<UserService> _logger; + + public UserService(AppDatabase database, ILogger<UserService> logger) { + _database = database; + _logger = logger; + } + + public bool CanCreateAccount(string username) { + if (username.IsNullOrWhiteSpace()) { + return false; + } + + var normalisedUsername = username.Trim(); + return _database.Users.All(c => c.Username != normalisedUsername); + } + + public async Task LogInUserAsync(HttpContext httpContext, IEnumerable<Claim> claims) { + var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); + var principal = new ClaimsPrincipal(identity); + var authenticationProperties = new AuthenticationProperties { + AllowRefresh = true, + IssuedUtc = DateTimeOffset.UtcNow, + }; + + await httpContext.SignInAsync(principal, authenticationProperties); + _logger.LogInformation("Logged in user {userId}", principal.FindFirstValue(AppClaims.USER_ID)); + } + + public async Task LogOutUserAsync(HttpContext httpContext, CancellationToken cancellationToken = default) { + await httpContext.SignOutAsync(); + _logger.LogInformation("Logged out user {userId}", httpContext.User.FindFirstValue(AppClaims.USER_ID)); + } + + public async Task MarkUserAsDeleted(Guid userId, Guid actorId) { + var user = _database.Users.FirstOrDefault(c => c.Id == userId); + if (user == default) { + _logger.LogInformation("Tried to delete unknown user {userId}", userId); + return; + } + + user.SetDeleted(actorId); + await _database.SaveChangesAsync(); + } +}
\ No newline at end of file |
