flaschengeist/flaschengeist/system/models/user.py

103 lines
3.4 KiB
Python

from ..database import db
from sqlalchemy.orm.collections import attribute_mapped_collection
from flask import current_app
from werkzeug.local import LocalProxy
logger = LocalProxy(lambda: current_app.logger)
association_table = db.Table('user_group',
db.Column('user_id', db.Integer, db.ForeignKey('user.id')),
db.Column('group_id', db.Integer, db.ForeignKey('group.id'))
)
class User(db.Model):
""" Database Object for User
Table for all safed User
Attributes:
id: Id in Database as Primary Key.
uid: User ID used by authentication provider
displayname: Name to show
firstname: Firstname of the User
lastname: Lastname of the User
mail: mail address of the User
"""
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True)
uid = db.Column(db.String(30))
displayname = db.Column(db.String(30))
firstname = db.Column(db.String(30))
lastname = db.Column(db.String(30))
mail = db.Column(db.String(30))
groups = db.relationship("Group", secondary=association_table)
sessions = db.relationship("AccessToken", back_populates="user")
attributes = db.relationship("UserAttribute", collection_class=attribute_mapped_collection('name'), cascade="all, delete")
def setAttribute(self, name, value):
if name in self.attributes:
self.attributes[name].value = value
else:
self.attributes[name] = UserAttribute(name=name, value=value)
def addGroup(self, name):
r = Group.query.filter_by(name=name).first()
if not r:
r = Group(name=name)
self.groups.append(r)
def updateData(self, data):
logger.debug("update data of user")
if 'uid' in data:
self.uid = data['uid']
if 'firstname' in data:
self.firstname = data['firstname']
if 'lastname' in data:
self.lastname = data['lastname']
if 'mail' in data:
self.mail = data['mail']
if 'displayname' in data:
self.displayname = data['displayname']
def toJSON(self):
return {
# TODO: username should be UID?
"username": self.uid,
"displayname": self.displayname,
"firstname": self.firstname,
"lastname": self.lastname,
"mail": self.mail,
"groups": ["user"] + [g.name for g in self.groups]
}
class UserAttribute(db.Model):
__tablename__ = 'userAttribute'
id = db.Column(db.Integer, primary_key=True)
user = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
name = db.Column(db.String(30))
value = db.Column(db.String(192))
group_permission_association_table = db.Table('group_permission',
db.Column('group_id', db.Integer, db.ForeignKey('group.id')),
db.Column('permission_id', db.Integer, db.ForeignKey('permission.id'))
)
class Group(db.Model):
__tablename__ = 'group'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(30))
permissions = db.relationship("Permission", secondary=group_permission_association_table)
def toJSON(self):
return {
'name': self.name
}
class Permission(db.Model):
__tablename__ = 'permission'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(30))