| | | 1 | | // SPDX-FileCopyrightText: 2026 Alper Çelik <[email protected]> |
| | | 2 | | // |
| | | 3 | | // SPDX-License-Identifier: AGPL-3.0-or-later |
| | | 4 | | |
| | | 5 | | using System.Buffers.Text; |
| | | 6 | | using System.Security.Claims; |
| | | 7 | | using System.Text.Encodings.Web; |
| | | 8 | | |
| | | 9 | | using Api.Auth.Models; |
| | | 10 | | using Api.Auth.Utils; |
| | | 11 | | using Api.Database; |
| | | 12 | | |
| | | 13 | | using Microsoft.AspNetCore.Authentication; |
| | | 14 | | using Microsoft.EntityFrameworkCore; |
| | | 15 | | using Microsoft.Extensions.Options; |
| | | 16 | | |
| | | 17 | | namespace Api.Auth.Handlers; |
| | | 18 | | |
| | | 19 | | class AuthHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder, PGCon |
| | 1 | 20 | | : AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder) |
| | | 21 | | { |
| | | 22 | | protected override async Task<AuthenticateResult> HandleAuthenticateAsync() |
| | 1 | 23 | | { |
| | 1 | 24 | | string?[] tokenHashes = [Context.Request.Headers.Authorization.LastOrDefault(), Context.Request.Cookies[LoginUti |
| | 1 | 25 | | List<byte[]> userTokenHashes = [.. tokenHashes |
| | 1 | 26 | | .Where(s => s != null && s.StartsWith(LoginUtils.UserTokenPrefix)) |
| | 0 | 27 | | .Select(s => Base64Url.DecodeFromChars( |
| | 0 | 28 | | s.AsSpan()[(LoginUtils.UserTokenPrefix.Length - 1)..]))]; |
| | | 29 | | |
| | 1 | 30 | | var userToken = await db.UserTokens.Where(ut => userTokenHashes.Contains(ut.TokenHash)).FirstOrDefaultAsync(); |
| | | 31 | | |
| | 1 | 32 | | if (userToken is not null) |
| | 0 | 33 | | { |
| | 0 | 34 | | await LoginUtils.UpdateLastUsedForUserToken(userToken, db); |
| | | 35 | | |
| | | 36 | | |
| | 0 | 37 | | Claim[] claims = [ |
| | 0 | 38 | | new Claim(ClaimTypes.NameIdentifier,userToken.UserId.ToString()), |
| | 0 | 39 | | new Claim(UserToken.PermissionBitsType,((long)userToken.Permissions).ToString()), |
| | 0 | 40 | | ]; |
| | | 41 | | |
| | 0 | 42 | | return AuthenticateResult.Success( |
| | 0 | 43 | | new AuthenticationTicket( |
| | 0 | 44 | | new ClaimsPrincipal( |
| | 0 | 45 | | new ClaimsPrincipal(new ClaimsIdentity( |
| | 0 | 46 | | claims |
| | 0 | 47 | | ) |
| | 0 | 48 | | ) |
| | 0 | 49 | | ), |
| | 0 | 50 | | Scheme.Name) |
| | 0 | 51 | | ); |
| | | 52 | | } |
| | | 53 | | |
| | | 54 | | |
| | 1 | 55 | | return AuthenticateResult.NoResult(); |
| | 1 | 56 | | } |
| | | 57 | | |
| | | 58 | | } |