Fixed Typo in accessController, added Roles for access controll

This commit is contained in:
Ferdinand Thiessen 2020-09-01 21:36:25 +02:00
parent 48dd7ea6ec
commit 66dcfa80b1
4 changed files with 40 additions and 36 deletions

View File

@ -45,16 +45,11 @@ def create_app():
logger.error('No authentification plugin configured or authentification plugin not found') logger.error('No authentification plugin configured or authentification plugin not found')
logger.info('Search for plugins') logger.info('Search for plugins')
discovered_plugins = { for entry_point in pkg_resources.iter_entry_points('flaschengeist.plugin'):
entry_point.name: entry_point.load() logger.debug("Found plugin: %s", entry_point.name)
for entry_point in pkg_resources.iter_entry_points('flaschengeist.plugin') if config.get(entry_point.name, 'enabled', fallback=False):
} logger.info('Loaded plugin > %s <', entry_point.name)
app.register_blueprint(entry_point.load()())
for name in discovered_plugins:
logger.debug("Found plugin: %s", name)
if config.get(name, 'enabled', fallback=False):
logger.info('Loaded plugin > %s <', name)
app.register_blueprint(discovered_plugins[name]())
return app return app
#app.register_blueprint(baruser) #app.register_blueprint(baruser)

View File

@ -4,12 +4,12 @@ from flaschengeist.system.database import db
from datetime import datetime, timedelta from datetime import datetime, timedelta
import secrets import secrets
from . import Singleton from . import Singleton
from flask import Blueprint, request, jsonify
import logging import logging
logger = logging.getLogger("flaschenpost") logger = logging.getLogger("flaschenpost")
class AccesTokenController(metaclass=Singleton):
class AccessTokenController(metaclass=Singleton):
""" Control all createt AccesToken """ Control all createt AccesToken
This Class create, delete, find and manage AccesToken. This Class create, delete, find and manage AccesToken.
@ -29,7 +29,7 @@ class AccesTokenController(metaclass=Singleton):
logger.debug("init accesstoken controller") logger.debug("init accesstoken controller")
self.lifetime = lifetime self.lifetime = lifetime
def validateAccessToken(self, token, group): def validateAccessToken(self, token, roles):
""" Verify Accestoken """ Verify Accestoken
Verify an Accestoken and Group so if the User has permission or not. Verify an Accestoken and Group so if the User has permission or not.
@ -37,7 +37,7 @@ class AccesTokenController(metaclass=Singleton):
Args: Args:
token: Token to verify. token: Token to verify.
group: Group like 'moneymaster', 'gastro', 'user' or 'bar' roles: Roles needed to access restricted routes
Returns: Returns:
An the AccesToken for this given Token or False. An the AccesToken for this given Token or False.
""" """
@ -48,14 +48,9 @@ class AccesTokenController(metaclass=Singleton):
logger.debug("now is {{ {} }}, endtime is {{ {} }}".format(now, endTime)) logger.debug("now is {{ {} }}, endtime is {{ {} }}".format(now, endTime))
if now <= endTime: if now <= endTime:
logger.debug("check if token {{ {} }} is same as {{ {} }}".format(token, accToken)) logger.debug("check if token {{ {} }} is same as {{ {} }}".format(token, accToken))
if accToken == token: if not roles or (roles and self.userHasRole(accToken.user, roles)):
# if not self.checkBar(accToken.user):
# accToken.lock_bar = False
# logger.debug("check if accestoken {{ {} }} has group {{ {} }}".format(accToken, group))
# if self.isSameGroup(accToken, group):
accToken.updateTimestamp() accToken.updateTimestamp()
db.session.commit() db.session.commit()
# logger.debug("found accesstoken {{ {} }} with token: {{ {} }} and group: {{ {} }}".format(accToken, token, group))
return accToken return accToken
else: else:
logger.debug("accesstoken is {{ {} }} out of date".format(accToken)) logger.debug("accesstoken is {{ {} }} out of date".format(accToken))
@ -64,6 +59,13 @@ class AccesTokenController(metaclass=Singleton):
logger.debug("no valid accesstoken with token: {{ {} }} and group: {{ {} }}".format(token, group)) logger.debug("no valid accesstoken with token: {{ {} }} and group: {{ {} }}".format(token, group))
return False return False
def userHasRole(self, user, roles):
for group in user.groups:
for role in group.roles:
if role.name in roles:
return True
return False
def createAccesToken(self, user, user_agent=None): def createAccesToken(self, user, user_agent=None):
""" Create an AccessToken """ Create an AccessToken

View File

@ -3,27 +3,22 @@ from flask import current_app, request, jsonify
from flaschengeist import logger from flaschengeist import logger
def login_required(**kwargs): def login_required(**kwargs):
from .controller.accesTokenController import AccesTokenController from .controller.accessTokenController import AccessTokenController
accessController = AccesTokenController() accessController = AccessTokenController()
#if "groups" in kwargs: roles = None
# groups = kwargs["groups"] if "roles" in kwargs:
#if "bar" in kwargs: roles = kwargs["roles"]
# bar = kwargs["bar"]
#logger.debug("groups are {{ {} }}".format(groups))
def real_decorator(func): def real_decorator(func):
@wraps(func) @wraps(func)
def wrapper(*args, **kwargs): def wrapper(*args, **kwargs):
token = request.headers.get('Token') token = request.headers.get('Token')
logger.debug("token is {{ {} }}".format(token)) logger.debug("token is {{ {} }}".format(token))
accToken = accessController.validateAccessToken(token, None) accToken = accessController.validateAccessToken(token, roles)
logger.debug("accToken is {{ {} }}".format(accToken)) logger.debug("accToken is {{ {} }}".format(accToken))
kwargs['accToken'] = accToken kwargs['accToken'] = accToken
if accToken: if accToken:
logger.debug("token {{ {} }} is valid".format(token)) logger.debug("token {{ {} }} is valid".format(token))
# if accToken.lock_bar and not bar:
# return jsonify({"error": "error",
# "message": "permission forbidden"}), 403
return func(*args, **kwargs) return func(*args, **kwargs)
else: else:
logger.warning("token {{ {} }} is not valid".format(token)) logger.warning("token {{ {} }} is not valid".format(token))

View File

@ -18,7 +18,7 @@ class User(db.Model):
Attributes: Attributes:
id: Id in Database as Primary Key. id: Id in Database as Primary Key.
uid: User ID used by authentification provider uid: User ID used by authentication provider
displayname: Name to show displayname: Name to show
firstname: Firstname of the User firstname: Firstname of the User
lastname: Lastname of the User lastname: Lastname of the User
@ -31,7 +31,7 @@ class User(db.Model):
firstname = db.Column(db.String(30)) firstname = db.Column(db.String(30))
lastname = db.Column(db.String(30)) lastname = db.Column(db.String(30))
mail = db.Column(db.String(30)) mail = db.Column(db.String(30))
groups = db.relationship("UserGroup", secondary=association_table) groups = db.relationship("Group", secondary=association_table)
sessions = db.relationship("AccessToken", back_populates="user") sessions = db.relationship("AccessToken", back_populates="user")
attributes = db.relationship("UserAttribute", collection_class=attribute_mapped_collection('name'), cascade="all, delete") attributes = db.relationship("UserAttribute", collection_class=attribute_mapped_collection('name'), cascade="all, delete")
@ -42,9 +42,9 @@ class User(db.Model):
self.attributes[name] = UserAttribute(name=name, value=value) self.attributes[name] = UserAttribute(name=name, value=value)
def addGroup(self, name): def addGroup(self, name):
r = UserGroup.query.filter_by(name=name).first() r = Group.query.filter_by(name=name).first()
if not r: if not r:
r = UserGroup(name=name) r = Group(name=name)
self.groups.append(r) self.groups.append(r)
def updateData(self, data): def updateData(self, data):
@ -79,13 +79,25 @@ class UserAttribute(db.Model):
name = db.Column(db.String(30)) name = db.Column(db.String(30))
value = db.Column(db.String(192)) value = db.Column(db.String(192))
class UserGroup(db.Model): 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' __tablename__ = 'group'
id = db.Column(db.Integer, primary_key=True) id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(30)) name = db.Column(db.String(30))
permissions = db.relationship("Permission", secondary=group_permission_association_table)
def toJSON(self): def toJSON(self):
return { return {
'name': self.name 'name': self.name
} }
class Permission(db.Model):
__tablename__ = 'permission'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(30))