From 23db38690e3bbdd795cef47a5a66dc6583a977ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tim=20Gr=C3=B6ger?= Date: Sun, 22 Dec 2019 22:27:39 +0100 Subject: [PATCH] fixed #79 and other bugs --- geruecht/__init__.py | 4 +-- geruecht/baruser/routes.py | 23 +++++++++------- geruecht/controller/accesTokenController.py | 2 +- geruecht/controller/databaseController.py | 20 ++++++++++++-- geruecht/controller/ldapController.py | 30 ++++++++++++++------- geruecht/finanzer/routes.py | 1 - geruecht/model/user.py | 13 ++++++--- geruecht/routes.py | 8 +++--- 8 files changed, 70 insertions(+), 31 deletions(-) diff --git a/geruecht/__init__.py b/geruecht/__init__.py index 39b790e..4c08b28 100644 --- a/geruecht/__init__.py +++ b/geruecht/__init__.py @@ -82,9 +82,9 @@ accesTokenController.start() from geruecht import routes -#from geruecht.baruser.routes import baruser +from geruecht.baruser.routes import baruser from geruecht.finanzer.routes import finanzer LOGGER.info("Registrate bluebrints") -#app.register_blueprint(baruser) +app.register_blueprint(baruser) app.register_blueprint(finanzer) diff --git a/geruecht/baruser/routes.py b/geruecht/baruser/routes.py index 1852a36..3f25633 100644 --- a/geruecht/baruser/routes.py +++ b/geruecht/baruser/routes.py @@ -23,18 +23,23 @@ def _bar(): dic = {} if accToken is not None: - users = User.query.all() + users = db.getAllUser() for user in users: geruecht = None geruecht = user.getGeruecht() if geruecht is not None: month = geruecht.getMonth(datetime.now().month) - amount = abs(month[0] - month[1]) + amount = month[0] - month[1] if amount != 0: - dic[user.userID] = {"username": user.username, + if amount >= 0: + type = 'credit' + else: + type = 'amount' + dic[user.cn] = {"username": user.cn, "firstname": user.firstname, "lastname": user.lastname, - "amount": abs(month[0] - month[1]) + "amount": abs(month[0] - month[1]), + "type": type } return jsonify(dic) return jsonify({"error": "permission denied"}), 401 @@ -58,12 +63,12 @@ def _baradd(): userID = data['userId'] amount = int(data['amount']) - user = User.query.filter_by(userID=userID).first() + user = db.getUser(userID) month = user.addAmount(amount) amount = abs(month[0] - month[1]) - return jsonify({"userId": user.userID, "amount": amount}) + return jsonify({"userId": user.cn, "amount": amount}) return jsonify({"error", "permission denied"}), 401 @baruser.route("/barGetUsers") @@ -82,11 +87,11 @@ def _getUsers(): retVal = {} if accToken is not None: - users = User.query.all() + users = db.getAllUser() for user in users: month = user.getGeruecht().getMonth() if month == 0: - retVal[user.userID] = {user.toJSON()} + retVal[user.cn] = {user.toJSON()} return jsonify(retVal) return jsonify({"error": "permission denied"}), 401 @@ -108,7 +113,7 @@ def _getUser(): data = request.get_json() userID = data['userId'] - user = User.query.filter_by(userID=userID) + user = db.getUser(userID) month = user.getGeruecht().getMonth() return jsonify({"userId": user.userID, "amount": month[1], "credit": month[0]}) diff --git a/geruecht/controller/accesTokenController.py b/geruecht/controller/accesTokenController.py index 6943371..ca92c9b 100644 --- a/geruecht/controller/accesTokenController.py +++ b/geruecht/controller/accesTokenController.py @@ -99,7 +99,7 @@ class AccesTokenController(Thread, metaclass=Singleton): """ print("controll if", accToken, "hase group", group) LOGGER.debug("Check if AccessToken {} has group {}".format(accToken, group)) - return True if accToken.user.group == group else False + return True if group in accToken.user.group else False def run(self): """ Starting Controll-Thread diff --git a/geruecht/controller/databaseController.py b/geruecht/controller/databaseController.py index 10fbb6d..20f5a89 100644 --- a/geruecht/controller/databaseController.py +++ b/geruecht/controller/databaseController.py @@ -53,13 +53,21 @@ class DatabaseController(metaclass=Singleton): return retVal + def _convertGroupToString(self, groups): + retVal = '' + for group in groups: + if len(retVal) != 0: + retVal += ',' + retVal += group + return retVal def insertUser(self, data): self.connect() cursor = self.db.cursor() + groups = self._convertGroupToString(data['group']) try: cursor.execute("insert into user (cn, dn, firstname, lastname, gruppe) VALUES ('{}','{}','{}','{}','{}')".format( - data['cn'], data['dn'], data['givenName'], data['sn'], data['group'])) + data['cn'], data['dn'], data['givenName'], data['sn'], groups)) self.db.commit() except Exception as err: self.db.rollback() @@ -70,14 +78,17 @@ class DatabaseController(metaclass=Singleton): def updateUser(self, data): self.connect() cursor = self.db.cursor() + groups = self._convertGroupToString(data['group']) try: cursor.execute("update user set dn='{}', firstname='{}', lastname='{}', gruppe='{}' where cn='{}'".format( - data['dn'], data['givenName'], data['sn'], data['group'], data['cn'])) + data['dn'], data['givenName'], data['sn'], groups, data['cn'])) self.db.commit() except Exception as err: self.db.rollback() self.db.close() + print(err.__traceback__) raise err + self.db.close() def getCreditListFromUser(self, user, **kwargs): @@ -104,6 +115,7 @@ class DatabaseController(metaclass=Singleton): 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.close() @@ -115,6 +127,7 @@ class DatabaseController(metaclass=Singleton): 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, @@ -131,7 +144,10 @@ class DatabaseController(metaclass=Singleton): 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() diff --git a/geruecht/controller/ldapController.py b/geruecht/controller/ldapController.py index dbd5a40..a07b3aa 100644 --- a/geruecht/controller/ldapController.py +++ b/geruecht/controller/ldapController.py @@ -37,18 +37,28 @@ class LDAPController(metaclass=Singleton): def getGroup(self, username): + retVal = [] self.connect() + main_group_data = self.client.search_s('ou=user,{}'.format(self.dn), ldap.SCOPE_SUBTREE, 'cn={}'.format(username), ['gidNumber']) + if main_group_data: + main_group_number = main_group_data[0][1]['gidNumber'][0].decode('utf-8') + group_data = self.client.search_s('ou=group,{}'.format(self.dn), ldap.SCOPE_SUBTREE, 'gidNumber={}'.format(main_group_number), ['cn']) + if group_data: + group_name = group_data[0][1]['cn'][0].decode('utf-8') + if group_name == 'ldap-user': + retVal.append(USER) + groups_data = self.client.search_s('ou=group,{}'.format(self.dn), ldap.SCOPE_SUBTREE, 'memberUID={}'.format(username), ['cn']) - if len(groups_data) == 0: - return USER - else: - data = groups_data[0][1]['cn'][0].decode('utf-8') - if data == 'finanzer': - return MONEY - elif data == 'gastro': - return GASTRO - elif data == 'bar': - return BAR + for data in groups_data: + print(data[1]['cn'][0].decode('utf-8')) + group_name = data[1]['cn'][0].decode('utf-8') + if group_name == 'finanzer': + retVal.append(MONEY) + elif group_name == 'gastro': + retVal.append(GASTRO) + elif group_name == 'bar': + retVal.append(BAR) + return retVal if __name__ == '__main__': diff --git a/geruecht/finanzer/routes.py b/geruecht/finanzer/routes.py index bf2c5c2..f1178cd 100644 --- a/geruecht/finanzer/routes.py +++ b/geruecht/finanzer/routes.py @@ -3,7 +3,6 @@ from geruecht.finanzer import LOGGER from datetime import datetime from geruecht import MONEY, db from geruecht.routes import verifyAccessToken -from geruecht.model.user import User finanzer = Blueprint("finanzer", __name__) diff --git a/geruecht/model/user.py b/geruecht/model/user.py index d549732..cec7dcc 100644 --- a/geruecht/model/user.py +++ b/geruecht/model/user.py @@ -27,6 +27,11 @@ class User(): self.firstname = data['firstname'] self.lastname = data['lastname'] self.group = data['gruppe'] + if type(data['gruppe']) == list: + self.group = data['gruppe'] + elif type(data['gruppe']) == str: + self.group = data['gruppe'].split(',') + self.db = geruecht.getDatabesController() self.ldap = geruecht.getLDAPController() self.geruechte = [] @@ -52,8 +57,8 @@ class User(): """ LOGGER.debug("Create Geruecht for user {} in year {}".format(self, year)) data = create_empty_data() - data['user_id'] = self.id, - data['last_schulden'] = amount, + data['user_id'] = self.id + data['last_schulden'] = amount data['year_date'] = year credit = CreditList(data) self.geruechte.append(credit) @@ -85,7 +90,7 @@ class User(): self.updateGeruecht() - return geruecht + return self.getGeruecht(year=year) def addAmount(self, amount, year=datetime.now().year, month=datetime.now().month): """ Add Amount @@ -171,11 +176,13 @@ class User(): A Dic with static Attributes. """ dic = { + "userId": self.cn, "cn": self.cn, "dn": self.dn, "firstname": self.firstname, "lastname": self.lastname, "group": self.group, + "username": self.cn } return dic diff --git a/geruecht/routes.py b/geruecht/routes.py index 6aa742f..349d575 100644 --- a/geruecht/routes.py +++ b/geruecht/routes.py @@ -59,6 +59,7 @@ def _login(): """ LOGGER.info("Start log in.") data = request.get_json() + print(data) LOGGER.debug("JSON from request: {}".format(data)) username = data['username'] password = data['password'] @@ -69,15 +70,15 @@ def _login(): try: ldap.login(username, password) LOGGER.info("Authentification successfull. Search Group") - group = ldap.getGroup(username) + groups = ldap.getGroup(username) LOGGER.info("Get userdata from LDAP") user_data = ldap.getUserData(username) - user_data['group'] = group + user_data['group'] = groups LOGGER.info('Insert user {} into database') db.insertUser(user_data) except Exception as err: - raise err + return jsonify({"error": str(err)}), 401 LOGGER.info("{} try to log in".format(username)) user = db.getUser(username) LOGGER.debug("User is {}".format(user)) @@ -87,6 +88,7 @@ def _login(): token = accesTokenController.createAccesToken(user) dic = user.toJSON() dic["token"] = token + dic["accessToken"] = token LOGGER.info("User {} success login.".format(username)) return jsonify(dic) else: