Skip to content

Instantly share code, notes, and snippets.

@jessegavin
Created July 2, 2012 15:58
Show Gist options
  • Save jessegavin/3033950 to your computer and use it in GitHub Desktop.
Save jessegavin/3033950 to your computer and use it in GitHub Desktop.
Original
Outcome<string> IAuthenticationService.ValidatePassword(IDssPrincipal dssPrincipal, string password)
{
const int minimumLength = 8;
const int maximumLength = 20;
const string specialCharactersPattern = @"\#\$\%\&\@\*\+\-\=\!\.\?\:\;\(\)\[\]\{\}\^\~_";
var observations = new List<string>();
var email = dssPrincipal.Identity.EmailAddress.ToMaybe();
// Password must not be null
if (string.IsNullOrWhiteSpace(password))
{
return Outcome.Failure("Password cannot be empty");
}
// Password must have at least 8 characters
if (password.Length < minimumLength)
{
observations.Add(string.Format("Password must be at least {0} characters", minimumLength));
}
// Password must have no more than 20 characters
if (password.Length > maximumLength)
{
observations.Add(string.Format("Password cannot be longer than {0} characters", maximumLength));
}
// Password must not contain a substring of the user's email
if (email.HasValue && email.Value.IndexOf(password, StringComparison.InvariantCultureIgnoreCase) > -1)
{
observations.Add("Password cannot contain parts of the email address associated with this account.");
}
// Password must not contain spaces
if (Regex.IsMatch(password, @"\w+"))
{
observations.Add("Password cannot contain spaces");
}
// Password must not contain prohibited characters
if (Regex.IsMatch(password, @"[^" + specialCharactersPattern + @"]+"))
{
observations.Add("Password contains prohibited characters");
}
// Password must have at least two classes of characters (e.g., letters, digits, "allowed specials").
var characterClasses = 0;
characterClasses += Regex.IsMatch(password, @"[a-zA-Z]+") ? 1 : 0;
characterClasses += Regex.IsMatch(password, @"\d+") ? 1 : 0;
characterClasses += Regex.IsMatch(password, @"[" + specialCharactersPattern + @"]+") ? 1 : 0;
if (characterClasses < 2)
{
observations.Add("Password must contain at least two kinds of characters (letters, numbers or 'allowed special characters'.");
}
return observations.Any() ? Outcome.Failure(observations.AsEnumerable()) : Outcome.Success();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment