| Name | Message | Date |
|---|---|---|
| 📄 AdminAuthService.cs | 11 days ago |
📄
MatDenDagen/Services/AdminAuthService.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
using System; using System.ComponentModel.DataAnnotations; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace MatDenDagen.Services; public sealed class AdminAuthService( ILogger<AdminAuthService> logger, IOptions<AdminAuthOptions> options, TimeProvider timeProvider, IHttpContextAccessor httpContextAccessor ) { private readonly string hash = options.Value.Hash; private readonly TimeSpan loginTime = options.Value.LoginTime; public bool ValidatePassword(string password) => BCrypt.Net.BCrypt.Verify(password, hash); public async Task SignIn() { if (httpContextAccessor.HttpContext is not { } httpContext) { logger.LogError("No HttpContext when signing in."); return; } var now = timeProvider.GetUtcNow(); var authProperties = new AuthenticationProperties { IsPersistent = true, AllowRefresh = true, IssuedUtc = now, ExpiresUtc = now + loginTime, }; await httpContext.SignInAsync( CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal( new ClaimsIdentity([new(ClaimTypes.Role, "Admin")], CookieAuthenticationDefaults.AuthenticationScheme) ), authProperties ); } public async Task SignOut() { if (httpContextAccessor.HttpContext is not { } httpContext) { logger.LogError("No HttpContext when signing out."); return; } await httpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); } } public sealed class AdminAuthOptions { [Required] public required string Hash { get; set; } [Required] public required TimeSpan LoginTime { get; set; } } [OptionsValidator] public sealed partial class AdminAuthOptionsValidator : IValidateOptions<AdminAuthOptions>; public static class AdminAuthServiceCollectionExtensions { public static IServiceCollection AddAdminService(this IServiceCollection services) { services.AddOptions<AdminAuthOptions>().BindConfiguration("Admin").ValidateOnStart(); services.AddTransient<IValidateOptions<AdminAuthOptions>, AdminAuthOptionsValidator>(); services.AddHttpContextAccessor(); services.TryAddSingleton(TimeProvider.System); services.AddTransient<AdminAuthService>(); return services; } }