Merge branch 'feature/ldap' of 192.168.5.2:newgeruecht into feature/ldap

 Conflicts:
	geruecht/baruser/routes.py
This commit is contained in:
Tim Gröger 2019-12-22 23:12:31 +01:00
commit 19ff9db9df
8 changed files with 70 additions and 31 deletions

View File

@ -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)

View File

@ -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,20 +87,20 @@ 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
@baruser.route("/search", methods=['POST'])
def _search():
token = request.headers.get("Token")
print(token)
accToken = verifyAccessToken(token, BAR)
if accToken is not None:
data = request.get_json()

View File

@ -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

View File

@ -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()

View File

@ -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
def __isUserInList(self, list, username):
help_list = []

View File

@ -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__)

View File

@ -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

View File

@ -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: