fixed #79 and other bugs

This commit is contained in:
Tim Gröger 2019-12-22 22:27:39 +01:00
parent c6508fd516
commit 23db38690e
8 changed files with 70 additions and 31 deletions

View File

@ -82,9 +82,9 @@ accesTokenController.start()
from geruecht import routes from geruecht import routes
#from geruecht.baruser.routes import baruser from geruecht.baruser.routes import baruser
from geruecht.finanzer.routes import finanzer from geruecht.finanzer.routes import finanzer
LOGGER.info("Registrate bluebrints") LOGGER.info("Registrate bluebrints")
#app.register_blueprint(baruser) app.register_blueprint(baruser)
app.register_blueprint(finanzer) app.register_blueprint(finanzer)

View File

@ -23,18 +23,23 @@ def _bar():
dic = {} dic = {}
if accToken is not None: if accToken is not None:
users = User.query.all() users = db.getAllUser()
for user in users: for user in users:
geruecht = None geruecht = None
geruecht = user.getGeruecht() geruecht = user.getGeruecht()
if geruecht is not None: if geruecht is not None:
month = geruecht.getMonth(datetime.now().month) month = geruecht.getMonth(datetime.now().month)
amount = abs(month[0] - month[1]) amount = month[0] - month[1]
if amount != 0: 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, "firstname": user.firstname,
"lastname": user.lastname, "lastname": user.lastname,
"amount": abs(month[0] - month[1]) "amount": abs(month[0] - month[1]),
"type": type
} }
return jsonify(dic) return jsonify(dic)
return jsonify({"error": "permission denied"}), 401 return jsonify({"error": "permission denied"}), 401
@ -58,12 +63,12 @@ def _baradd():
userID = data['userId'] userID = data['userId']
amount = int(data['amount']) amount = int(data['amount'])
user = User.query.filter_by(userID=userID).first() user = db.getUser(userID)
month = user.addAmount(amount) month = user.addAmount(amount)
amount = abs(month[0] - month[1]) 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 return jsonify({"error", "permission denied"}), 401
@baruser.route("/barGetUsers") @baruser.route("/barGetUsers")
@ -82,11 +87,11 @@ def _getUsers():
retVal = {} retVal = {}
if accToken is not None: if accToken is not None:
users = User.query.all() users = db.getAllUser()
for user in users: for user in users:
month = user.getGeruecht().getMonth() month = user.getGeruecht().getMonth()
if month == 0: if month == 0:
retVal[user.userID] = {user.toJSON()} retVal[user.cn] = {user.toJSON()}
return jsonify(retVal) return jsonify(retVal)
return jsonify({"error": "permission denied"}), 401 return jsonify({"error": "permission denied"}), 401
@ -108,7 +113,7 @@ def _getUser():
data = request.get_json() data = request.get_json()
userID = data['userId'] userID = data['userId']
user = User.query.filter_by(userID=userID) user = db.getUser(userID)
month = user.getGeruecht().getMonth() month = user.getGeruecht().getMonth()
return jsonify({"userId": user.userID, "amount": month[1], "credit": month[0]}) return jsonify({"userId": user.userID, "amount": month[1], "credit": month[0]})

View File

@ -99,7 +99,7 @@ class AccesTokenController(Thread, metaclass=Singleton):
""" """
print("controll if", accToken, "hase group", group) print("controll if", accToken, "hase group", group)
LOGGER.debug("Check if AccessToken {} has group {}".format(accToken, 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): def run(self):
""" Starting Controll-Thread """ Starting Controll-Thread

View File

@ -53,13 +53,21 @@ class DatabaseController(metaclass=Singleton):
return retVal return retVal
def _convertGroupToString(self, groups):
retVal = ''
for group in groups:
if len(retVal) != 0:
retVal += ','
retVal += group
return retVal
def insertUser(self, data): def insertUser(self, data):
self.connect() self.connect()
cursor = self.db.cursor() cursor = self.db.cursor()
groups = self._convertGroupToString(data['group'])
try: try:
cursor.execute("insert into user (cn, dn, firstname, lastname, gruppe) VALUES ('{}','{}','{}','{}','{}')".format( 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() self.db.commit()
except Exception as err: except Exception as err:
self.db.rollback() self.db.rollback()
@ -70,14 +78,17 @@ class DatabaseController(metaclass=Singleton):
def updateUser(self, data): def updateUser(self, data):
self.connect() self.connect()
cursor = self.db.cursor() cursor = self.db.cursor()
groups = self._convertGroupToString(data['group'])
try: try:
cursor.execute("update user set dn='{}', firstname='{}', lastname='{}', gruppe='{}' where cn='{}'".format( 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() self.db.commit()
except Exception as err: except Exception as err:
self.db.rollback() self.db.rollback()
self.db.close() self.db.close()
print(err.__traceback__)
raise err raise err
self.db.close() self.db.close()
def getCreditListFromUser(self, user, **kwargs): def getCreditListFromUser(self, user, **kwargs):
@ -104,6 +115,7 @@ class DatabaseController(metaclass=Singleton):
cursor = self.db.cursor() cursor = self.db.cursor()
try: try:
cursor.execute("insert into creditList (year_date, user_id) values ({},{})".format(year, user_id)) cursor.execute("insert into creditList (year_date, user_id) values ({},{})".format(year, user_id))
self.db.commit()
self.db.close() self.db.close()
except Exception as err: except Exception as err:
self.db.close() self.db.close()
@ -115,6 +127,7 @@ class DatabaseController(metaclass=Singleton):
try: try:
cursor.execute("select * from creditList where user_id={} and year_date={}".format(creditlist.user_id, creditlist.year)) cursor.execute("select * from creditList where user_id={} and year_date={}".format(creditlist.user_id, creditlist.year))
data = cursor.fetchall() data = cursor.fetchall()
self.db.close()
if len(data) == 0: if len(data) == 0:
self.createCreditList(creditlist.user_id, creditlist.year) 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, 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.dez_guthaben, creditlist.dez_schulden,
creditlist.last_schulden, creditlist.year, creditlist.user_id) creditlist.last_schulden, creditlist.year, creditlist.user_id)
print(sql) print(sql)
self.connect()
cursor = self.db.cursor()
cursor.execute(sql) cursor.execute(sql)
self.db.commit()
self.db.close() self.db.close()
except Exception as err: except Exception as err:
self.db.rollback() self.db.rollback()

View File

@ -37,18 +37,28 @@ class LDAPController(metaclass=Singleton):
def getGroup(self, username): def getGroup(self, username):
retVal = []
self.connect() 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']) groups_data = self.client.search_s('ou=group,{}'.format(self.dn), ldap.SCOPE_SUBTREE, 'memberUID={}'.format(username), ['cn'])
if len(groups_data) == 0: for data in groups_data:
return USER print(data[1]['cn'][0].decode('utf-8'))
else: group_name = data[1]['cn'][0].decode('utf-8')
data = groups_data[0][1]['cn'][0].decode('utf-8') if group_name == 'finanzer':
if data == 'finanzer': retVal.append(MONEY)
return MONEY elif group_name == 'gastro':
elif data == 'gastro': retVal.append(GASTRO)
return GASTRO elif group_name == 'bar':
elif data == 'bar': retVal.append(BAR)
return BAR return retVal
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -3,7 +3,6 @@ from geruecht.finanzer import LOGGER
from datetime import datetime from datetime import datetime
from geruecht import MONEY, db from geruecht import MONEY, db
from geruecht.routes import verifyAccessToken from geruecht.routes import verifyAccessToken
from geruecht.model.user import User
finanzer = Blueprint("finanzer", __name__) finanzer = Blueprint("finanzer", __name__)

View File

@ -27,6 +27,11 @@ class User():
self.firstname = data['firstname'] self.firstname = data['firstname']
self.lastname = data['lastname'] self.lastname = data['lastname']
self.group = data['gruppe'] 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.db = geruecht.getDatabesController()
self.ldap = geruecht.getLDAPController() self.ldap = geruecht.getLDAPController()
self.geruechte = [] self.geruechte = []
@ -52,8 +57,8 @@ class User():
""" """
LOGGER.debug("Create Geruecht for user {} in year {}".format(self, year)) LOGGER.debug("Create Geruecht for user {} in year {}".format(self, year))
data = create_empty_data() data = create_empty_data()
data['user_id'] = self.id, data['user_id'] = self.id
data['last_schulden'] = amount, data['last_schulden'] = amount
data['year_date'] = year data['year_date'] = year
credit = CreditList(data) credit = CreditList(data)
self.geruechte.append(credit) self.geruechte.append(credit)
@ -85,7 +90,7 @@ class User():
self.updateGeruecht() self.updateGeruecht()
return geruecht return self.getGeruecht(year=year)
def addAmount(self, amount, year=datetime.now().year, month=datetime.now().month): def addAmount(self, amount, year=datetime.now().year, month=datetime.now().month):
""" Add Amount """ Add Amount
@ -171,11 +176,13 @@ class User():
A Dic with static Attributes. A Dic with static Attributes.
""" """
dic = { dic = {
"userId": self.cn,
"cn": self.cn, "cn": self.cn,
"dn": self.dn, "dn": self.dn,
"firstname": self.firstname, "firstname": self.firstname,
"lastname": self.lastname, "lastname": self.lastname,
"group": self.group, "group": self.group,
"username": self.cn
} }
return dic return dic

View File

@ -59,6 +59,7 @@ def _login():
""" """
LOGGER.info("Start log in.") LOGGER.info("Start log in.")
data = request.get_json() data = request.get_json()
print(data)
LOGGER.debug("JSON from request: {}".format(data)) LOGGER.debug("JSON from request: {}".format(data))
username = data['username'] username = data['username']
password = data['password'] password = data['password']
@ -69,15 +70,15 @@ def _login():
try: try:
ldap.login(username, password) ldap.login(username, password)
LOGGER.info("Authentification successfull. Search Group") LOGGER.info("Authentification successfull. Search Group")
group = ldap.getGroup(username) groups = ldap.getGroup(username)
LOGGER.info("Get userdata from LDAP") LOGGER.info("Get userdata from LDAP")
user_data = ldap.getUserData(username) user_data = ldap.getUserData(username)
user_data['group'] = group user_data['group'] = groups
LOGGER.info('Insert user {} into database') LOGGER.info('Insert user {} into database')
db.insertUser(user_data) db.insertUser(user_data)
except Exception as err: except Exception as err:
raise err return jsonify({"error": str(err)}), 401
LOGGER.info("{} try to log in".format(username)) LOGGER.info("{} try to log in".format(username))
user = db.getUser(username) user = db.getUser(username)
LOGGER.debug("User is {}".format(user)) LOGGER.debug("User is {}".format(user))
@ -87,6 +88,7 @@ def _login():
token = accesTokenController.createAccesToken(user) token = accesTokenController.createAccesToken(user)
dic = user.toJSON() dic = user.toJSON()
dic["token"] = token dic["token"] = token
dic["accessToken"] = token
LOGGER.info("User {} success login.".format(username)) LOGGER.info("User {} success login.".format(username))
return jsonify(dic) return jsonify(dic)
else: else: