Read-only mirrors. Development, issues and pull requests are on GitHub.

summaryrefslogtreecommitdiffhomepage
path: root/apps/api/Accounts/AccountEndpoints.cs
blob: 5e9fb9de91428d1860b4a75eb13ccecd4c908ba2 (plain)
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com>
// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.0

namespace Progmasoft.Progmaweb.Api.Accounts;

using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Google;

internal static class AccountEndpoints
{
    internal const string ExternalCookieScheme = "ProgmasoftExternal";

    public static IEndpointRouteBuilder MapAccountEndpoints(this IEndpointRouteBuilder endpoints)
    {
        RouteGroupBuilder accounts = endpoints.MapGroup("/api/v1/accounts");

        accounts.MapPost("/register", RegisterAsync).RequireRateLimiting("account-auth");
        accounts.MapPost("/login", LoginAsync).RequireRateLimiting("account-auth");
        accounts.MapPost("/logout", LogoutAsync);
        accounts.MapGet("/me", MeAsync);
        accounts.MapGet("/oauth/google/start", StartGoogleAsync).RequireRateLimiting("account-auth");
        accounts.MapGet("/oauth/google/complete", CompleteGoogleAsync).RequireRateLimiting("account-auth");

        return endpoints;
    }

    private static IResult StartGoogleAsync(string? accountName, IConfiguration configuration)
    {
        if (string.IsNullOrWhiteSpace(configuration["Authentication:Google:ClientId"]) ||
            string.IsNullOrWhiteSpace(configuration["Authentication:Google:ClientSecret"]))
        {
            return Results.Problem(
                title: "Google sign-in is unavailable",
                detail: "The Google identity provider has not been configured.",
                statusCode: StatusCodes.Status503ServiceUnavailable);
        }

        string? normalized = null;
        if (accountName is not null && !AccountNamePolicy.TryNormalize(accountName, out normalized, out _))
        {
            return Results.Redirect("/register?google=invalid-account-name");
        }

        AuthenticationProperties properties = new()
        {
            RedirectUri = "/api/v1/accounts/oauth/google/complete"
        };
        if (normalized is not null)
        {
            properties.Items["accountName"] = normalized;
        }

        return Results.Challenge(properties, [GoogleDefaults.AuthenticationScheme]);
    }

    private static async Task<IResult> CompleteGoogleAsync(
        AccountService accounts,
        SessionService sessions,
        HttpContext context,
        CancellationToken cancellationToken)
    {
        AuthenticateResult external = await context.AuthenticateAsync(ExternalCookieScheme);
        if (!external.Succeeded || external.Principal is null)
        {
            return Results.Redirect("/login?google=failed");
        }

        string? email = external.Principal.FindFirstValue(ClaimTypes.Email);
        string? accountName = null;
        external.Properties?.Items.TryGetValue("accountName", out accountName);
        (AuthenticatedAccount? authentication, GoogleAccountFailure failure) =
            await accounts.AuthenticateGoogleAsync(email, accountName, sessions, cancellationToken);
        await context.SignOutAsync(ExternalCookieScheme);

        if (authentication is null)
        {
            string destination = failure switch
            {
                GoogleAccountFailure.AccountNameRequired => "/register?google=account-name-required",
                GoogleAccountFailure.InvalidAccountName => "/register?google=invalid-account-name",
                GoogleAccountFailure.AccountNameUnavailable => "/register?google=account-name-unavailable",
                _ => "/login?google=failed"
            };
            return Results.Redirect(destination);
        }

        WriteSessionCookie(context, sessions, authentication);
        return Results.Redirect($"/{Uri.EscapeDataString(authentication.Account.AccountName)}/dashboard");
    }

    private static async Task<IResult> RegisterAsync(
        RegisterAccountRequest request,
        AccountService accounts,
        SessionService sessions,
        HttpContext context,
        CancellationToken cancellationToken)
    {
        (AuthenticatedAccount? authentication, Dictionary<string, string[]> errors) =
            await accounts.RegisterAsync(request, sessions, cancellationToken);

        if (authentication is null)
        {
            return Results.ValidationProblem(errors);
        }

        WriteSessionCookie(context, sessions, authentication);
        return Results.Created($"/api/v1/accounts/{Uri.EscapeDataString(authentication.Account.AccountName)}",
            ToResponse(authentication.Account));
    }

    private static async Task<IResult> LoginAsync(
        LoginAccountRequest request,
        AccountService accounts,
        SessionService sessions,
        HttpContext context,
        CancellationToken cancellationToken)
    {
        AuthenticatedAccount? authentication = await accounts.LoginAsync(request, sessions, cancellationToken);
        if (authentication is null)
        {
            return Results.Problem(
                title: "Sign-in failed",
                detail: "The email address or password is incorrect.",
                statusCode: StatusCodes.Status401Unauthorized);
        }

        WriteSessionCookie(context, sessions, authentication);
        return Results.Ok(ToResponse(authentication.Account));
    }

    private static async Task<IResult> LogoutAsync(
        SessionService sessions,
        HttpContext context,
        CancellationToken cancellationToken)
    {
        context.Request.Cookies.TryGetValue(sessions.CookieName, out string? token);
        await sessions.RevokeAsync(token, cancellationToken);
        context.Response.Cookies.Delete(sessions.CookieName, new CookieOptions
        {
            HttpOnly = true,
            Path = "/",
            SameSite = SameSiteMode.Lax,
            Secure = true
        });
        return Results.NoContent();
    }

    private static async Task<IResult> MeAsync(
        SessionService sessions,
        HttpContext context,
        CancellationToken cancellationToken)
    {
        context.Request.Cookies.TryGetValue(sessions.CookieName, out string? token);
        AccountRecord? account = await sessions.AuthenticateAsync(token, cancellationToken);
        return account is null ? Results.Unauthorized() : Results.Ok(ToResponse(account));
    }

    private static void WriteSessionCookie(
        HttpContext context,
        SessionService sessions,
        AuthenticatedAccount authentication) =>
        context.Response.Cookies.Append(
            sessions.CookieName,
            authentication.SessionToken,
            SessionService.CreateCookieOptions(authentication.ExpiresAt));

    private static AccountResponse ToResponse(AccountRecord account) =>
        new(account.AccountName, account.Email, account.CreatedAt);
}