< Summary

Information
Class: Anichron.API.Endpoints.SessionResponse
Assembly: Anichron.API
File(s): /home/runner/work/anichron/anichron/src/Anichron.API/Endpoints/AuthEndpoints.cs
Tag: 19_45211875487
Line coverage
100%
Covered lines: 5
Uncovered lines: 0
Coverable lines: 5
Total lines: 114
Line coverage: 100%
Branch coverage
N/A
Covered branches: 0
Total branches: 0
Branch coverage: N/A
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%11100%

File(s)

/home/runner/work/anichron/anichron/src/Anichron.API/Endpoints/AuthEndpoints.cs

#LineLine coverage
 1using Anichron.API.Infrastructure;
 2using Anichron.API.Services;
 3using Microsoft.AspNetCore.Mvc;
 4using System.Text.Json.Serialization;
 5
 6namespace Anichron.API.Endpoints;
 7
 8public static class AuthEndpoints
 9{
 10    internal const string RefreshTokenCookieName = "refresh_token";
 11
 12    public static IEndpointRouteBuilder MapAuthEndpoints(this IEndpointRouteBuilder app)
 13    {
 14        var group = app.MapGroup(ApiPaths.Auth.Group).WithTags("Auth");
 15
 16        group.MapPost(ApiPaths.Auth.Register, RegisterAsync).AllowAnonymous().RequireRateLimit(AuthRateLimitPolicies.Sen
 17             .Produces<SessionResponse>()
 18             .ProducesValidationProblem(StatusCodes.Status409Conflict)
 19             .ProducesValidationProblem(StatusCodes.Status422UnprocessableEntity);
 20        group.MapPost(ApiPaths.Auth.Login, LoginWebAsync).AllowAnonymous().RequireRateLimit(AuthRateLimitPolicies.Sensit
 21             .Produces<SessionResponse>()
 22             .ProducesProblem(StatusCodes.Status401Unauthorized);
 23        group.MapPost(ApiPaths.Auth.LoginMobile, LoginMobileAsync).AllowAnonymous().RequireRateLimit(AuthRateLimitPolici
 24             .Produces<SessionResponse>()
 25             .ProducesProblem(StatusCodes.Status401Unauthorized);
 26        group.MapPost(ApiPaths.Auth.Refresh, RefreshAsync).AllowAnonymous().RequireRateLimit(AuthRateLimitPolicies.Refre
 27             .Produces<SessionResponse>()
 28             .ProducesProblem(StatusCodes.Status401Unauthorized);
 29        group.MapPost(ApiPaths.Auth.Logout, LogoutAsync).RequireUserAllowedWhileMustChangePassword()
 30             .Produces(StatusCodes.Status204NoContent);
 31        group.MapPost(ApiPaths.Auth.PasswordResetRequest, PasswordResetRequest).AllowAnonymous().RequireRateLimit(AuthRa
 32             .Produces(StatusCodes.Status501NotImplemented);
 33        group.MapPost(ApiPaths.Auth.PasswordResetConfirm, PasswordResetConfirm).AllowAnonymous().RequireRateLimit(AuthRa
 34             .Produces(StatusCodes.Status501NotImplemented);
 35
 36        return app;
 37    }
 38
 39    internal static async Task<IResult> RegisterAsync(
 40        RegisterRequest request,
 41        IAuthService auth,
 42        ISessionResponseMapper mapper,
 43        HttpContext http,
 44        CancellationToken ct)
 45    {
 46        var result = await auth.RegisterAsync(request.Username, request.Email, request.Password, request.InviteToken, ct
 47        return mapper.GetRegistrationResult(result, http);
 48    }
 49
 50    internal static Task<IResult> LoginWebAsync(
 51        LoginRequest request, IAuthService auth, ISessionResponseMapper mapper, HttpContext http, CancellationToken ct)
 52        => HandleLoginAsync(request, auth, mapper, http, setCookie: true, ct);
 53
 54    internal static Task<IResult> LoginMobileAsync(
 55        LoginRequest request, IAuthService auth, ISessionResponseMapper mapper, HttpContext http, CancellationToken ct)
 56        => HandleLoginAsync(request, auth, mapper, http, setCookie: false, ct);
 57
 58    private static async Task<IResult> HandleLoginAsync(
 59        LoginRequest request, IAuthService auth, ISessionResponseMapper mapper, HttpContext http, bool setCookie, Cancel
 60    {
 61        var result = await auth.LoginAsync(request.UsernameOrEmail, request.Password, ct);
 62        return mapper.GetLoginResult(result, http, setCookie);
 63    }
 64
 65    internal static async Task<IResult> RefreshAsync(
 66        HttpContext http,
 67        IAuthService auth,
 68        ISessionResponseMapper mapper,
 69        // [FromBody] is explicit here because the request is nullable —
 70        // web clients send no body (token arrives via cookie), mobile clients send it in the body.
 71        [FromBody] RefreshRequest? request,
 72        CancellationToken ct)
 73    {
 74        var rawToken = http.Request.Cookies[RefreshTokenCookieName] ?? request?.RefreshToken;
 75        if (rawToken is null)
 76        {
 77            return ApiProblems.Problem(
 78                StatusCodes.Status401Unauthorized, ErrorCodes.RefreshTokenRequired, ProblemMessages.RefreshTokenRequired
 79        }
 80
 81        var result = await auth.RefreshAsync(rawToken, ct);
 82        return mapper.GetRefreshResult(result, http);
 83    }
 84
 85    internal static async Task<IResult> LogoutAsync(
 86        HttpContext http, IAuthService auth, ISessionResponseMapper mapper, [FromBody] RefreshRequest? request, Cancella
 87    {
 88        var rawToken = http.Request.Cookies[RefreshTokenCookieName] ?? request?.RefreshToken;
 89        mapper.ClearSessionCookies(http);
 90        if (rawToken is not null)
 91            await auth.RevokeAsync(rawToken, ct);
 92        return Results.NoContent();
 93    }
 94
 95    // Not yet implemented — planned for Epic 8 (email notifications with deep links).
 96    private static IResult PasswordResetRequest() => Results.StatusCode(StatusCodes.Status501NotImplemented);
 97
 98    private static IResult PasswordResetConfirm() => Results.StatusCode(StatusCodes.Status501NotImplemented);
 99}
 100
 101public sealed record RegisterRequest(string Username, string Email, string Password, string InviteToken);
 102public sealed record LoginRequest(string UsernameOrEmail, string Password);
 103public sealed record RefreshRequest(string RefreshToken);
 104
 105/// <summary>A new or renewed session, with the refresh token only when it is not set as a cookie.</summary>
 106/// <param name="AccessToken">The access token.</param>
 107/// <param name="ExpiresIn">The access token's remaining lifetime in whole seconds.</param>
 108/// <param name="User">The signed-in user.</param>
 109/// <param name="RefreshToken">The refresh token, for a client that keeps it itself.</param>
 29110public sealed record SessionResponse(
 29111    string AccessToken,
 29112    int ExpiresIn,
 29113    UserProfileResponse User,
 29114    [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? RefreshToken = null);