feat: give the user the ability to make a password policy
This commit is contained in:
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