Skip to content

Instantly share code, notes, and snippets.

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