/shabti/templates/humanoid/+package+/model/identity.py_tmpl
https://bitbucket.org/gawel/shabti · Unknown · 155 lines · 130 code · 25 blank · 0 comment · 0 complexity · f2626d706e472e10e8a499099a423bd3 MD5 · raw file
- """ Sample SQLAlchemy-powered model definition for the repoze.what SQL plugin.
- From published Pylons + repoze.what example:
- http://wiki.pylonshq.com/display/pylonscookbook/Authorization+with+repoze.what
- """
- import logging
- import os
- import bcrypt
- import datetime
- from sqlalchemy import Table, ForeignKey, Column
- from sqlalchemy.types import String, Unicode, UnicodeText, Integer, DateTime,\
- Boolean, Float
- from sqlalchemy.orm import relation, backref, synonym
- from sqlalchemy.ext.declarative import synonym_for
- from {{package}}.model.meta import Base, Session
- log = logging.getLogger(__name__)
- # This is the association table for the many-to-many relationship between
- # groups and permissions.
- group_permission_table = Table(
- 'group_permission', Base.metadata,
- Column('group_id', Integer, ForeignKey('group.group_id',
- onupdate="CASCADE", ondelete="CASCADE")),
- Column('permission_id', Integer, ForeignKey('permission.permission_id',
- onupdate="CASCADE", ondelete="CASCADE"))
- )
- # This is the association table for the many-to-many relationship between
- # groups and members - this is, the memberships.
- user_group_table = Table(
- 'user_group', Base.metadata,
- Column('user_id', Integer, ForeignKey('user.user_id',
- onupdate="CASCADE", ondelete="CASCADE")),
- Column('group_id', Integer, ForeignKey('group.group_id',
- onupdate="CASCADE", ondelete="CASCADE"))
- )
- # auth model
- class NotAuthenticated(Exception):pass
- class Group(Base):
- """An ultra-simple group definition."""
- __tablename__ = 'group'
- group_id = Column(Integer, autoincrement=True, primary_key=True)
- name = Column(Unicode(16), unique=True)
- description = Column(Unicode(255))
- active = Column(Boolean(), default=False)
- created = Column(DateTime(), default=datetime.datetime.utcnow())
- users = relation('User', secondary=user_group_table, backref='groups')
- @synonym_for('group_id')
- @property
- def id(self):
- return self.group_id
- def __repr__(self):
- return self.name
-
- __unicode__ = __repr__
-
- class User(Base):
- """
- Reasonably basic User definition. Probably would want additional
- attributes."""
- __tablename__ = 'user'
- user_id = Column(Integer, autoincrement=True, primary_key=True)
- username = Column(Unicode(16), unique=True)
- displayname = Column(Unicode(255))
- email = Column(Unicode(255))
- _password = Column('password', Unicode(80))
- password_check = Column(Unicode(80))
- active = Column(Boolean(), default=False)
- created = Column(DateTime(), default=datetime.datetime.utcnow())
- def _set_password(self, password):
- """Hash password on the fly."""
- hashed_password = password
-
- if isinstance(password, unicode):
- password_8bit = password.encode('UTF-8')
- else:
- password_8bit = password
-
- hashed_password = bcrypt.hashpw(password_8bit, bcrypt.gensalt())
-
- # Make sure the hashed password is an UTF-8 object at the end of the
- # process because SQLAlchemy _wants_ a unicode object for Unicode
- # fields
- if not isinstance(hashed_password, unicode):
- hashed_password = hashed_password.decode('UTF-8')
-
- self._password = hashed_password
-
- def _get_password(self):
- """Return the password hashed"""
- return self._password
- password = synonym('_password', descriptor=property(_get_password,
- _set_password))
- def __repr__(self):
- return self.username
-
- __unicode__ = __repr__
-
- @synonym_for('user_id')
- @property
- def id(self):
- return self.user_id
-
- @classmethod
- def authenticate(cls, username, password):
- try:
- user = Session.query(cls).filter_by(
- username=username, active=True).one()
- if user and bcrypt.hashpw(password, user.password) == user.password:
- log.debug("Authentication succeeded")
- return user
- except Exception, emsg:
- log.debug("Authentication failed: %s" % str(emsg))
- raise NotAuthenticated
- raise NotAuthenticated
-
- # def validate_password(self, user, password):
- # return bcrypt.hashpw(password, user.password) == user.password
- def validate_password(self, password):
- """
- Check the password against existing credentials.
-
- :param password: the password that was provided by the user to
- try and authenticate. This is the clear text version that we will
- need to match against the hashed one in the database.
- :type password: unicode object.
- :return: Whether the password is valid.
- :rtype: bool
-
- """
- return bcrypt.hashpw(password, self.password) == self.password
-
- class Permission(Base):
- """A relationship that determines what each Group can do"""
- __tablename__ = 'permission'
- permission_id = Column(Integer, autoincrement=True, primary_key=True)
- name = Column(Unicode(16), unique=True)
- description = Column(Unicode(255))
- groups = relation(Group, secondary=group_permission_table,
- backref='permissions')
- def __repr__(self):
- return self.name
-
- __unicode__ = __repr__
- @synonym_for('permission_id')
- @property
- def id(self):
- return self.permission_id