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

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

namespace Progmasoft.Progmaweb.Api.Accounts;

/// <summary>Rules for passwords.</summary>
/// <remarks>
/// Only length is constrained, so long passphrases are welcome. The upper bound keeps hashing cost bounded for a
/// request that an anonymous caller can send.
/// </remarks>
internal static class PasswordPolicy
{
    /// <summary>Fewest characters a password may have.</summary>
    public const int MinimumLength = 12;
    /// <summary>Most characters a password may have.</summary>
    public const int MaximumLength = 256;

    /// <summary>Validates a new password.</summary>
    /// <param name="password">The password in plain text.</param>
    /// <param name="error">Message for the user when the password is refused; empty otherwise.</param>
    /// <returns><see langword="true"/> when the password may be used.</returns>
    public static bool TryValidate(string? password, out string error)
    {
        if (password is null || password.Length < MinimumLength)
        {
            error = $"Passwords must contain at least {MinimumLength} characters.";
            return false;
        }

        if (password.Length > MaximumLength)
        {
            error = $"Passwords cannot exceed {MaximumLength} characters.";
            return false;
        }

        if (password.Contains('\0'))
        {
            error = "Passwords cannot contain a null character.";
            return false;
        }

        error = string.Empty;
        return true;
    }
}