| | | 1 | | // SPDX-FileCopyrightText: 2026 Alper Çelik <[email protected]> |
| | | 2 | | // |
| | | 3 | | // SPDX-License-Identifier: AGPL-3.0-or-later |
| | | 4 | | |
| | | 5 | | using System.Text; |
| | | 6 | | |
| | | 7 | | using Api.Auth.Utils; |
| | | 8 | | using Api.Database; |
| | | 9 | | |
| | | 10 | | using FluentValidation; |
| | | 11 | | |
| | | 12 | | using Geralt; |
| | | 13 | | |
| | | 14 | | using Microsoft.AspNetCore.Http.HttpResults; |
| | | 15 | | using Microsoft.AspNetCore.Mvc; |
| | | 16 | | using Microsoft.EntityFrameworkCore; |
| | | 17 | | |
| | | 18 | | namespace Api.Auth.Endpoints; |
| | | 19 | | |
| | | 20 | | public static class LoginEndpoints |
| | | 21 | | { |
| | | 22 | | public static void Map(IEndpointRouteBuilder route) |
| | 1 | 23 | | { |
| | 1 | 24 | | route.MapPost("login", Login); |
| | 1 | 25 | | } |
| | | 26 | | |
| | | 27 | | public static async Task< |
| | | 28 | | Results< |
| | | 29 | | Ok<LoginUtils.LoginResultDTO>, |
| | | 30 | | ForbidHttpResult |
| | | 31 | | >> Login( |
| | | 32 | | [FromServices] HttpContext ctx, |
| | | 33 | | [FromServices] PGContext db, |
| | | 34 | | [FromHeader(Name = "user-agent")] string userAgent, |
| | | 35 | | [FromBody] LoginDTO loginDTO |
| | | 36 | | ) |
| | 0 | 37 | | { |
| | 0 | 38 | | Guid? userId = null; |
| | 0 | 39 | | string hash = string.Empty; |
| | | 40 | | |
| | 0 | 41 | | if (loginDTO.UserEmail is not null) |
| | 0 | 42 | | { |
| | 0 | 43 | | var user = await db.Users |
| | 0 | 44 | | .Where(u => u.Email == loginDTO.UserEmail) |
| | 0 | 45 | | .Select(u => new { u.Id, u.PasswordHash }) |
| | 0 | 46 | | .FirstAsync(); |
| | 0 | 47 | | userId = user.Id; |
| | 0 | 48 | | hash = user.PasswordHash; |
| | 0 | 49 | | } |
| | | 50 | | |
| | 0 | 51 | | var password = Encoding.UTF8.GetBytes(loginDTO.Password.Normalize()); |
| | 0 | 52 | | if (userId is not null && |
| | 0 | 53 | | Argon2id.VerifyHash(hash, password)) |
| | 0 | 54 | | { |
| | 0 | 55 | | var token = await LoginUtils.CreateUserSession(userId.Value, userAgent, db); |
| | 0 | 56 | | await db.SaveChangesAsync(); |
| | | 57 | | |
| | 0 | 58 | | return LoginUtils.LogUserIn(ctx, token); |
| | | 59 | | } |
| | 0 | 60 | | return TypedResults.Forbid(); |
| | 0 | 61 | | } |
| | | 62 | | |
| | | 63 | | |
| | 0 | 64 | | public record LoginDTO(string UserEmail, string Password); |
| | | 65 | | } |