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

summaryrefslogtreecommitdiffhomepage
path: root/apps/api/Accounts/AccountService.cs
blob: 3e7ced11be02995c47407ff7bceff5889e3be53b (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
// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com>
// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.0

using Microsoft.AspNetCore.Identity;

namespace Progmasoft.Progmaweb.Api.Accounts;

internal sealed class AccountService(
    IAccountStore store,
    TimeProvider timeProvider)
{
    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,
            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)
        {
            return null;
        }

        AccountRecord? account = await store.FindByEmailAsync(normalizedEmail, cancellationToken);
        if (account is null || account.PasswordHash is null)
        {
            // A fixed dummy record keeps the missing-account path on the same password-hashing primitive.
            AccountRecord dummyBase = new(Guid.Empty, "Missing00", "MISSING00", "missing@example.invalid",
                "MISSING@EXAMPLE.INVALID", string.Empty, DateTimeOffset.UnixEpoch);
            AccountRecord dummy = dummyBase with
            {
                PasswordHash = passwordHasher.HashPassword(dummyBase, "not-the-provided-password")
            };
            _ = passwordHasher.VerifyHashedPassword(dummy, dummy.PasswordHash, 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? providerEmail,
            string? requestedAccountName,
            SessionService sessions,
            CancellationToken cancellationToken)
    {
        if (!EmailAddressPolicy.TryNormalize(providerEmail, out string email, out string normalizedEmail, out _))
        {
            return (null, GoogleAccountFailure.ProviderRejected);
        }

        AccountRecord? existing = await store.FindByEmailAsync(normalizedEmail, cancellationToken);
        if (existing is not null)
        {
            return (await sessions.CreateAsync(existing, cancellationToken), GoogleAccountFailure.None);
        }

        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,
            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)
        {
            // A concurrent callback may have created the same verified Google identity.
            AccountRecord? concurrent = await store.FindByEmailAsync(normalizedEmail, 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
}