flaschengeist/flaschengeist/models/user.py

89 lines
2.9 KiB
Python

from sqlalchemy.orm.collections import attribute_mapped_collection
from . import ModelSerializeMixin
from flaschengeist.database import db
association_table = db.Table(
"user_x_role",
db.Column("user_id", db.Integer, db.ForeignKey("user.id")),
db.Column("role_id", db.Integer, db.ForeignKey("role.id")),
)
role_permission_association_table = db.Table(
"role_x_permission",
db.Column("role_id", db.Integer, db.ForeignKey("role.id")),
db.Column("permission_id", db.Integer, db.ForeignKey("permission.id")),
)
class Permission(db.Model, ModelSerializeMixin):
__tablename__ = "permission"
name: str = db.Column(db.String(30), unique=True)
_id = db.Column("id", db.Integer, primary_key=True)
class Role(db.Model, ModelSerializeMixin):
__tablename__ = "role"
name: str = db.Column(db.String(30), unique=True)
permissions: [Permission] = db.relationship(
"Permission", secondary=role_permission_association_table, cascade="all, delete"
)
_id = db.Column("id", db.Integer, primary_key=True)
class User(db.Model, ModelSerializeMixin):
"""Database Object for User
Table for all saved User
Attributes:
id: Id in Database as Primary Key.
uid: User ID used by authentication provider
display_name: Name to show
firstname: Firstname of the User
lastname: Lastname of the User
mail: mail address of the User
"""
__tablename__ = "user"
userid: str = db.Column(db.String(30))
display_name: str = db.Column(db.String(30))
firstname: str = db.Column(db.String(30))
lastname: str = db.Column(db.String(30))
mail: str = db.Column(db.String(30))
roles: [Role] = db.relationship("Role", secondary=association_table)
_id = db.Column("id", db.Integer, primary_key=True)
_sessions = db.relationship("Session", back_populates="_user")
_attributes = db.relationship(
"_UserAttribute", collection_class=attribute_mapped_collection("name"), cascade="all, delete"
)
def set_attribute(self, name, value):
if name in self._attributes:
self._attributes[name].value = value
else:
self._attributes[name] = _UserAttribute(name=name, value=value)
def has_attribute(self, name):
return name in self._attributes
def get_attribute(self, name):
return self._attributes[name].value
def get_permissions(self):
return ["user"] + [permission.name for role in self.roles for permission in role.permissions]
def has_permission(self, permission):
return permission in self.get_permissions()
class _UserAttribute(db.Model, ModelSerializeMixin):
__tablename__ = "user_attribute"
id = db.Column("id", db.Integer, primary_key=True)
user: User = db.Column("user", db.Integer, db.ForeignKey("user.id"), nullable=False)
name: str = db.Column(db.String(30))
value: str = db.Column(db.String(192))