flaschengeist/flaschengeist/system/models/user.py

92 lines
3.0 KiB
Python
Raw Normal View History

from datetime import datetime
from ..database import db
from .accessToken import AccessToken
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 authentification 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("UserGroup", 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 = UserGroup.query.filter_by(name=name).first()
if not r:
r = UserGroup(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))
class UserGroup(db.Model):
__tablename__ = 'group'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(30))
def toJSON(self):
return {
'name': self.name
}