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

summaryrefslogtreecommitdiffhomepage
path: root/apps/api/Accounts/AccountService.cs
blob: 7168eb613aee9ba458330e886da368caaf3c338d (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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com>
// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1

using Microsoft.AspNetCore.Identity;

namespace Progmasoft.Progmaweb.Api.Accounts;

internal sealed class AccountService(
    IAccountStore store,
    TimeProvider timeProvider)
{
    private static readonly AccountRecord DummyAccount = new(
        Guid.Empty,
        "Missing00",
        "MISSING00",
        "missing@example.invalid",
        "MISSING@EXAMPLE.INVALID",
        null,
        string.Empty,
        DateTimeOffset.UnixEpoch);
    private static readonly string DummyPasswordHash =
        new PasswordHasher<AccountRecord>().HashPassword(DummyAccount, "not-the-provided-password");

    private readonly PasswordHasher<AccountRecord> passwordHasher = new();

    public async ValueTask<(AuthenticatedAccount? Authentication, Dictionary<string, string[]> Errors)> RegisterAsync(
        RegisterAccountRequest request,
        SessionService sessions,
        CancellationToken cancellationToken)
    {
        Dictionary<string, string[]> errors = ValidateRegistration(request, out string accountName,
            out string email, out string normalizedEmail);
        if (errors.Count != 0)
        {
            return (null, errors);
        }

        AccountRecord provisional = new(
            Guid.NewGuid(),
            accountName,
            AccountNamePolicy.NormalizeForLookup(accountName),
            email,
            normalizedEmail,
            null,
            string.Empty,
            timeProvider.GetUtcNow());

        string passwordHash = passwordHasher.HashPassword(provisional, request.Password!);
        AccountRecord account = provisional with { PasswordHash = passwordHash };
        CreateAccountResult result = await store.CreateAsync(account, cancellationToken);

        if (result.Status is CreateAccountStatus.AccountNameUnavailable)
        {
            return (null, new Dictionary<string, string[]> { ["accountName"] = ["That account name is unavailable."] });
        }

        if (result.Status is CreateAccountStatus.EmailUnavailable)
        {
            return (null, new Dictionary<string, string[]> { ["email"] = ["That email address is already registered."] });
        }

        AuthenticatedAccount authentication = await sessions.CreateAsync(account, cancellationToken);
        return (authentication, errors);
    }

    public async ValueTask<AuthenticatedAccount?> LoginAsync(
        LoginAccountRequest request,
        SessionService sessions,
        CancellationToken cancellationToken)
    {
        if (!EmailAddressPolicy.TryNormalize(request.Email, out _, out string normalizedEmail, out _) ||
            request.Password is null || request.Password.Length > PasswordPolicy.MaximumLength)
        {
            return null;
        }

        AccountRecord? account = await store.FindByEmailAsync(normalizedEmail, cancellationToken);
        if (account is null || account.PasswordHash is null)
        {
            // Reuse one private hash so an unknown email follows one expensive verification, like a bad password.
            _ = passwordHasher.VerifyHashedPassword(DummyAccount, DummyPasswordHash, request.Password);
            return null;
        }

        PasswordVerificationResult verification =
            passwordHasher.VerifyHashedPassword(account, account.PasswordHash, request.Password);
        if (verification is PasswordVerificationResult.Failed)
        {
            return null;
        }

        return await sessions.CreateAsync(account, cancellationToken);
    }

    public async ValueTask<(AuthenticatedAccount? Authentication, GoogleAccountFailure Failure)>
        AuthenticateGoogleAsync(
            string? providerSubject,
            string? providerEmail,
            string? requestedAccountName,
            SessionService sessions,
            CancellationToken cancellationToken)
    {
        if (string.IsNullOrWhiteSpace(providerSubject) ||
            !EmailAddressPolicy.TryNormalize(providerEmail, out string email, out string normalizedEmail, out _))
        {
            return (null, GoogleAccountFailure.ProviderRejected);
        }

        AccountRecord? knownGoogleAccount =
            await store.FindByGoogleSubjectAsync(providerSubject, cancellationToken);
        if (knownGoogleAccount is not null)
        {
            return (await sessions.CreateAsync(knownGoogleAccount, cancellationToken), GoogleAccountFailure.None);
        }

        AccountRecord? existing = await store.FindByEmailAsync(normalizedEmail, cancellationToken);
        if (existing is not null)
        {
            // Password registrations do not verify ownership of the supplied email address yet. Automatically
            // linking a verified Google identity by email would therefore let two unrelated people share an
            // account (and any already-issued sessions) when one of them registered the other's address.
            return (null, GoogleAccountFailure.ProviderRejected);
        }

        if (requestedAccountName is null)
        {
            return (null, GoogleAccountFailure.AccountNameRequired);
        }

        if (!AccountNamePolicy.TryNormalize(requestedAccountName, out string accountName, out _))
        {
            return (null, GoogleAccountFailure.InvalidAccountName);
        }

        AccountRecord account = new(
            Guid.NewGuid(),
            accountName,
            AccountNamePolicy.NormalizeForLookup(accountName),
            email,
            normalizedEmail,
            providerSubject,
            null,
            timeProvider.GetUtcNow());
        CreateAccountResult result = await store.CreateAsync(account, cancellationToken);

        if (result.Status is CreateAccountStatus.AccountNameUnavailable)
        {
            return (null, GoogleAccountFailure.AccountNameUnavailable);
        }

        if (result.Status is CreateAccountStatus.EmailUnavailable)
        {
            // Any different identity can win the email race, including an unverified password registration.
            return (null, GoogleAccountFailure.ProviderRejected);
        }

        if (result.Status is CreateAccountStatus.GoogleSubjectUnavailable)
        {
            AccountRecord? concurrent = await store.FindByGoogleSubjectAsync(providerSubject, cancellationToken);
            return concurrent is null
                ? (null, GoogleAccountFailure.ProviderRejected)
                : (await sessions.CreateAsync(concurrent, cancellationToken), GoogleAccountFailure.None);
        }

        return (await sessions.CreateAsync(account, cancellationToken), GoogleAccountFailure.None);
    }

    private static Dictionary<string, string[]> ValidateRegistration(
        RegisterAccountRequest request,
        out string accountName,
        out string email,
        out string normalizedEmail)
    {
        Dictionary<string, string[]> errors = [];

        if (!AccountNamePolicy.TryNormalize(request.AccountName, out accountName, out string accountNameError))
        {
            errors["accountName"] = [accountNameError];
        }

        if (!EmailAddressPolicy.TryNormalize(request.Email, out email, out normalizedEmail, out string emailError))
        {
            errors["email"] = [emailError];
        }

        if (!PasswordPolicy.TryValidate(request.Password, out string passwordError))
        {
            errors["password"] = [passwordError];
        }

        return errors;
    }
}

internal enum GoogleAccountFailure
{
    None,
    ProviderRejected,
    AccountNameRequired,
    InvalidAccountName,
    AccountNameUnavailable
}