Created
May 20, 2013 16:01
-
-
Save j2labs/5613224 to your computer and use it in GitHub Desktop.
Password field for Schematics
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
>>> from schematics.models import Model | |
>>> from schematics.serialize import whitelist, blacklist | |
>>> from schematics.types import BaseType, StringType | |
>>> from schematics.exceptions import ValidationError | |
>>> import hashlib | |
>>> import random | |
>>> | |
>>> class PasswordType(BaseType): | |
... ALGORITHM = 'MD5' | |
... def __init__(self, **kw): | |
... super(PasswordType, self).__init__(self, **kw) | |
... def convert(self, value): | |
... (password, salt) = value | |
... pass_string = self.gen_secret(password, salt) | |
... return pass_string | |
... def to_primitive(self, value): | |
... return str(value) | |
... def gen_secret(self, password, salt=None): | |
... if salt == None: | |
... salt = self.gen_salt() | |
... digest = self.gen_digest(password, salt) | |
... secret_string = ':::'.join([self.ALGORITHM, digest, salt]) | |
... return secret_string | |
... def gen_digest(self, password, salt): | |
... return hashlib.md5(salt + password).hexdigest() | |
... def gen_salt(self): | |
... alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" | |
... alphanum = alphabet + "0123456789" | |
... salt = ''.join(random.choice(alphanum) for i in range(16)) | |
... return salt | |
... | |
>>> class User(Model): | |
... secret = PasswordType() | |
... name = StringType(required=True, max_length=50) | |
... bio = StringType(max_length=100) | |
... class Options: | |
... roles = { | |
... 'owner': blacklist(), | |
... 'public': whitelist('name', 'bio'), | |
... } | |
... | |
>>> | |
>>> u = User() | |
>>> u.secret = ('whatevz', None) | |
>>> | |
>>> u.secret | |
'MD5:::0abff363012d1e934ecc509df62be1ff:::YFfnk5kzsb2uRA9f' | |
>>> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment