feat: give the user the ability to make a password policy
This commit is contained in:
@ -1,11 +1,10 @@
|
||||
using Konscious.Security.Cryptography;
|
||||
using System;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Mirea.Api.Security.Services;
|
||||
|
||||
public partial class PasswordHashService
|
||||
public class PasswordHashService
|
||||
{
|
||||
public int SaltSize { private get; init; }
|
||||
public int HashSize { private get; init; }
|
||||
@ -54,15 +53,4 @@ public partial class PasswordHashService
|
||||
|
||||
public bool VerifyPassword(string password, string saltBase64, string hashBase64) =>
|
||||
VerifyPassword(password, Convert.FromBase64String(saltBase64), Convert.FromBase64String(hashBase64));
|
||||
|
||||
public static bool HasPasswordInPolicySecurity(string password) =>
|
||||
password.Length >= 8 &&
|
||||
PasswordExistSpecialSymbol().IsMatch(password) &&
|
||||
PasswordExistUpperLetter().IsMatch(password);
|
||||
|
||||
[GeneratedRegex("[A-Z]+")]
|
||||
private static partial Regex PasswordExistUpperLetter();
|
||||
|
||||
[GeneratedRegex("[!@#$%^&*]+")]
|
||||
private static partial Regex PasswordExistSpecialSymbol();
|
||||
}
|
40
Security/Services/PasswordPolicyService.cs
Normal file
40
Security/Services/PasswordPolicyService.cs
Normal file
@ -0,0 +1,40 @@
|
||||
using Mirea.Api.Security.Common.Domain;
|
||||
using System.Linq;
|
||||
using System.Security;
|
||||
|
||||
namespace Mirea.Api.Security.Services;
|
||||
|
||||
public class PasswordPolicyService(PasswordPolicy policy)
|
||||
{
|
||||
public void ValidatePasswordOrThrow(string password)
|
||||
{
|
||||
if (password.Length < policy.MinimumLength)
|
||||
throw new SecurityException($"Password must be at least {policy.MinimumLength} characters long.");
|
||||
|
||||
if (policy.RequireLetter && !password.Any(char.IsLetter))
|
||||
throw new SecurityException("Password must contain at least one letter.");
|
||||
|
||||
if (policy.RequireLettersDifferentCase && !password.Any(char.IsLower) && !password.Any(char.IsUpper))
|
||||
throw new SecurityException("Password must contain at least one lowercase and uppercase letter.");
|
||||
|
||||
if (policy.RequireDigit && !password.Any(char.IsDigit))
|
||||
throw new SecurityException("Password must contain at least one digit.");
|
||||
|
||||
if (policy.RequireSpecialCharacter && password.All(char.IsLetterOrDigit))
|
||||
throw new SecurityException("Password must contain at least one special character.");
|
||||
}
|
||||
|
||||
public bool TryValidatePassword(string password)
|
||||
{
|
||||
try
|
||||
{
|
||||
ValidatePasswordOrThrow(password);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user