Skip to content

Instantly share code, notes, and snippets.

@danielholmstrom
Created May 8, 2014 15:58
Show Gist options
  • Save danielholmstrom/54eef322731a1192b3b6 to your computer and use it in GitHub Desktop.
Save danielholmstrom/54eef322731a1192b3b6 to your computer and use it in GitHub Desktop.
"""
Auth database models
~~~~~~~~~~~~~~~~~~~~
"""
from pyramid.security import (
Allow,
Authenticated,
DENY_ALL,
)
from pluto.database import (
Model,
Table,
Column,
Integer,
Unicode,
ForeignKey,
attribute_mapped_collection,
backref,
relationship,
hybrid_property,
CreatedAtMixin,
)
acl_role_id_length = 256
"""Max length of an AclRole id"""
class AuthUser(CreatedAtMixin, Model):
"""Auth user"""
def __acl__(any=None):
"""Get ACL rules
:param any: Class, None or instance
"""
acl = [
(Allow, ('role', 'admin'), 'create'),
(Allow, ('role', 'admin'), 'update'),
(Allow, Authenticated, 'read'),
DENY_ALL,
]
if any and hasattr(any, 'id'):
return [(Allow, ('user', any.id), 'update')] + acl
else:
return acl
id = Column(Integer, primary_key=True)
username = Column(Unicode, unique=True)
_password = Column('password', Unicode(80))
@hybrid_property
def password(self):
"""Get the hashed password"""
return self._password
@password.setter
def set_password(self, password):
"""Hash the password on set"""
# TODO: Decide on hash method
hashed_password = password
self._password = hashed_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 password == self.password
acl_role_auth_user = Table(
'acl_role_auth_user',
Model.metadata,
Column('auth_user_id',
None,
ForeignKey('auth_user.id',
onupdate='CASCADE',
ondelete='CASCADE'),
primary_key=True),
Column('acl_role_id',
None,
ForeignKey('acl_role.id',
onupdate='CASCADE',
ondelete='CASCADE'),
primary_key=True),
)
"""AuthUser:AclRole relation table
This is not mapped to a class since we don't want to create objects with for
this table
"""
class AclRole(Model):
"""ACL role"""
acl = [
(Allow, ('role', 'admin'), 'create'),
(Allow, ('role', 'admin'), 'update'),
(Allow, Authenticated, 'read'),
DENY_ALL,
]
id = Column(Unicode(acl_role_id_length), primary_key=True)
auth_users = relationship(
AuthUser,
secondary=acl_role_auth_user,
collection_class=attribute_mapped_collection('id'),
backref=backref('acl_roles',
collection_class=attribute_mapped_collection('id'),
lazy='joined'))
"""Users that has this role, mapped by their id"""
def includeme(config):
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment