From 754f373cb06b9db87547af4c1ca2a5fd4d046e32 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tim=20Gr=C3=B6ger?= Date: Sat, 18 Jan 2020 23:31:49 +0100 Subject: [PATCH 1/4] add addWorker and deletWorker --- geruecht/__init__.py | 2 + geruecht/baruser/routes.py | 13 ++--- geruecht/controller/__init__.py | 10 +++- geruecht/controller/accesTokenController.py | 23 ++++++-- geruecht/controller/databaseController.py | 64 ++++++++++++++++++++- geruecht/controller/userController.py | 27 ++++++++- geruecht/finanzer/routes.py | 16 +++--- geruecht/routes.py | 8 +-- geruecht/user/routes.py | 4 +- geruecht/vorstand/__init__.py | 0 geruecht/vorstand/routes.py | 24 ++++++++ 11 files changed, 161 insertions(+), 30 deletions(-) create mode 100644 geruecht/vorstand/__init__.py create mode 100644 geruecht/vorstand/routes.py diff --git a/geruecht/__init__.py b/geruecht/__init__.py index 943228c..012a56e 100644 --- a/geruecht/__init__.py +++ b/geruecht/__init__.py @@ -21,8 +21,10 @@ from geruecht import routes from geruecht.baruser.routes import baruser from geruecht.finanzer.routes import finanzer from geruecht.user.routes import user +from geruecht.vorstand.routes import vorstand LOGGER.info("Registrate bluebrints") app.register_blueprint(baruser) app.register_blueprint(finanzer) app.register_blueprint(user) +app.register_blueprint(vorstand) diff --git a/geruecht/baruser/routes.py b/geruecht/baruser/routes.py index bc704a7..88290b8 100644 --- a/geruecht/baruser/routes.py +++ b/geruecht/baruser/routes.py @@ -18,7 +18,7 @@ def _bar(): print(request.headers) token = request.headers.get("Token") print(token) - accToken = accesTokenController.validateAccessToken(token, BAR) + accToken = accesTokenController.validateAccessToken(token, [BAR]) dic = {} if accToken: @@ -57,7 +57,7 @@ def _baradd(): """ token = request.headers.get("Token") print(token) - accToken = accesTokenController.validateAccessToken(token, BAR) + accToken = accesTokenController.validateAccessToken(token, [BAR]) if accToken: data = request.get_json() @@ -94,7 +94,7 @@ def _getUsers(): """ token = request.headers.get("Token") print(token) - accToken = accesTokenController.validateAccessToken(token, BAR) + accToken = accesTokenController.validateAccessToken(token, [BAR]) retVal = {} if accToken: @@ -105,7 +105,7 @@ def _getUsers(): @baruser.route("/barGetUser", methods=['POST']) def _getUser(): token = request.headers.get("Token") - accToken = accesTokenController.validateAccessToken(token, BAR) + accToken = accesTokenController.validateAccessToken(token, [BAR]) if accToken: data = request.get_json() username = data['userId'] @@ -126,10 +126,9 @@ def _getUser(): def _search(): token = request.headers.get("Token") print(token) - accToken = accesTokenController.validateAccessToken(token, BAR) - accToken2 = accesTokenController.validateAccessToken(token, MONEY) + accToken = accesTokenController.validateAccessToken(token, [BAR, MONEY]) - if accToken or accToken2: + if accToken: data = request.get_json() searchString = data['searchString'] diff --git a/geruecht/controller/__init__.py b/geruecht/controller/__init__.py index ed03c81..7b0d1c8 100644 --- a/geruecht/controller/__init__.py +++ b/geruecht/controller/__init__.py @@ -36,8 +36,14 @@ mailConfig = config.getMail() db = DatabaseController(dbConfig['URL'], dbConfig['user'], dbConfig['passwd'], dbConfig['database']) ldapController = LDAPController(ldapConfig['URL'], ldapConfig['dn']) -accesTokenController = AccesTokenController(accConfig) + from . emailController import EmailController emailController = EmailController(mailConfig['URL'], mailConfig['user'], mailConfig['passwd'], mailConfig['port'], mailConfig['email']) from . userController import UserController -userController = UserController() \ No newline at end of file +def getUserController(): + if userController is not None: + return userController + else: + return UserController() +userController = UserController() +accesTokenController = AccesTokenController(accConfig) \ No newline at end of file diff --git a/geruecht/controller/accesTokenController.py b/geruecht/controller/accesTokenController.py index 281ad37..7ec0c08 100644 --- a/geruecht/controller/accesTokenController.py +++ b/geruecht/controller/accesTokenController.py @@ -1,9 +1,12 @@ from geruecht.model.accessToken import AccessToken +#import geruecht.controller.userController as userController +from geruecht.model import BAR from geruecht.controller import LOGGER from datetime import datetime, timedelta import hashlib from . import Singleton + class AccesTokenController(metaclass=Singleton): """ Control all createt AccesToken @@ -26,6 +29,12 @@ class AccesTokenController(metaclass=Singleton): self.tokenList = [] + #def checkBar(self, user): + # if (userController.checkBarUser(user)): + # user.group.append(BAR) + # elif BAR in user.group: + # user.group.remove(BAR) + def validateAccessToken(self, token, group): """ Verify Accestoken @@ -47,6 +56,7 @@ class AccesTokenController(metaclass=Singleton): now = datetime.now() LOGGER.debug("Check if AccessToken's Endtime {} is bigger then now {}".format(endTime, now)) if now <= endTime: + self.checkBar(accToken.user) LOGGER.debug("Check if AccesToken {} has same group {}".format(accToken, group)) if self.isSameGroup(accToken, group): accToken.updateTimestamp() @@ -72,24 +82,27 @@ class AccesTokenController(metaclass=Singleton): LOGGER.info("Create AccessToken") now = datetime.ctime(datetime.now()) token = hashlib.md5((now + user.dn).encode('utf-8')).hexdigest() + self.checkBar(user) accToken = AccessToken(user, token, datetime.now()) LOGGER.debug("Add AccessToken {} to current Tokens".format(accToken)) self.tokenList.append(accToken) LOGGER.info("Finished create AccessToken {} with Token {}".format(accToken, token)) return token - def isSameGroup(self, accToken, group): + def isSameGroup(self, accToken, groups): """ Verify group in AccessToken Verify if the User in the AccesToken has the right group. Args: accToken: AccessToken to verify. - group: Group to verify. + groups: Group to verify. Returns: A Bool. If the same then True else False """ - print("controll if", accToken, "hase group", group) - LOGGER.debug("Check if AccessToken {} has group {}".format(accToken, group)) - return True if group in accToken.user.group else False + print("controll if", accToken, "hase groups", groups) + LOGGER.debug("Check if AccessToken {} has group {}".format(accToken, groups)) + for group in groups: + if group in accToken.user.group: return True + return False diff --git a/geruecht/controller/databaseController.py b/geruecht/controller/databaseController.py index f58cd6c..fa4f6a9 100644 --- a/geruecht/controller/databaseController.py +++ b/geruecht/controller/databaseController.py @@ -2,7 +2,7 @@ import pymysql from . import Singleton from geruecht.model.user import User from geruecht.model.creditList import CreditList -from datetime import datetime +from datetime import datetime, timedelta class DatabaseController(metaclass=Singleton): ''' @@ -61,6 +61,22 @@ class DatabaseController(metaclass=Singleton): return retVal + def getUserById(self, id): + self.connect() + retVal = None + try: + cursor = self.db.cursor() + cursor.execute("select * from user where id={}".format(id)) + data = cursor.fetchone() + self.db.close() + except Exception as err: + raise err + if data: + retVal = User(data) + creditLists = self.getCreditListFromUser(retVal) + retVal.initGeruechte(creditLists) + return retVal + def _convertGroupToString(self, groups): retVal = '' for group in groups: @@ -164,6 +180,52 @@ class DatabaseController(metaclass=Singleton): self.db.close() raise err + def getWorker(self, user, date): + self.connect() + try: + cursor = self.db.cursor() + cursor.execute("select * from bardienste where user_id={} and startdatetime='{}'".format(user.id, date)) + data = cursor.fetchone() + self.db.close() + except Exception as err: + raise err + return {"user": user, "startdatetime": data['startdatetime'], "enddatetime": data['enddatetime']} + + def getWorkers(self, date): + self.connect() + try: + cursor = self.db.cursor() + cursor.execute("select * from bardienste where startdatetime='{}'".format(date)) + data = cursor.fetchall() + self.db.close() + except Exception as err: + raise err + + return [{"user": self.getUserById(work['user_id']).toJSON(), "startdatetime": work['startdatetime'], "enddatetime": work['enddatetime']} for work in data] + + def setWorker(self, user, date): + self.connect() + try: + cursor = self.db.cursor() + cursor.execute("insert into bardienste (user_id, startdatetime, enddatetime) values ({},'{}','{}')".format(user.id, date, date + timedelta(days=1))) + self.db.commit() + self.db.close() + except Exception as err: + self.db.rollback() + self.db.close() + raise err + + def deleteWorker(self, user, date): + self.connect() + try: + cursor = self.db.cursor() + cursor.execute("delete from bardienste where user_id={} and startdatetime='{}'".format(user.id, date)) + self.db.commit() + self.db.close() + except Exception as err: + self.db.rollback() + self.db.close() + raise err if __name__ == '__main__': db = DatabaseController() diff --git a/geruecht/controller/userController.py b/geruecht/controller/userController.py index f027816..541ff75 100644 --- a/geruecht/controller/userController.py +++ b/geruecht/controller/userController.py @@ -1,13 +1,28 @@ from . import LOGGER, Singleton, db, ldapController as ldap, emailController from geruecht.model.user import User from geruecht.exceptions import PermissionDenied -from datetime import datetime +from datetime import datetime, timedelta class UserController(metaclass=Singleton): def __init__(self): pass + def getWorker(self, date, username=None): + if (username): + user = self.getUser(username) + return [db.getWorker(user, date)] + return db.getWorkers(date) + + def addWorker(self, username, date): + user = self.getUser(username) + if (not db.getWorker(user, date)): + db.setWorker(user, date) + + def deleteWorker(self, username, date): + user = self.getUser(username) + db.setWorker(user, date) + def lockUser(self, username, locked): user = self.getUser(username) user.updateData({'locked': locked}) @@ -54,6 +69,16 @@ class UserController(metaclass=Singleton): self.__updateGeruechte(user) return db.getAllUser() + def checkBarUser(self, user): + date = datetime.now() + startdatetime = date.replace(hour=11, minute=0, microsecond=0) + enddatetime = startdatetime + timedelta(days=1) + result = False + if date >= startdatetime and date < enddatetime: + result = db.getWorker(user, startdatetime) + return True if result else False + + def getUser(self, username): user = db.getUser(username) groups = ldap.getGroup(username) diff --git a/geruecht/finanzer/routes.py b/geruecht/finanzer/routes.py index 4f1894d..209f14e 100644 --- a/geruecht/finanzer/routes.py +++ b/geruecht/finanzer/routes.py @@ -20,7 +20,7 @@ def _getFinanzer(): LOGGER.info("Get main for Finanzer") token = request.headers.get("Token") LOGGER.debug("Verify AccessToken with Token {}".format(token)) - accToken = accesTokenController.validateAccessToken(token, MONEY) + accToken = accesTokenController.validateAccessToken(token, [MONEY]) if accToken: LOGGER.debug("Get all Useres") users = userController.getAllUsersfromDB() @@ -50,7 +50,7 @@ def _addAmount(): LOGGER.info("Add Amount") token = request.headers.get("Token") LOGGER.debug("Verify AccessToken with Token {}".format(token)) - accToken = accesTokenController.validateAccessToken(token, MONEY) + accToken = accesTokenController.validateAccessToken(token, [MONEY]) if accToken: data = request.get_json() @@ -93,7 +93,7 @@ def _addCredit(): LOGGER.info("Add Amount") token = request.headers.get("Token") LOGGER.debug("Verify AccessToken with Token {}".format(token)) - accToken = accesTokenController.validateAccessToken(token, MONEY) + accToken = accesTokenController.validateAccessToken(token, [MONEY]) if accToken: @@ -128,7 +128,7 @@ def _addCredit(): @finanzer.route("/finanzerLock", methods=['POST']) def _finanzerLock(): token = request.headers.get("Token") - accToken = accesTokenController.validateAccessToken(token, MONEY) + accToken = accesTokenController.validateAccessToken(token, [MONEY]) if accToken: data = request.get_json() @@ -141,7 +141,7 @@ def _finanzerLock(): @finanzer.route("/finanzerSetConfig", methods=['POST']) def _finanzerSetConfig(): token = request.headers.get("Token") - accToken = accesTokenController.validateAccessToken(token, MONEY) + accToken = accesTokenController.validateAccessToken(token, [MONEY]) if accToken: data = request.get_json() @@ -155,7 +155,7 @@ def _finanzerSetConfig(): @finanzer.route("/finanzerAddUser", methods=['POST']) def _finanzerAddUser(): token = request.headers.get("Token") - accToken = accesTokenController.validateAccessToken(token, MONEY) + accToken = accesTokenController.validateAccessToken(token, [MONEY]) if accToken: data = request.get_json() @@ -175,7 +175,7 @@ def _finanzerAddUser(): @finanzer.route("/finanzerSendOneMail", methods=['POST']) def _finanzerSendOneMail(): token = request.headers.get("Token") - accToken = accesTokenController.validateAccessToken(token, MONEY) + accToken = accesTokenController.validateAccessToken(token, [MONEY]) if accToken: data = request.get_json() @@ -187,7 +187,7 @@ def _finanzerSendOneMail(): @finanzer.route("/finanzerSendAllMail", methods=['GET']) def _finanzerSendAllMail(): token = request.headers.get("Token") - accToken = accesTokenController.validateAccessToken(token, MONEY) + accToken = accesTokenController.validateAccessToken(token, [MONEY]) if accToken: retVal = userController.sendAllMail() diff --git a/geruecht/routes.py b/geruecht/routes.py index 6db7239..346691e 100644 --- a/geruecht/routes.py +++ b/geruecht/routes.py @@ -12,16 +12,16 @@ def login(user, password): @app.route("/valid") def _valid(): token = request.headers.get("Token") - accToken = accesTokenController.validateAccessToken(token, MONEY) + accToken = accesTokenController.validateAccessToken(token, [MONEY]) if accToken: return jsonify(accToken.user.toJSON()) - accToken = accesTokenController.validateAccessToken(token, BAR) + accToken = accesTokenController.validateAccessToken(token, [BAR]) if accToken: return jsonify(accToken.user.toJSON()) - accToken = accesTokenController.validateAccessToken(token, GASTRO) + accToken = accesTokenController.validateAccessToken(token, [GASTRO]) if accToken: return jsonify(accToken.user.toJSON()) - accToken = accesTokenController.validateAccessToken(token, USER) + accToken = accesTokenController.validateAccessToken(token, [USER]) if accToken: return jsonify(accToken.user.toJSON()) return jsonify({"error": "permission denied"}), 401 diff --git a/geruecht/user/routes.py b/geruecht/user/routes.py index af4341b..03f3a0f 100644 --- a/geruecht/user/routes.py +++ b/geruecht/user/routes.py @@ -9,7 +9,7 @@ user = Blueprint("user", __name__) def _main(): token = request.headers.get("Token") - accToken = accesTokenController.validateAccessToken(token, USER) + accToken = accesTokenController.validateAccessToken(token, [USER]) if accToken: accToken.user = userController.getUser(accToken.user.uid) retVal = accToken.user.toJSON() @@ -21,7 +21,7 @@ def _main(): def _addAmount(): token = request.headers.get("Token") - accToken = accesTokenController.validateAccessToken(token, USER) + accToken = accesTokenController.validateAccessToken(token, [USER]) if accToken: data = request.get_json() amount = int(data['amount']) diff --git a/geruecht/vorstand/__init__.py b/geruecht/vorstand/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/geruecht/vorstand/routes.py b/geruecht/vorstand/routes.py new file mode 100644 index 0000000..a0535a8 --- /dev/null +++ b/geruecht/vorstand/routes.py @@ -0,0 +1,24 @@ +from flask import Blueprint, request, jsonify +from datetime import datetime +from geruecht.controller import accesTokenController, userController +from geruecht.model import MONEY, GASTRO + +vorstand = Blueprint("vorstand", __name__) + +@vorstand.route("/sm/addUser", methods=['POST', 'GET']) +def _addUser(): + + if request.method == 'GET': + return "

HEllo World

" + + token = request.headers.get("Token") + accToken = accesTokenController.validateAccessToken(token, [MONEY, GASTRO]) + if accToken: + data = request.get_json() + user = data['user'] + date = datetime.utcfromtimestamp(int(data['date'])) + userController.addWorker(user['username'], date) + + print(data) + return jsonify({"date": date}) + return jsonify({"error": "permission denied"}), 401 \ No newline at end of file From 29f20b23278e3c5e87ef3cb27e12e0299c1bc06b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tim=20Gr=C3=B6ger?= Date: Sun, 19 Jan 2020 00:37:40 +0100 Subject: [PATCH 2/4] fixed imports, bugfix that accLifetime will load from config file --- geruecht/baruser/routes.py | 9 ++++++- geruecht/configparser.py | 2 +- geruecht/controller/__init__.py | 28 --------------------- geruecht/controller/accesTokenController.py | 16 ++++++------ geruecht/controller/databaseController.py | 2 +- geruecht/controller/userController.py | 15 +++++++++-- geruecht/finanzer/routes.py | 5 +++- geruecht/routes.py | 7 ++++-- geruecht/user/routes.py | 7 +++++- 9 files changed, 47 insertions(+), 44 deletions(-) diff --git a/geruecht/baruser/routes.py b/geruecht/baruser/routes.py index 88290b8..7f6248d 100644 --- a/geruecht/baruser/routes.py +++ b/geruecht/baruser/routes.py @@ -1,10 +1,17 @@ from flask import Blueprint, request, jsonify -from geruecht.controller import ldapController as ldap, accesTokenController, userController +import geruecht.controller as gc +import geruecht.controller.ldapController as lc +import geruecht.controller.accesTokenController as ac +import geruecht.controller.userController as uc from datetime import datetime from geruecht.model import BAR, MONEY baruser = Blueprint("baruser", __name__) +ldap= lc.LDAPController(gc.ldapConfig['URL'], gc.ldapConfig['dn']) +accesTokenController = ac.AccesTokenController() +userController = uc.UserController() + @baruser.route("/bar") def _bar(): """ Main function for Baruser diff --git a/geruecht/configparser.py b/geruecht/configparser.py index 247f23c..fc92b61 100644 --- a/geruecht/configparser.py +++ b/geruecht/configparser.py @@ -34,7 +34,7 @@ class ConifgParser(): self.ldap = self.config['LDAP'] LOGGER.info("Set LDAPconfig: {}".format(self.ldap)) if 'AccessTokenLifeTime' in self.config: - self.accessTokenLifeTime = self.config['AccessTokenLifeTime'] + self.accessTokenLifeTime = int(self.config['AccessTokenLifeTime']) LOGGER.info("Set AccessTokenLifeTime: {}".format(self.accessTokenLifeTime)) else: self.accessTokenLifeTime = default['AccessTokenLifeTime'] diff --git a/geruecht/controller/__init__.py b/geruecht/controller/__init__.py index 7b0d1c8..b659474 100644 --- a/geruecht/controller/__init__.py +++ b/geruecht/controller/__init__.py @@ -15,35 +15,7 @@ class Singleton(type): cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cls._instances[cls] -from .databaseController import DatabaseController -def getDatabesController(): - if db is not None: - return db - else: - return DatabaseController(dbConfig['URL'], dbConfig['user'], dbConfig['passwd'], dbConfig['database']) -from .ldapController import LDAPController -def getLDAPController(): - if ldapController is not None: - return ldapController - else: - return LDAPController(ldapConfig['URL'], ldapConfig['dn']) -from .accesTokenController import AccesTokenController - dbConfig = config.getDatabase() ldapConfig = config.getLDAP() accConfig = config.getAccessToken() mailConfig = config.getMail() - -db = DatabaseController(dbConfig['URL'], dbConfig['user'], dbConfig['passwd'], dbConfig['database']) -ldapController = LDAPController(ldapConfig['URL'], ldapConfig['dn']) - -from . emailController import EmailController -emailController = EmailController(mailConfig['URL'], mailConfig['user'], mailConfig['passwd'], mailConfig['port'], mailConfig['email']) -from . userController import UserController -def getUserController(): - if userController is not None: - return userController - else: - return UserController() -userController = UserController() -accesTokenController = AccesTokenController(accConfig) \ No newline at end of file diff --git a/geruecht/controller/accesTokenController.py b/geruecht/controller/accesTokenController.py index 7ec0c08..160459e 100644 --- a/geruecht/controller/accesTokenController.py +++ b/geruecht/controller/accesTokenController.py @@ -1,11 +1,13 @@ from geruecht.model.accessToken import AccessToken -#import geruecht.controller.userController as userController +import geruecht.controller as gc +import geruecht.controller.userController as uc from geruecht.model import BAR from geruecht.controller import LOGGER from datetime import datetime, timedelta import hashlib from . import Singleton +userController = uc.UserController() class AccesTokenController(metaclass=Singleton): """ Control all createt AccesToken @@ -25,15 +27,15 @@ class AccesTokenController(metaclass=Singleton): Initialize Thread and set tokenList empty. """ LOGGER.info("Initialize AccessTokenController") - self.lifetime = lifetime + self.lifetime = gc.accConfig self.tokenList = [] - #def checkBar(self, user): - # if (userController.checkBarUser(user)): - # user.group.append(BAR) - # elif BAR in user.group: - # user.group.remove(BAR) + def checkBar(self, user): + if (userController.checkBarUser(user)): + user.group.append(BAR) + elif BAR in user.group: + user.group.remove(BAR) def validateAccessToken(self, token, group): """ Verify Accestoken diff --git a/geruecht/controller/databaseController.py b/geruecht/controller/databaseController.py index fa4f6a9..50153c7 100644 --- a/geruecht/controller/databaseController.py +++ b/geruecht/controller/databaseController.py @@ -189,7 +189,7 @@ class DatabaseController(metaclass=Singleton): self.db.close() except Exception as err: raise err - return {"user": user, "startdatetime": data['startdatetime'], "enddatetime": data['enddatetime']} + return {"user": user, "startdatetime": data['startdatetime'], "enddatetime": data['enddatetime']} if data else None def getWorkers(self, date): self.connect() diff --git a/geruecht/controller/userController.py b/geruecht/controller/userController.py index 541ff75..151d248 100644 --- a/geruecht/controller/userController.py +++ b/geruecht/controller/userController.py @@ -1,8 +1,15 @@ -from . import LOGGER, Singleton, db, ldapController as ldap, emailController +from . import LOGGER, Singleton, ldapConfig, dbConfig, mailConfig +import geruecht.controller.databaseController as dc +import geruecht.controller.ldapController as lc +import geruecht.controller.emailController as ec from geruecht.model.user import User from geruecht.exceptions import PermissionDenied from datetime import datetime, timedelta +db = dc.DatabaseController(dbConfig['URL'], dbConfig['user'], dbConfig['passwd'], dbConfig['database']) +ldap = lc.LDAPController(ldapConfig['URL'], ldapConfig['dn']) +emailController = ec.EmailController(mailConfig['URL'], mailConfig['user'], mailConfig['passwd'], mailConfig['port'], mailConfig['email']) + class UserController(metaclass=Singleton): def __init__(self): @@ -71,7 +78,11 @@ class UserController(metaclass=Singleton): def checkBarUser(self, user): date = datetime.now() - startdatetime = date.replace(hour=11, minute=0, microsecond=0) + zero = date.replace(hour=0, minute=0, second=0, microsecond=0) + end = zero + timedelta(hours=11) + startdatetime = date.replace(hour=11, minute=0, second=0, microsecond=0) + if date > zero and end > date: + startdatetime = startdatetime - timedelta(days=1) enddatetime = startdatetime + timedelta(days=1) result = False if date >= startdatetime and date < enddatetime: diff --git a/geruecht/finanzer/routes.py b/geruecht/finanzer/routes.py index 209f14e..15bfc3b 100644 --- a/geruecht/finanzer/routes.py +++ b/geruecht/finanzer/routes.py @@ -1,11 +1,14 @@ from flask import Blueprint, request, jsonify from geruecht.finanzer import LOGGER from datetime import datetime -from geruecht.controller import accesTokenController, userController +import geruecht.controller.userController as uc +import geruecht.controller.accesTokenController as ac from geruecht.model import MONEY finanzer = Blueprint("finanzer", __name__) +accesTokenController = ac.AccesTokenController() +userController = uc.UserController() @finanzer.route("/getFinanzerMain") def _getFinanzer(): diff --git a/geruecht/routes.py b/geruecht/routes.py index 346691e..daf8d78 100644 --- a/geruecht/routes.py +++ b/geruecht/routes.py @@ -1,9 +1,12 @@ from geruecht import app, LOGGER from geruecht.exceptions import PermissionDenied -from geruecht.controller import accesTokenController, userController +import geruecht.controller.accesTokenController as ac +import geruecht.controller.userController as uc from geruecht.model import MONEY, BAR, USER, GASTRO from flask import request, jsonify +accesTokenController = ac.AccesTokenController() +userController = uc.UserController() def login(user, password): return user.login(password) @@ -48,7 +51,7 @@ def _login(): user = userController.loginUser(username, password) user.password = password token = accesTokenController.createAccesToken(user) - dic = user.toJSON() + dic = accesTokenController.validateAccessToken(token, [USER]).user.toJSON() dic["token"] = token dic["accessToken"] = token LOGGER.info("User {} success login.".format(username)) diff --git a/geruecht/user/routes.py b/geruecht/user/routes.py index 03f3a0f..089f3c7 100644 --- a/geruecht/user/routes.py +++ b/geruecht/user/routes.py @@ -1,10 +1,15 @@ from flask import Blueprint, request, jsonify -from geruecht.controller import userController, accesTokenController +import geruecht.controller as gc +import geruecht.controller.userController as uc +import geruecht.controller.accesTokenController as ac from geruecht.model import USER from datetime import datetime user = Blueprint("user", __name__) +accesTokenController = ac.AccesTokenController() +userController = uc.UserController() + @user.route("/user/main") def _main(): From f782be934d0627bf002e34c577e48fec1a5991a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tim=20Gr=C3=B6ger?= Date: Sun, 19 Jan 2020 09:07:45 +0100 Subject: [PATCH 3/4] added decoratos for connected in database and login_requird in routes --- geruecht/__init__.py | 2 +- geruecht/baruser/routes.py | 167 +++++++-------- geruecht/controller/databaseController.py | 107 ++++------ geruecht/decorator.py | 21 ++ geruecht/finanzer/routes.py | 243 +++++++++------------- geruecht/user/routes.py | 27 ++- geruecht/vorstand/routes.py | 23 +- 7 files changed, 266 insertions(+), 324 deletions(-) create mode 100644 geruecht/decorator.py diff --git a/geruecht/__init__.py b/geruecht/__init__.py index 012a56e..a303078 100644 --- a/geruecht/__init__.py +++ b/geruecht/__init__.py @@ -15,7 +15,7 @@ from flask_cors import CORS LOGGER.info("Build APP") app = Flask(__name__) CORS(app) -# app.config['SECRET_KEY'] = '0a657b97ef546da90b2db91862ad4e29' +app.config['SECRET_KEY'] = '0a657b97ef546da90b2db91862ad4e29' from geruecht import routes from geruecht.baruser.routes import baruser diff --git a/geruecht/baruser/routes.py b/geruecht/baruser/routes.py index 7f6248d..92ac2bb 100644 --- a/geruecht/baruser/routes.py +++ b/geruecht/baruser/routes.py @@ -1,19 +1,20 @@ from flask import Blueprint, request, jsonify import geruecht.controller as gc import geruecht.controller.ldapController as lc -import geruecht.controller.accesTokenController as ac import geruecht.controller.userController as uc from datetime import datetime from geruecht.model import BAR, MONEY +from geruecht.decorator import login_required baruser = Blueprint("baruser", __name__) ldap= lc.LDAPController(gc.ldapConfig['URL'], gc.ldapConfig['dn']) -accesTokenController = ac.AccesTokenController() userController = uc.UserController() + @baruser.route("/bar") -def _bar(): +@login_required(groups=[BAR]) +def _bar(**kwargs): """ Main function for Baruser Returns JSON-file with all Users, who hast amounts in this month. @@ -22,38 +23,33 @@ def _bar(): JSON-File with Users, who has amounts in this month or ERROR 401 Permission Denied """ - print(request.headers) - token = request.headers.get("Token") - print(token) - accToken = accesTokenController.validateAccessToken(token, [BAR]) - dic = {} - if accToken: - users = userController.getAllUsersfromDB() - for user in users: - geruecht = None - geruecht = user.getGeruecht(datetime.now().year) - if geruecht is not None: - month = geruecht.getMonth(datetime.now().month) - amount = month[0] - month[1] - all = geruecht.getSchulden() - if all != 0: - if all >= 0: - type = 'credit' - else: - type = 'amount' - dic[user.uid] = {"username": user.uid, - "firstname": user.firstname, - "lastname": user.lastname, - "amount": abs(all), - "locked": user.locked, - "type": type - } - return jsonify(dic) - return jsonify({"error": "permission denied"}), 401 + users = userController.getAllUsersfromDB() + for user in users: + geruecht = None + geruecht = user.getGeruecht(datetime.now().year) + if geruecht is not None: + month = geruecht.getMonth(datetime.now().month) + amount = month[0] - month[1] + all = geruecht.getSchulden() + if all != 0: + if all >= 0: + type = 'credit' + else: + type = 'amount' + dic[user.uid] = {"username": user.uid, + "firstname": user.firstname, + "lastname": user.lastname, + "amount": abs(all), + "locked": user.locked, + "type": type + } + return jsonify(dic) + @baruser.route("/baradd", methods=['POST']) -def _baradd(): +@login_required(groups=[BAR]) +def _baradd(**kwargs): """ Function for Baruser to add amount This function added to the user with the posted userID the posted amount. @@ -62,35 +58,31 @@ def _baradd(): JSON-File with userID and the amount or ERROR 401 Permission Denied """ - token = request.headers.get("Token") - print(token) - accToken = accesTokenController.validateAccessToken(token, [BAR]) + data = request.get_json() + userID = data['userId'] + amount = int(data['amount']) - if accToken: - data = request.get_json() - userID = data['userId'] - amount = int(data['amount']) + date = datetime.now() + userController.addAmount(userID, amount, year=date.year, month=date.month) + user = userController.getUser(userID) + geruecht = user.getGeruecht(year=date.year) + month = geruecht.getMonth(month=date.month) + amount = abs(month[0] - month[1]) + all = geruecht.getSchulden() + if all >= 0: + type = 'credit' + else: + type = 'amount' + dic = user.toJSON() + dic['amount'] = abs(all) + dic['type'] = type - date = datetime.now() - userController.addAmount(userID, amount, year=date.year, month=date.month) - user = userController.getUser(userID) - geruecht = user.getGeruecht(year=date.year) - month = geruecht.getMonth(month=date.month) - amount = abs(month[0] - month[1]) - all = geruecht.getSchulden() - if all >= 0: - type = 'credit' - else: - type = 'amount' - dic = user.toJSON() - dic['amount'] = abs(all) - dic['type'] = type + return jsonify(dic) - return jsonify(dic) - return jsonify({"error", "permission denied"}), 401 @baruser.route("/barGetUsers") -def _getUsers(): +@login_required(groups=[BAR, MONEY]) +def _getUsers(**kwargs): """ Get Users without amount This Function returns all Users, who hasn't an amount in this month. @@ -99,48 +91,33 @@ def _getUsers(): JSON-File with Users or ERROR 401 Permission Denied """ - token = request.headers.get("Token") - print(token) - accToken = accesTokenController.validateAccessToken(token, [BAR]) - retVal = {} - if accToken: - retVal = ldap.getAllUser() - return jsonify(retVal) - return jsonify({"error": "permission denied"}), 401 + retVal = ldap.getAllUser() + return jsonify(retVal) + @baruser.route("/barGetUser", methods=['POST']) -def _getUser(): - token = request.headers.get("Token") - accToken = accesTokenController.validateAccessToken(token, [BAR]) - if accToken: - data = request.get_json() - username = data['userId'] - user = userController.getUser(username) - amount = user.getGeruecht(datetime.now().year).getSchulden() - if amount >= 0: - type = 'credit' - else: - type = 'amount' +@login_required(groups=[BAR]) +def _getUser(**kwargs): + data = request.get_json() + username = data['userId'] + user = userController.getUser(username) + amount = user.getGeruecht(datetime.now().year).getSchulden() + if amount >= 0: + type = 'credit' + else: + type = 'amount' + + retVal = user.toJSON() + retVal['amount'] = amount + retVal['type'] = type + return jsonify(retVal) - retVal = user.toJSON() - retVal['amount'] = amount - retVal['type'] = type - return jsonify(retVal) - return jsonify("error", "permission denied"), 401 @baruser.route("/search", methods=['POST']) -def _search(): - token = request.headers.get("Token") - print(token) - accToken = accesTokenController.validateAccessToken(token, [BAR, MONEY]) - - if accToken: - data = request.get_json() - - searchString = data['searchString'] - - retVal = ldap.searchUser(searchString) - - return jsonify(retVal) - return jsonify({"error": "permission denied"}), 401 +@login_required(groups=[BAR, MONEY]) +def _search(**kwargs): + data = request.get_json() + searchString = data['searchString'] + retVal = ldap.searchUser(searchString) + return jsonify(retVal) diff --git a/geruecht/controller/databaseController.py b/geruecht/controller/databaseController.py index 50153c7..a1df38e 100644 --- a/geruecht/controller/databaseController.py +++ b/geruecht/controller/databaseController.py @@ -4,6 +4,14 @@ from geruecht.model.user import User from geruecht.model.creditList import CreditList from datetime import datetime, timedelta +def connected(func): + def wrapper(*args, **kwargs): + self = args[0] + if not self.db.open: + self.connect() + return func(*args,**kwargs) + return wrapper + class DatabaseController(metaclass=Singleton): ''' DatabaesController @@ -24,16 +32,12 @@ class DatabaseController(metaclass=Singleton): self.db = pymysql.connect(self.url, self.user, self.password, self.database, cursorclass=pymysql.cursors.DictCursor) except Exception as err: raise err - + @connected def getAllUser(self): - self.connect() cursor = self.db.cursor() - try: - cursor.execute("select * from user") - data = cursor.fetchall() - self.db.close() - except Exception as err: - raise err + cursor.execute("select * from user") + data = cursor.fetchall() + self.db.close() if data: retVal = [] @@ -43,34 +47,26 @@ class DatabaseController(metaclass=Singleton): user.initGeruechte(creditLists) retVal.append(user) return retVal - + @connected def getUser(self, username): - self.connect() retVal = None cursor = self.db.cursor() - try: - cursor.execute("select * from user where uid='{}'".format(username)) - data = cursor.fetchone() - self.db.close() - except Exception as err: - raise err + cursor.execute("select * from user where uid='{}'".format(username)) + data = cursor.fetchone() + self.db.close() if data: retVal = User(data) creditLists = self.getCreditListFromUser(retVal) retVal.initGeruechte(creditLists) return retVal - + @connected def getUserById(self, id): - self.connect() retVal = None - try: - cursor = self.db.cursor() - cursor.execute("select * from user where id={}".format(id)) - data = cursor.fetchone() - self.db.close() - except Exception as err: - raise err + cursor = self.db.cursor() + cursor.execute("select * from user where id={}".format(id)) + data = cursor.fetchone() + self.db.close() if data: retVal = User(data) creditLists = self.getCreditListFromUser(retVal) @@ -85,8 +81,8 @@ class DatabaseController(metaclass=Singleton): retVal += group return retVal + @connected def insertUser(self, user): - self.connect() cursor = self.db.cursor() groups = self._convertGroupToString(user.group) try: @@ -99,8 +95,8 @@ class DatabaseController(metaclass=Singleton): raise err self.db.close() + @connected def updateUser(self, user): - self.connect() cursor = self.db.cursor() groups = self._convertGroupToString(user.group) try: @@ -117,38 +113,35 @@ class DatabaseController(metaclass=Singleton): self.db.close() + @connected def getCreditListFromUser(self, user, **kwargs): - self.connect() cursor = self.db.cursor() - try: - if 'year' in kwargs: - sql = "select * from creditList where user_id={} and year_date={}".format(user.id, kwargs['year']) - else: - sql = "select * from creditList where user_id={}".format(user.id) - cursor.execute(sql) - data = cursor.fetchall() - self.db.close() - except Exception as err: - self.db.close() - raise err + if 'year' in kwargs: + sql = "select * from creditList where user_id={} and year_date={}".format(user.id, kwargs['year']) + else: + sql = "select * from creditList where user_id={}".format(user.id) + cursor.execute(sql) + data = cursor.fetchall() + self.db.close() if len(data) == 1: return [CreditList(data[0])] else: return [CreditList(value) for value in data] + @connected def createCreditList(self, user_id, year=datetime.now().year): - self.connect() cursor = self.db.cursor() try: cursor.execute("insert into creditList (year_date, user_id) values ({},{})".format(year, user_id)) self.db.commit() self.db.close() except Exception as err: + self.db.rollback() self.db.close() raise err + @connected def updateCreditList(self, creditlist): - self.connect() cursor = self.db.cursor() try: cursor.execute("select * from creditList where user_id={} and year_date={}".format(creditlist.user_id, creditlist.year)) @@ -179,32 +172,24 @@ class DatabaseController(metaclass=Singleton): self.db.rollback() self.db.close() raise err - + @connected def getWorker(self, user, date): - self.connect() - try: - cursor = self.db.cursor() - cursor.execute("select * from bardienste where user_id={} and startdatetime='{}'".format(user.id, date)) - data = cursor.fetchone() - self.db.close() - except Exception as err: - raise err + cursor = self.db.cursor() + cursor.execute("select * from bardienste where user_id={} and startdatetime='{}'".format(user.id, date)) + data = cursor.fetchone() + self.db.close() return {"user": user, "startdatetime": data['startdatetime'], "enddatetime": data['enddatetime']} if data else None + @connected def getWorkers(self, date): - self.connect() - try: - cursor = self.db.cursor() - cursor.execute("select * from bardienste where startdatetime='{}'".format(date)) - data = cursor.fetchall() - self.db.close() - except Exception as err: - raise err - + cursor = self.db.cursor() + cursor.execute("select * from bardienste where startdatetime='{}'".format(date)) + data = cursor.fetchall() + self.db.close() return [{"user": self.getUserById(work['user_id']).toJSON(), "startdatetime": work['startdatetime'], "enddatetime": work['enddatetime']} for work in data] + @connected def setWorker(self, user, date): - self.connect() try: cursor = self.db.cursor() cursor.execute("insert into bardienste (user_id, startdatetime, enddatetime) values ({},'{}','{}')".format(user.id, date, date + timedelta(days=1))) @@ -215,8 +200,8 @@ class DatabaseController(metaclass=Singleton): self.db.close() raise err + @connected def deleteWorker(self, user, date): - self.connect() try: cursor = self.db.cursor() cursor.execute("delete from bardienste where user_id={} and startdatetime='{}'".format(user.id, date)) diff --git a/geruecht/decorator.py b/geruecht/decorator.py new file mode 100644 index 0000000..4addb6a --- /dev/null +++ b/geruecht/decorator.py @@ -0,0 +1,21 @@ +from functools import wraps +def login_required(**kwargs): + import geruecht.controller.accesTokenController as ac + from geruecht.model import BAR, USER, MONEY, GASTRO + from flask import request, jsonify + accessController = ac.AccesTokenController() + groups = [USER, BAR, GASTRO, MONEY] + if "groups" in kwargs: + groups = kwargs["groups"] + def real_decorator(func): + @wraps(func) + def wrapper(*args, **kwargs): + token = request.headers.get('Token') + accToken = accessController.validateAccessToken(token, groups) + kwargs['accToken'] = accToken + if accToken: + return func(*args, **kwargs) + else: + return jsonify({"error": "error", "message": "permission denied"}), 401 + return wrapper + return real_decorator \ No newline at end of file diff --git a/geruecht/finanzer/routes.py b/geruecht/finanzer/routes.py index 15bfc3b..92d7be1 100644 --- a/geruecht/finanzer/routes.py +++ b/geruecht/finanzer/routes.py @@ -2,16 +2,17 @@ from flask import Blueprint, request, jsonify from geruecht.finanzer import LOGGER from datetime import datetime import geruecht.controller.userController as uc -import geruecht.controller.accesTokenController as ac from geruecht.model import MONEY +from geruecht.decorator import login_required finanzer = Blueprint("finanzer", __name__) -accesTokenController = ac.AccesTokenController() userController = uc.UserController() + @finanzer.route("/getFinanzerMain") -def _getFinanzer(): +@login_required(groups=[MONEY]) +def _getFinanzer(**kwargs): """ Function for /getFinanzerMain Retrieves all User for the groupe 'moneymaster' @@ -20,26 +21,20 @@ def _getFinanzer(): A JSON-File with Users or ERROR 401 Permission Denied. """ - LOGGER.info("Get main for Finanzer") - token = request.headers.get("Token") - LOGGER.debug("Verify AccessToken with Token {}".format(token)) - accToken = accesTokenController.validateAccessToken(token, [MONEY]) - if accToken: - LOGGER.debug("Get all Useres") - users = userController.getAllUsersfromDB() - dic = {} - for user in users: - LOGGER.debug("Add User {} to ReturnValue".format(user)) - dic[user.uid] = user.toJSON() - dic[user.uid]['creditList'] = {credit.year: credit.toJSON() for credit in user.geruechte} - LOGGER.debug("ReturnValue is {}".format(dic)) - LOGGER.info("Send main for Finanzer") - return jsonify(dic) - LOGGER.info("Permission Denied") - return jsonify({"error": "permission denied"}), 401 + LOGGER.debug("Get all Useres") + users = userController.getAllUsersfromDB() + dic = {} + for user in users: + LOGGER.debug("Add User {} to ReturnValue".format(user)) + dic[user.uid] = user.toJSON() + dic[user.uid]['creditList'] = {credit.year: credit.toJSON() for credit in user.geruechte} + LOGGER.debug("ReturnValue is {}".format(dic)) + LOGGER.info("Send main for Finanzer") + return jsonify(dic) @finanzer.route("/finanzerAddAmount", methods=['POST']) -def _addAmount(): +@login_required(groups=[MONEY]) +def _addAmount(**kwargs): """ Add Amount to User This Function add an amount to the user with posted userID. @@ -50,39 +45,32 @@ def _addAmount(): JSON-File with geruecht of year or ERROR 401 Permission Denied """ - LOGGER.info("Add Amount") - token = request.headers.get("Token") - LOGGER.debug("Verify AccessToken with Token {}".format(token)) - accToken = accesTokenController.validateAccessToken(token, [MONEY]) - - if accToken: - data = request.get_json() - LOGGER.debug("Get data {}".format(data)) - userID = data['userId'] - amount = int(data['amount']) - LOGGER.debug("UserID is {} and amount is {}".format(userID, amount)) - try: - year = int(data['year']) - except KeyError as er: - LOGGER.error("KeyError in year. Year is set to default.") - year = datetime.now().year - try: - month = int(data['month']) - except KeyError as er: - LOGGER.error("KeyError in month. Month is set to default.") - month = datetime.now().month - LOGGER.debug("Year is {} and Month is {}".format(year, month)) - userController.addAmount(userID, amount, year=year, month=month, finanzer=True) - user = userController.getUser(userID) - retVal = {str(geruecht.year): geruecht.toJSON() for geruecht in user.geruechte} - retVal['locked'] = user.locked - LOGGER.info("Send updated Geruecht") - return jsonify(retVal) - LOGGER.info("Permission Denied") - return jsonify({"error": "permission denied"}), 401 + data = request.get_json() + LOGGER.debug("Get data {}".format(data)) + userID = data['userId'] + amount = int(data['amount']) + LOGGER.debug("UserID is {} and amount is {}".format(userID, amount)) + try: + year = int(data['year']) + except KeyError as er: + LOGGER.error("KeyError in year. Year is set to default.") + year = datetime.now().year + try: + month = int(data['month']) + except KeyError as er: + LOGGER.error("KeyError in month. Month is set to default.") + month = datetime.now().month + LOGGER.debug("Year is {} and Month is {}".format(year, month)) + userController.addAmount(userID, amount, year=year, month=month, finanzer=True) + user = userController.getUser(userID) + retVal = {str(geruecht.year): geruecht.toJSON() for geruecht in user.geruechte} + retVal['locked'] = user.locked + LOGGER.info("Send updated Geruecht") + return jsonify(retVal) @finanzer.route("/finanzerAddCredit", methods=['POST']) -def _addCredit(): +@login_required(groups=[MONEY]) +def _addCredit(**kwargs): """ Add Credit to User This Function add an credit to the user with posted userID. @@ -93,106 +81,79 @@ def _addCredit(): JSON-File with geruecht of year or ERROR 401 Permission Denied """ - LOGGER.info("Add Amount") - token = request.headers.get("Token") - LOGGER.debug("Verify AccessToken with Token {}".format(token)) - accToken = accesTokenController.validateAccessToken(token, [MONEY]) + data = request.get_json() + print(data) + LOGGER.debug("Get data {}".format(data)) + userID = data['userId'] + credit = int(data['credit']) + LOGGER.debug("UserID is {} and credit is {}".format(userID, credit)) - if accToken: + try: + year = int(data['year']) + except KeyError as er: + LOGGER.error("KeyError in year. Year is set to default.") + year = datetime.now().year + try: + month = int(data['month']) + except KeyError as er: + LOGGER.error("KeyError in month. Month is set to default.") + month = datetime.now().month - data = request.get_json() - print(data) - LOGGER.debug("Get data {}".format(data)) - userID = data['userId'] - credit = int(data['credit']) - LOGGER.debug("UserID is {} and credit is {}".format(userID, credit)) + LOGGER.debug("Year is {} and Month is {}".format(year, month)) + userController.addCredit(userID, credit, year=year, month=month).toJSON() + user = userController.getUser(userID) + retVal = {str(geruecht.year): geruecht.toJSON() for geruecht in user.geruechte} + retVal['locked'] = user.locked + LOGGER.info("Send updated Geruecht") + return jsonify(retVal) - try: - year = int(data['year']) - except KeyError as er: - LOGGER.error("KeyError in year. Year is set to default.") - year = datetime.now().year - try: - month = int(data['month']) - except KeyError as er: - LOGGER.error("KeyError in month. Month is set to default.") - month = datetime.now().month - - LOGGER.debug("Year is {} and Month is {}".format(year, month)) - userController.addCredit(userID, credit, year=year, month=month).toJSON() - user = userController.getUser(userID) - retVal = {str(geruecht.year): geruecht.toJSON() for geruecht in user.geruechte} - retVal['locked'] = user.locked - LOGGER.info("Send updated Geruecht") - return jsonify(retVal) - LOGGER.info("Permission Denied") - return jsonify({"error": "permission denied"}), 401 @finanzer.route("/finanzerLock", methods=['POST']) -def _finanzerLock(): - token = request.headers.get("Token") - accToken = accesTokenController.validateAccessToken(token, [MONEY]) +@login_required(groups=[MONEY]) +def _finanzerLock(**kwargs): + data = request.get_json() + username = data['userId'] + locked = bool(data['locked']) + retVal = userController.lockUser(username, locked).toJSON() + return jsonify(retVal) - if accToken: - data = request.get_json() - username = data['userId'] - locked = bool(data['locked']) - retVal = userController.lockUser(username, locked).toJSON() - return jsonify(retVal) - return jsonify({"error": "permission denied"}), 401 @finanzer.route("/finanzerSetConfig", methods=['POST']) -def _finanzerSetConfig(): - token = request.headers.get("Token") - accToken = accesTokenController.validateAccessToken(token, [MONEY]) - - if accToken: - data = request.get_json() - username = data['userId'] - autoLock = bool(data['autoLock']) - limit = int(data['limit']) - retVal = userController.updateConfig(username, {'lockLimit': limit, 'autoLock': autoLock}).toJSON() - return jsonify(retVal) - return jsonify({"error": "permission denied"}), 401 +@login_required(groups=[MONEY]) +def _finanzerSetConfig(**kwargs): + data = request.get_json() + username = data['userId'] + autoLock = bool(data['autoLock']) + limit = int(data['limit']) + retVal = userController.updateConfig(username, {'lockLimit': limit, 'autoLock': autoLock}).toJSON() + return jsonify(retVal) @finanzer.route("/finanzerAddUser", methods=['POST']) -def _finanzerAddUser(): - token = request.headers.get("Token") - accToken = accesTokenController.validateAccessToken(token, [MONEY]) - - if accToken: - data = request.get_json() - username = data['userId'] - userController.getUser(username) - LOGGER.debug("Get all Useres") - users = userController.getAllUsersfromDB() - dic = {} - for user in users: - LOGGER.debug("Add User {} to ReturnValue".format(user)) - dic[user.uid] = user.toJSON() - dic[user.uid]['creditList'] = {credit.year: credit.toJSON() for credit in user.geruechte} - LOGGER.debug("ReturnValue is {}".format(dic)) - return jsonify(dic), 200 - return jsonify({"error": "permission denied"}), 401 +@login_required(groups=[MONEY]) +def _finanzerAddUser(**kwargs): + data = request.get_json() + username = data['userId'] + userController.getUser(username) + LOGGER.debug("Get all Useres") + users = userController.getAllUsersfromDB() + dic = {} + for user in users: + LOGGER.debug("Add User {} to ReturnValue".format(user)) + dic[user.uid] = user.toJSON() + dic[user.uid]['creditList'] = {credit.year: credit.toJSON() for credit in user.geruechte} + LOGGER.debug("ReturnValue is {}".format(dic)) + return jsonify(dic), 200 @finanzer.route("/finanzerSendOneMail", methods=['POST']) -def _finanzerSendOneMail(): - token = request.headers.get("Token") - accToken = accesTokenController.validateAccessToken(token, [MONEY]) - - if accToken: - data = request.get_json() - username = data['userId'] - retVal = userController.sendMail(username) - return jsonify(retVal) - return jsonify({"error:", "permission denied"}), 401 +@login_required(groups=[MONEY]) +def _finanzerSendOneMail(**kwargs): + data = request.get_json() + username = data['userId'] + retVal = userController.sendMail(username) + return jsonify(retVal) @finanzer.route("/finanzerSendAllMail", methods=['GET']) -def _finanzerSendAllMail(): - token = request.headers.get("Token") - accToken = accesTokenController.validateAccessToken(token, [MONEY]) - - if accToken: - retVal = userController.sendAllMail() - return jsonify(retVal) - return jsonify({"error": "permission denied"}), 401 \ No newline at end of file +@login_required(groups=[MONEY]) +def _finanzerSendAllMail(**kwargs): + retVal = userController.sendAllMail() + return jsonify(retVal) \ No newline at end of file diff --git a/geruecht/user/routes.py b/geruecht/user/routes.py index 089f3c7..5b30297 100644 --- a/geruecht/user/routes.py +++ b/geruecht/user/routes.py @@ -1,33 +1,30 @@ from flask import Blueprint, request, jsonify -import geruecht.controller as gc +from geruecht.decorator import login_required import geruecht.controller.userController as uc -import geruecht.controller.accesTokenController as ac from geruecht.model import USER from datetime import datetime user = Blueprint("user", __name__) -accesTokenController = ac.AccesTokenController() userController = uc.UserController() -@user.route("/user/main") -def _main(): - token = request.headers.get("Token") - accToken = accesTokenController.validateAccessToken(token, [USER]) - if accToken: +@user.route("/user/main") +@login_required(groups=[USER]) +def _main(**kwargs): + if 'accToken' in kwargs: + accToken = kwargs['accToken'] accToken.user = userController.getUser(accToken.user.uid) retVal = accToken.user.toJSON() retVal['creditList'] = {credit.year: credit.toJSON() for credit in accToken.user.geruechte} return jsonify(retVal) - return jsonify({"error": "permission denied"}), 401 + return jsonify("error", "something went wrong"), 500 @user.route("/user/addAmount", methods=['POST']) -def _addAmount(): - - token = request.headers.get("Token") - accToken = accesTokenController.validateAccessToken(token, [USER]) - if accToken: +@login_required(groups=[USER]) +def _addAmount(**kwargs): + if 'accToken' in kwargs: + accToken = kwargs['accToken'] data = request.get_json() amount = int(data['amount']) date = datetime.now() @@ -36,4 +33,4 @@ def _addAmount(): retVal = accToken.user.toJSON() retVal['creditList'] = {credit.year: credit.toJSON() for credit in accToken.user.geruechte} return jsonify(retVal) - return jsonify({"error": "permission denied"}), 401 \ No newline at end of file + return jsonify({"error": "something went wrong"}), 500 \ No newline at end of file diff --git a/geruecht/vorstand/routes.py b/geruecht/vorstand/routes.py index a0535a8..3d69f90 100644 --- a/geruecht/vorstand/routes.py +++ b/geruecht/vorstand/routes.py @@ -1,24 +1,25 @@ from flask import Blueprint, request, jsonify from datetime import datetime -from geruecht.controller import accesTokenController, userController +import geruecht.controller.userController as uc +from geruecht.decorator import login_required from geruecht.model import MONEY, GASTRO vorstand = Blueprint("vorstand", __name__) +userController = uc.UserController() + @vorstand.route("/sm/addUser", methods=['POST', 'GET']) + +@login_required(groups=[MONEY, GASTRO]) def _addUser(): if request.method == 'GET': return "

HEllo World

" - token = request.headers.get("Token") - accToken = accesTokenController.validateAccessToken(token, [MONEY, GASTRO]) - if accToken: - data = request.get_json() - user = data['user'] - date = datetime.utcfromtimestamp(int(data['date'])) - userController.addWorker(user['username'], date) + data = request.get_json() + user = data['user'] + date = datetime.utcfromtimestamp(int(data['date'])) + userController.addWorker(user['username'], date) - print(data) - return jsonify({"date": date}) - return jsonify({"error": "permission denied"}), 401 \ No newline at end of file + print(data) + return jsonify({"date": date}) \ No newline at end of file From 635051d615d2667434dba219f65bc36180b5665a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tim=20Gr=C3=B6ger?= Date: Sun, 19 Jan 2020 21:32:58 +0100 Subject: [PATCH 4/4] change database controller without multithreading --- geruecht/__init__.py | 8 + geruecht/configparser.py | 3 +- geruecht/controller/databaseController.py | 190 +++++++--------------- geruecht/controller/userController.py | 5 +- geruecht/model/priceList.py | 17 -- geruecht/vorstand/routes.py | 26 ++- 6 files changed, 97 insertions(+), 152 deletions(-) delete mode 100644 geruecht/model/priceList.py diff --git a/geruecht/__init__.py b/geruecht/__init__.py index a303078..af71892 100644 --- a/geruecht/__init__.py +++ b/geruecht/__init__.py @@ -5,6 +5,8 @@ """ from .logger import getLogger +from geruecht.controller import dbConfig +from flask_mysqldb import MySQL LOGGER = getLogger(__name__) LOGGER.info("Initialize App") @@ -16,6 +18,12 @@ LOGGER.info("Build APP") app = Flask(__name__) CORS(app) app.config['SECRET_KEY'] = '0a657b97ef546da90b2db91862ad4e29' +app.config['MYSQL_HOST'] = dbConfig['URL'] +app.config['MYSQL_USER'] = dbConfig['user'] +app.config['MYSQL_PASSWORD'] = dbConfig['passwd'] +app.config['MYSQL_DB'] = dbConfig['database'] +app.config['MYSQL_CURSORCLASS'] = 'DictCursor' +db = MySQL(app) from geruecht import routes from geruecht.baruser.routes import baruser diff --git a/geruecht/configparser.py b/geruecht/configparser.py index fc92b61..e1ab855 100644 --- a/geruecht/configparser.py +++ b/geruecht/configparser.py @@ -1,6 +1,7 @@ import yaml import sys -from . import LOGGER +from .logger import getLogger +LOGGER = getLogger(__name__) default = { 'AccessTokenLifeTime': 1800, diff --git a/geruecht/controller/databaseController.py b/geruecht/controller/databaseController.py index a1df38e..da45192 100644 --- a/geruecht/controller/databaseController.py +++ b/geruecht/controller/databaseController.py @@ -1,17 +1,10 @@ import pymysql from . import Singleton +from geruecht import db from geruecht.model.user import User from geruecht.model.creditList import CreditList from datetime import datetime, timedelta -def connected(func): - def wrapper(*args, **kwargs): - self = args[0] - if not self.db.open: - self.connect() - return func(*args,**kwargs) - return wrapper - class DatabaseController(metaclass=Singleton): ''' DatabaesController @@ -19,25 +12,13 @@ class DatabaseController(metaclass=Singleton): Connect to the Database and execute sql-executions ''' - def __init__(self, url='192.168.5.108', user='wu5', password='E1n$tein', database='geruecht'): - self.url = url - self.user = user - self.password = password - self.database = database - self.connect() + def __init__(self): + self.db = db - - def connect(self): - try: - self.db = pymysql.connect(self.url, self.user, self.password, self.database, cursorclass=pymysql.cursors.DictCursor) - except Exception as err: - raise err - @connected def getAllUser(self): - cursor = self.db.cursor() + cursor = self.db.connection.cursor() cursor.execute("select * from user") data = cursor.fetchall() - self.db.close() if data: retVal = [] @@ -47,26 +28,24 @@ class DatabaseController(metaclass=Singleton): user.initGeruechte(creditLists) retVal.append(user) return retVal - @connected + def getUser(self, username): retVal = None - cursor = self.db.cursor() + cursor = self.db.connection.cursor() cursor.execute("select * from user where uid='{}'".format(username)) data = cursor.fetchone() - self.db.close() if data: retVal = User(data) creditLists = self.getCreditListFromUser(retVal) retVal.initGeruechte(creditLists) return retVal - @connected + def getUserById(self, id): retVal = None - cursor = self.db.cursor() + cursor = self.db.connection.cursor() cursor.execute("select * from user where id={}".format(id)) data = cursor.fetchone() - self.db.close() if data: retVal = User(data) creditLists = self.getCreditListFromUser(retVal) @@ -81,136 +60,93 @@ class DatabaseController(metaclass=Singleton): retVal += group return retVal - @connected + def insertUser(self, user): - cursor = self.db.cursor() + cursor = self.db.connection.cursor() groups = self._convertGroupToString(user.group) - try: - cursor.execute("insert into user (uid, dn, firstname, lastname, gruppe, lockLimit, locked, autoLock, mail) VALUES ('{}','{}','{}','{}','{}',{},{},{},'{}')".format( - user.uid, user.dn, user.firstname, user.lastname, groups, user.limit, user.locked, user.autoLock, user.mail)) - self.db.commit() - except Exception as err: - self.db.rollback() - self.db.close() - raise err - self.db.close() + cursor.execute("insert into user (uid, dn, firstname, lastname, gruppe, lockLimit, locked, autoLock, mail) VALUES ('{}','{}','{}','{}','{}',{},{},{},'{}')".format( + user.uid, user.dn, user.firstname, user.lastname, groups, user.limit, user.locked, user.autoLock, user.mail)) + self.db.connection.commit() + - @connected def updateUser(self, user): - cursor = self.db.cursor() + cursor = self.db.connection.cursor() groups = self._convertGroupToString(user.group) - try: - sql = "update user set dn='{}', firstname='{}', lastname='{}', gruppe='{}', lockLimit={}, locked={}, autoLock={}, mail='{}' where uid='{}'".format( - user.dn, user.firstname, user.lastname, groups, user.limit, user.locked, user.autoLock, user.mail, user.uid) - print(sql) - cursor.execute(sql) - self.db.commit() - except Exception as err: - self.db.rollback() - self.db.close() - print(err.__traceback__) - raise err + sql = "update user set dn='{}', firstname='{}', lastname='{}', gruppe='{}', lockLimit={}, locked={}, autoLock={}, mail='{}' where uid='{}'".format( + user.dn, user.firstname, user.lastname, groups, user.limit, user.locked, user.autoLock, user.mail, user.uid) + print(sql) + cursor.execute(sql) + self.db.connection.commit() - self.db.close() - @connected def getCreditListFromUser(self, user, **kwargs): - cursor = self.db.cursor() + cursor = self.db.connection.cursor() if 'year' in kwargs: sql = "select * from creditList where user_id={} and year_date={}".format(user.id, kwargs['year']) else: sql = "select * from creditList where user_id={}".format(user.id) cursor.execute(sql) data = cursor.fetchall() - self.db.close() if len(data) == 1: return [CreditList(data[0])] else: return [CreditList(value) for value in data] - @connected - def createCreditList(self, user_id, year=datetime.now().year): - cursor = self.db.cursor() - try: - cursor.execute("insert into creditList (year_date, user_id) values ({},{})".format(year, user_id)) - self.db.commit() - self.db.close() - except Exception as err: - self.db.rollback() - self.db.close() - raise err - @connected + def createCreditList(self, user_id, year=datetime.now().year): + cursor = self.db.connection.cursor() + cursor.execute("insert into creditList (year_date, user_id) values ({},{})".format(year, user_id)) + self.db.connection.commit() + + def updateCreditList(self, creditlist): - cursor = self.db.cursor() - try: - cursor.execute("select * from creditList where user_id={} and year_date={}".format(creditlist.user_id, creditlist.year)) - data = cursor.fetchall() - self.db.close() - if len(data) == 0: - self.createCreditList(creditlist.user_id, creditlist.year) - sql = "update creditList set jan_guthaben={}, jan_schulden={},feb_guthaben={}, feb_schulden={}, maer_guthaben={}, maer_schulden={}, apr_guthaben={}, apr_schulden={}, mai_guthaben={}, mai_schulden={}, jun_guthaben={}, jun_schulden={}, jul_guthaben={}, jul_schulden={}, aug_guthaben={}, aug_schulden={},sep_guthaben={}, sep_schulden={},okt_guthaben={}, okt_schulden={}, nov_guthaben={}, nov_schulden={}, dez_guthaben={}, dez_schulden={}, last_schulden={} where year_date={} and user_id={}".format(creditlist.jan_guthaben, creditlist.jan_schulden, - creditlist.feb_guthaben, creditlist.feb_schulden, - creditlist.maer_guthaben, creditlist.maer_schulden, - creditlist.apr_guthaben, creditlist.apr_schulden, - creditlist.mai_guthaben, creditlist.mai_schulden, - creditlist.jun_guthaben, creditlist.jun_schulden, - creditlist.jul_guthaben, creditlist.jul_schulden, - creditlist.aug_guthaben, creditlist.aug_schulden, - creditlist.sep_guthaben, creditlist.sep_schulden, - creditlist.okt_guthaben, creditlist.okt_schulden, - creditlist.nov_guthaben, creditlist.nov_schulden, - creditlist.dez_guthaben, creditlist.dez_schulden, - creditlist.last_schulden, creditlist.year, creditlist.user_id) - print(sql) - self.connect() - cursor = self.db.cursor() - cursor.execute(sql) - self.db.commit() - self.db.close() - except Exception as err: - self.db.rollback() - self.db.close() - raise err - @connected + cursor = self.db.connection.cursor() + cursor.execute("select * from creditList where user_id={} and year_date={}".format(creditlist.user_id, creditlist.year)) + data = cursor.fetchall() + if len(data) == 0: + self.createCreditList(creditlist.user_id, creditlist.year) + sql = "update creditList set jan_guthaben={}, jan_schulden={},feb_guthaben={}, feb_schulden={}, maer_guthaben={}, maer_schulden={}, apr_guthaben={}, apr_schulden={}, mai_guthaben={}, mai_schulden={}, jun_guthaben={}, jun_schulden={}, jul_guthaben={}, jul_schulden={}, aug_guthaben={}, aug_schulden={},sep_guthaben={}, sep_schulden={},okt_guthaben={}, okt_schulden={}, nov_guthaben={}, nov_schulden={}, dez_guthaben={}, dez_schulden={}, last_schulden={} where year_date={} and user_id={}".format(creditlist.jan_guthaben, creditlist.jan_schulden, + creditlist.feb_guthaben, creditlist.feb_schulden, + creditlist.maer_guthaben, creditlist.maer_schulden, + creditlist.apr_guthaben, creditlist.apr_schulden, + creditlist.mai_guthaben, creditlist.mai_schulden, + creditlist.jun_guthaben, creditlist.jun_schulden, + creditlist.jul_guthaben, creditlist.jul_schulden, + creditlist.aug_guthaben, creditlist.aug_schulden, + creditlist.sep_guthaben, creditlist.sep_schulden, + creditlist.okt_guthaben, creditlist.okt_schulden, + creditlist.nov_guthaben, creditlist.nov_schulden, + creditlist.dez_guthaben, creditlist.dez_schulden, + creditlist.last_schulden, creditlist.year, creditlist.user_id) + print(sql) + cursor = self.db.connection.cursor() + cursor.execute(sql) + self.db.connection.commit() + def getWorker(self, user, date): - cursor = self.db.cursor() + cursor = self.db.connection.cursor() cursor.execute("select * from bardienste where user_id={} and startdatetime='{}'".format(user.id, date)) data = cursor.fetchone() - self.db.close() - return {"user": user, "startdatetime": data['startdatetime'], "enddatetime": data['enddatetime']} if data else None + return {"user": user.toJSON(), "startdatetime": data['startdatetime'], "enddatetime": data['enddatetime']} if data else None + - @connected def getWorkers(self, date): - cursor = self.db.cursor() + cursor = self.db.connection.cursor() cursor.execute("select * from bardienste where startdatetime='{}'".format(date)) data = cursor.fetchall() - self.db.close() return [{"user": self.getUserById(work['user_id']).toJSON(), "startdatetime": work['startdatetime'], "enddatetime": work['enddatetime']} for work in data] - @connected - def setWorker(self, user, date): - try: - cursor = self.db.cursor() - cursor.execute("insert into bardienste (user_id, startdatetime, enddatetime) values ({},'{}','{}')".format(user.id, date, date + timedelta(days=1))) - self.db.commit() - self.db.close() - except Exception as err: - self.db.rollback() - self.db.close() - raise err - @connected + def setWorker(self, user, date): + cursor = self.db.connection.cursor() + cursor.execute("insert into bardienste (user_id, startdatetime, enddatetime) values ({},'{}','{}')".format(user.id, date, date + timedelta(days=1))) + self.db.connection.commit() + + def deleteWorker(self, user, date): - try: - cursor = self.db.cursor() - cursor.execute("delete from bardienste where user_id={} and startdatetime='{}'".format(user.id, date)) - self.db.commit() - self.db.close() - except Exception as err: - self.db.rollback() - self.db.close() - raise err + cursor = self.db.connection.cursor() + cursor.execute("delete from bardienste where user_id={} and startdatetime='{}'".format(user.id, date)) + self.db.connection.commit() if __name__ == '__main__': db = DatabaseController() diff --git a/geruecht/controller/userController.py b/geruecht/controller/userController.py index 151d248..1590749 100644 --- a/geruecht/controller/userController.py +++ b/geruecht/controller/userController.py @@ -6,7 +6,7 @@ from geruecht.model.user import User from geruecht.exceptions import PermissionDenied from datetime import datetime, timedelta -db = dc.DatabaseController(dbConfig['URL'], dbConfig['user'], dbConfig['passwd'], dbConfig['database']) +db = dc.DatabaseController() ldap = lc.LDAPController(ldapConfig['URL'], ldapConfig['dn']) emailController = ec.EmailController(mailConfig['URL'], mailConfig['user'], mailConfig['passwd'], mailConfig['port'], mailConfig['email']) @@ -25,10 +25,11 @@ class UserController(metaclass=Singleton): user = self.getUser(username) if (not db.getWorker(user, date)): db.setWorker(user, date) + return self.getWorker(date, username=username) def deleteWorker(self, username, date): user = self.getUser(username) - db.setWorker(user, date) + db.deleteWorker(user, date) def lockUser(self, username, locked): user = self.getUser(username) diff --git a/geruecht/model/priceList.py b/geruecht/model/priceList.py deleted file mode 100644 index 0f8c6ef..0000000 --- a/geruecht/model/priceList.py +++ /dev/null @@ -1,17 +0,0 @@ -from geruecht.controller import db - -class PriceList(db.Model): - """ Database Model for PriceList - - PriceList has lots of Drinks and safe all Prices (normal, for club, for other clubs, which catagory, etc) - """ - id = db.Column(db.Integer, primary_key=True) - - name = db.Column(db.String, nullable=False, unique=True) - price = db.Column(db.Integer, nullable=False) - price_club = db.Column(db.Integer, nullable=False) - price_ext_club = db.Column(db.Integer, nullable=False) - category = db.Column(db.Integer, nullable=False) - upPrice = db.Column(db.Integer) - upPrice_club = db.Column(db.Integer) - upPrice_ext_club = db.Column(db.Integer) diff --git a/geruecht/vorstand/routes.py b/geruecht/vorstand/routes.py index 3d69f90..d1184dc 100644 --- a/geruecht/vorstand/routes.py +++ b/geruecht/vorstand/routes.py @@ -9,9 +9,8 @@ userController = uc.UserController() @vorstand.route("/sm/addUser", methods=['POST', 'GET']) - @login_required(groups=[MONEY, GASTRO]) -def _addUser(): +def _addUser(**kwargs): if request.method == 'GET': return "

HEllo World

" @@ -19,7 +18,24 @@ def _addUser(): data = request.get_json() user = data['user'] date = datetime.utcfromtimestamp(int(data['date'])) - userController.addWorker(user['username'], date) + retVal = userController.addWorker(user['username'], date) + print(retVal) + return jsonify(retVal) - print(data) - return jsonify({"date": date}) \ No newline at end of file +@vorstand.route("/sm/getUser", methods=['POST']) +@login_required(groups=[MONEY, GASTRO]) +def _getUser(**kwargs): + data = request.get_json() + date = datetime.utcfromtimestamp(int(data['date'])) + retVal = userController.getWorker(date) + print(retVal) + return jsonify(retVal) + +@vorstand.route("/sm/deleteUser", methods=['POST']) +@login_required(groups=[MONEY, GASTRO]) +def _deletUser(**kwargs): + data = request.get_json() + user = data['user'] + date = datetime.utcfromtimestamp(int(data['date'])) + userController.deleteWorker(user['username'], date) + return jsonify({"ok": "ok"}) \ No newline at end of file