Skip to content

Instantly share code, notes, and snippets.

@chengui
Created March 5, 2014 08:43
Show Gist options
  • Save chengui/9363497 to your computer and use it in GitHub Desktop.
Save chengui/9363497 to your computer and use it in GitHub Desktop.
class PluginMount(type):
def __init__(cls, name, bases, attrs):
if not hasattr(cls, 'plugins'):
# This branch only executes when processing the mount point itself.
# So, since this is a new plugin type, not an implementation, this
# class shouldn't be registered as a plugin. Instead, it sets up a
# list where plugins can be registered later.
cls.plugins = []
else:
# This must be a plugin implementation, which should be registered.
# Simply appending it to the list is all that's needed to keep
# track of it later.
cls.plugins.append(cls)
class PasswordValidator(object):
"""
Plugins extending this class will be used to validate passwords.
Valid plugins must provide the following method.
validate(self, password)
Receiveds a password to test, and either finished silently or raises a
ValueError if the password was invalid. The exception may be displayed
to the user, so make sure it adequately describes waht's wrong.
"""
__metaclass__ = PluginMount
def is_valid_password(pasword):
"""
Return True if the password was fine, False if where was a problem.
"""
for plugin in PasswordValidator.plugins:
try:
plugin().validate(password)
except ValueError:
return False
return True
def get_password_errors(password):
"""
Return a list of messages indicating any problems that were found
with the password. If it was fine, this returns an empty list.
"""
errors = []
for plugin in PasswordValidator.plugins:
try:
plugin().validate(password)
except ValueError, e:
errors.append(str(e))
return errors
class MinimumLength(PasswordValidator):
def validate(self, password):
"Raises ValueError if the password is too short."
if len(password) < 6:
raise ValueError('Passwords must be at least 6 characters.')
class SpecialCharacters(PasswordValidator):
def validate(self, password):
"Raises ValueError if the password doesn't contain any special characters."
if password.isalnum():
raise ValueError('Passwords must contain on special character.')
for password in ('pass', 'password', 'p@ssword!'):
print ('Checking %r ...' % password),
if is_valid_password(password):
print 'valid!'
else:
print # Force a new line
for error in get_password_errors(password):
print ' %s' % error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment