Created
January 14, 2013 01:05
-
-
Save inklesspen/4527085 to your computer and use it in GitHub Desktop.
barebones user model
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
| import bcrypt # http://pypi.python.org/pypi/py-bcrypt | |
| class User(Base): | |
| __tablename__ = 'users' | |
| id = Column(Integer, primary_key=True) | |
| query = DBSession.query_property() | |
| username = Column(Unicode(50), unique=True, nullable=False) | |
| password_hash = Column(String(60), nullable=False) | |
| def __repr__(self): | |
| if self.id is None: | |
| return "<User('%s', unsaved=True>" % self.username | |
| return "<User(%d, '%s')>" % (self.id, self.username) | |
| @classmethod | |
| def get_user(cls, username): | |
| return cls.query.filter(cls.username == username).one() | |
| @classmethod | |
| def new(cls, username, password): | |
| user = cls(username=username) | |
| user.change_password(password) | |
| return user | |
| def check_password(self, candidate): | |
| return bcrypt.hashpw(candidate, self.password_hash) == self.password_hash | |
| def change_password(self, new_password): | |
| self.password_hash = User.generate_password_hash(new_password) | |
| # For testing purposes; you want a strong difficulty in production, but a weak one like 2 in your unit tests | |
| bcrypt_difficulty = 12 | |
| @classmethod | |
| def generate_password_hash(cls, new_password, difficulty=None): | |
| difficulty = cls.bcrypt_difficulty if difficulty is None else difficulty | |
| return bcrypt.hashpw(new_password, bcrypt.gensalt(difficulty)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment