update for UnitTests
new controller: userController so routes don't have to import users or creditlist and don't do logics.
This commit is contained in:
parent
5b37e3d15b
commit
6ee6c1d44a
|
@ -4,74 +4,18 @@
|
||||||
Initialize also a singelton for the AccesTokenControler and start the Thread.
|
Initialize also a singelton for the AccesTokenControler and start the Thread.
|
||||||
|
|
||||||
"""
|
"""
|
||||||
import logging
|
from .logger import getLogger
|
||||||
from logging.handlers import WatchedFileHandler
|
|
||||||
import sys
|
|
||||||
|
|
||||||
MONEY = "moneymaster"
|
|
||||||
GASTRO = "gastro"
|
|
||||||
USER = "user"
|
|
||||||
BAR = "bar"
|
|
||||||
|
|
||||||
FORMATTER = logging.Formatter("%(asctime)s — %(name)s — %(levelname)s — %(message)s")
|
|
||||||
|
|
||||||
logFileHandler = WatchedFileHandler("testlog.log")
|
|
||||||
logFileHandler.setFormatter(FORMATTER)
|
|
||||||
|
|
||||||
logStreamHandler = logging.StreamHandler(stream=sys.stdout)
|
|
||||||
logStreamHandler.setFormatter(FORMATTER)
|
|
||||||
|
|
||||||
def getLogger(logger_name):
|
|
||||||
logger = logging.getLogger(logger_name)
|
|
||||||
logger.setLevel(logging.DEBUG)
|
|
||||||
logger.addHandler(logFileHandler)
|
|
||||||
logger.addHandler(logStreamHandler)
|
|
||||||
|
|
||||||
logger.propagate = False
|
|
||||||
|
|
||||||
return logger
|
|
||||||
|
|
||||||
LOGGER = getLogger(__name__)
|
LOGGER = getLogger(__name__)
|
||||||
LOGGER.info("Initialize App")
|
LOGGER.info("Initialize App")
|
||||||
|
|
||||||
class Singleton(type):
|
|
||||||
_instances = {}
|
|
||||||
def __call__(cls, *args, **kwargs):
|
|
||||||
if cls not in cls._instances:
|
|
||||||
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
|
|
||||||
return cls._instances[cls]
|
|
||||||
|
|
||||||
from .controller.databaseController import DatabaseController
|
|
||||||
db = DatabaseController()
|
|
||||||
from .controller.ldapController import LDAPController
|
|
||||||
ldapController = LDAPController()
|
|
||||||
|
|
||||||
def getDatabesController():
|
|
||||||
if db is not None:
|
|
||||||
return db
|
|
||||||
else:
|
|
||||||
return DatabaseController()
|
|
||||||
def getLDAPController():
|
|
||||||
if ldapController is not None:
|
|
||||||
return ldapController
|
|
||||||
else:
|
|
||||||
return LDAPController()
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
from flask import Flask
|
from flask import Flask
|
||||||
from flask_cors import CORS
|
from flask_cors import CORS
|
||||||
from .controller.accesTokenController import AccesTokenController
|
|
||||||
|
|
||||||
LOGGER.info("Build APP")
|
LOGGER.info("Build APP")
|
||||||
app = Flask(__name__)
|
app = Flask(__name__)
|
||||||
CORS(app)
|
CORS(app)
|
||||||
# app.config['SECRET_KEY'] = '0a657b97ef546da90b2db91862ad4e29'
|
# app.config['SECRET_KEY'] = '0a657b97ef546da90b2db91862ad4e29'
|
||||||
accesTokenController = AccesTokenController("GERUECHT")
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
from geruecht import routes
|
from geruecht import routes
|
||||||
from geruecht.baruser.routes import baruser
|
from geruecht.baruser.routes import baruser
|
||||||
|
|
|
@ -1,6 +1,7 @@
|
||||||
from flask import Blueprint, request, jsonify
|
from flask import Blueprint, request, jsonify
|
||||||
from geruecht import BAR, db, ldapController as ldap, accesTokenController
|
from geruecht.controller import ldapController as ldap, accesTokenController, userController
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
from geruecht.model import BAR
|
||||||
|
|
||||||
baruser = Blueprint("baruser", __name__)
|
baruser = Blueprint("baruser", __name__)
|
||||||
|
|
||||||
|
@ -21,10 +22,10 @@ def _bar():
|
||||||
|
|
||||||
dic = {}
|
dic = {}
|
||||||
if accToken:
|
if accToken:
|
||||||
users = db.getAllUser()
|
users = userController.getAllUsersfromDB()
|
||||||
for user in users:
|
for user in users:
|
||||||
geruecht = None
|
geruecht = None
|
||||||
geruecht = user.getGeruecht()
|
geruecht = user.getGeruecht(datetime.now().year)
|
||||||
if geruecht is not None:
|
if geruecht is not None:
|
||||||
month = geruecht.getMonth(datetime.now().month)
|
month = geruecht.getMonth(datetime.now().month)
|
||||||
amount = month[0] - month[1]
|
amount = month[0] - month[1]
|
||||||
|
@ -33,7 +34,7 @@ def _bar():
|
||||||
type = 'credit'
|
type = 'credit'
|
||||||
else:
|
else:
|
||||||
type = 'amount'
|
type = 'amount'
|
||||||
dic[user.cn] = {"username": user.cn,
|
dic[user.uid] = {"username": user.uid,
|
||||||
"firstname": user.firstname,
|
"firstname": user.firstname,
|
||||||
"lastname": user.lastname,
|
"lastname": user.lastname,
|
||||||
"amount": abs(month[0] - month[1]),
|
"amount": abs(month[0] - month[1]),
|
||||||
|
@ -61,18 +62,13 @@ def _baradd():
|
||||||
userID = data['userId']
|
userID = data['userId']
|
||||||
amount = int(data['amount'])
|
amount = int(data['amount'])
|
||||||
|
|
||||||
user = db.getUser(userID)
|
date = datetime.now()
|
||||||
if user is None:
|
userController.addAmount(userID, amount, year=date.year, month=date.month)
|
||||||
groups = ldap.getGroup(userID)
|
user = userController.getUser(userID)
|
||||||
user_data = ldap.getUserData(userID)
|
month = user.getGeruecht(year=date.year).getMonth(month=date.month)
|
||||||
user_data['group'] = groups
|
|
||||||
db.insertUser(user_data)
|
|
||||||
user = db.getUser(userID)
|
|
||||||
month = user.addAmount(amount)
|
|
||||||
|
|
||||||
amount = abs(month[0] - month[1])
|
amount = abs(month[0] - month[1])
|
||||||
|
|
||||||
return jsonify({"userId": user.cn, "amount": amount})
|
return jsonify({"userId": user.uid, "amount": amount})
|
||||||
return jsonify({"error", "permission denied"}), 401
|
return jsonify({"error", "permission denied"}), 401
|
||||||
|
|
||||||
@baruser.route("/barGetUsers")
|
@baruser.route("/barGetUsers")
|
||||||
|
|
|
@ -1,3 +1,30 @@
|
||||||
from geruecht import getLogger
|
from geruecht.logger import getLogger
|
||||||
|
|
||||||
LOGGER = getLogger(__name__)
|
LOGGER = getLogger(__name__)
|
||||||
|
|
||||||
|
class Singleton(type):
|
||||||
|
_instances = {}
|
||||||
|
def __call__(cls, *args, **kwargs):
|
||||||
|
if cls not in cls._instances:
|
||||||
|
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()
|
||||||
|
from .ldapController import LDAPController
|
||||||
|
def getLDAPController():
|
||||||
|
if ldapController is not None:
|
||||||
|
return ldapController
|
||||||
|
else:
|
||||||
|
return LDAPController()
|
||||||
|
from .accesTokenController import AccesTokenController
|
||||||
|
|
||||||
|
db = DatabaseController()
|
||||||
|
ldapController = LDAPController()
|
||||||
|
accesTokenController = AccesTokenController("GERUECHT")
|
||||||
|
from . userController import UserController
|
||||||
|
userController = UserController()
|
|
@ -2,9 +2,7 @@ from geruecht.model.accessToken import AccessToken
|
||||||
from geruecht.controller import LOGGER
|
from geruecht.controller import LOGGER
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
import hashlib
|
import hashlib
|
||||||
import logging
|
from . import Singleton
|
||||||
from logging.handlers import WatchedFileHandler
|
|
||||||
from geruecht import Singleton
|
|
||||||
|
|
||||||
class AccesTokenController(metaclass=Singleton):
|
class AccesTokenController(metaclass=Singleton):
|
||||||
""" Control all createt AccesToken
|
""" Control all createt AccesToken
|
||||||
|
@ -26,17 +24,6 @@ class AccesTokenController(metaclass=Singleton):
|
||||||
"""
|
"""
|
||||||
LOGGER.info("Initialize AccessTokenController")
|
LOGGER.info("Initialize AccessTokenController")
|
||||||
|
|
||||||
LOGGER.debug("Build Logger for VerificationThread")
|
|
||||||
|
|
||||||
FORMATTER = logging.Formatter("%(asctime)s — %(name)s — %(levelname)s — %(message)s")
|
|
||||||
|
|
||||||
logFileHandler = WatchedFileHandler("Verification.log")
|
|
||||||
logFileHandler.setFormatter(FORMATTER)
|
|
||||||
|
|
||||||
self.LOGGER = logging.getLogger("VerificationThread")
|
|
||||||
self.LOGGER.setLevel(logging.DEBUG)
|
|
||||||
self.LOGGER.addHandler(logFileHandler)
|
|
||||||
self.LOGGER.propagate = False
|
|
||||||
self.tokenList = []
|
self.tokenList = []
|
||||||
|
|
||||||
def validateAccessToken(self, token, group):
|
def validateAccessToken(self, token, group):
|
||||||
|
|
|
@ -1,5 +1,5 @@
|
||||||
import pymysql
|
import pymysql
|
||||||
from geruecht import Singleton
|
from . import Singleton
|
||||||
from geruecht.model.user import User
|
from geruecht.model.user import User
|
||||||
from geruecht.model.creditList import CreditList
|
from geruecht.model.creditList import CreditList
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
@ -36,20 +36,28 @@ class DatabaseController(metaclass=Singleton):
|
||||||
raise err
|
raise err
|
||||||
|
|
||||||
if data:
|
if data:
|
||||||
return [User(value) for value in data]
|
retVal = []
|
||||||
|
for value in data:
|
||||||
|
user = User(value)
|
||||||
|
creditLists = self.getCreditListFromUser(user)
|
||||||
|
user.initGeruechte(creditLists)
|
||||||
|
retVal.append(user)
|
||||||
|
return retVal
|
||||||
|
|
||||||
def getUser(self, username):
|
def getUser(self, username):
|
||||||
self.connect()
|
self.connect()
|
||||||
retVal = None
|
retVal = None
|
||||||
cursor = self.db.cursor()
|
cursor = self.db.cursor()
|
||||||
try:
|
try:
|
||||||
cursor.execute("select * from user where cn='{}'".format(username))
|
cursor.execute("select * from user where uid='{}'".format(username))
|
||||||
data = cursor.fetchone()
|
data = cursor.fetchone()
|
||||||
self.db.close()
|
self.db.close()
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
raise err
|
raise err
|
||||||
if data:
|
if data:
|
||||||
retVal = User(data)
|
retVal = User(data)
|
||||||
|
creditLists = self.getCreditListFromUser(retVal)
|
||||||
|
retVal.initGeruechte(creditLists)
|
||||||
|
|
||||||
return retVal
|
return retVal
|
||||||
|
|
||||||
|
@ -66,8 +74,8 @@ class DatabaseController(metaclass=Singleton):
|
||||||
cursor = self.db.cursor()
|
cursor = self.db.cursor()
|
||||||
groups = self._convertGroupToString(data['group'])
|
groups = self._convertGroupToString(data['group'])
|
||||||
try:
|
try:
|
||||||
cursor.execute("insert into user (cn, dn, firstname, lastname, gruppe) VALUES ('{}','{}','{}','{}','{}')".format(
|
cursor.execute("insert into user (uid, dn, firstname, lastname, gruppe) VALUES ('{}','{}','{}','{}','{}')".format(
|
||||||
data['cn'], data['dn'], data['givenName'], data['sn'], groups))
|
data['uid'], 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()
|
||||||
|
@ -80,8 +88,8 @@ class DatabaseController(metaclass=Singleton):
|
||||||
cursor = self.db.cursor()
|
cursor = self.db.cursor()
|
||||||
groups = self._convertGroupToString(data['group'])
|
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 uid='{}'".format(
|
||||||
data['dn'], data['givenName'], data['sn'], groups, data['cn']))
|
data['dn'], data['givenName'], data['sn'], groups, data['uid']))
|
||||||
self.db.commit()
|
self.db.commit()
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
self.db.rollback()
|
self.db.rollback()
|
||||||
|
|
|
@ -1,5 +1,7 @@
|
||||||
import ldap
|
import ldap
|
||||||
from geruecht import MONEY, USER, GASTRO, BAR, Singleton
|
from geruecht.model import MONEY, USER, GASTRO, BAR
|
||||||
|
from geruecht.exceptions import PermissionDenied
|
||||||
|
from . import Singleton
|
||||||
|
|
||||||
class LDAPController(metaclass=Singleton):
|
class LDAPController(metaclass=Singleton):
|
||||||
'''
|
'''
|
||||||
|
@ -20,15 +22,16 @@ class LDAPController(metaclass=Singleton):
|
||||||
def login(self, username, password):
|
def login(self, username, password):
|
||||||
self.connect()
|
self.connect()
|
||||||
try:
|
try:
|
||||||
self.client.bind_s("cn={},ou=user,{}".format(username, self.dn), password)
|
cn = self.client.search_s("ou=user,{}".format(self.dn), ldap.SCOPE_SUBTREE, 'uid={}'.format(username),['cn'])[0][1]['cn'][0].decode('utf-8')
|
||||||
|
self.client.bind_s("cn={},ou=user,{}".format(cn, self.dn), password)
|
||||||
self.client.unbind_s()
|
self.client.unbind_s()
|
||||||
except:
|
except:
|
||||||
self.client.unbind_s()
|
self.client.unbind_s()
|
||||||
raise Exception("Invalid Password or Username")
|
raise PermissionDenied("Invalid Password or Username")
|
||||||
|
|
||||||
def getUserData(self, username):
|
def getUserData(self, username):
|
||||||
self.connect()
|
self.connect()
|
||||||
search_data = self.client.search_s('ou=user,{}'.format(self.dn), ldap.SCOPE_SUBTREE, 'cn={}'.format(username), ['cn', 'givenName', 'sn'])
|
search_data = self.client.search_s('ou=user,{}'.format(self.dn), ldap.SCOPE_SUBTREE, 'uid={}'.format(username), ['uid', 'givenName', 'sn'])
|
||||||
retVal = search_data[0][1]
|
retVal = search_data[0][1]
|
||||||
for k,v in retVal.items():
|
for k,v in retVal.items():
|
||||||
retVal[k] = v[0].decode('utf-8')
|
retVal[k] = v[0].decode('utf-8')
|
||||||
|
@ -39,7 +42,7 @@ class LDAPController(metaclass=Singleton):
|
||||||
def getGroup(self, username):
|
def getGroup(self, username):
|
||||||
retVal = []
|
retVal = []
|
||||||
self.connect()
|
self.connect()
|
||||||
main_group_data = self.client.search_s('ou=user,{}'.format(self.dn), ldap.SCOPE_SUBTREE, 'cn={}'.format(username), ['gidNumber'])
|
main_group_data = self.client.search_s('ou=user,{}'.format(self.dn), ldap.SCOPE_SUBTREE, 'uid={}'.format(username), ['gidNumber'])
|
||||||
if main_group_data:
|
if main_group_data:
|
||||||
main_group_number = main_group_data[0][1]['gidNumber'][0].decode('utf-8')
|
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'])
|
group_data = self.client.search_s('ou=group,{}'.format(self.dn), ldap.SCOPE_SUBTREE, 'gidNumber={}'.format(main_group_number), ['cn'])
|
||||||
|
@ -71,10 +74,10 @@ class LDAPController(metaclass=Singleton):
|
||||||
def getAllUser(self):
|
def getAllUser(self):
|
||||||
self.connect()
|
self.connect()
|
||||||
retVal = []
|
retVal = []
|
||||||
data = self.client.search_s('ou=user,{}'.format(self.dn), ldap.SCOPE_SUBTREE, attrlist=['cn', 'givenName', 'sn'])
|
data = self.client.search_s('ou=user,{}'.format(self.dn), ldap.SCOPE_SUBTREE, attrlist=['uid', 'givenName', 'sn'])
|
||||||
for user in data:
|
for user in data:
|
||||||
if 'cn' in user[1]:
|
if 'uid' in user[1]:
|
||||||
username = user[1]['cn'][0].decode('utf-8')
|
username = user[1]['uid'][0].decode('utf-8')
|
||||||
firstname = user[1]['givenName'][0].decode('utf-8')
|
firstname = user[1]['givenName'][0].decode('utf-8')
|
||||||
lastname = user[1]['sn'][0].decode('utf-8')
|
lastname = user[1]['sn'][0].decode('utf-8')
|
||||||
retVal.append({'username': username, 'firstname': firstname, 'lastname': lastname})
|
retVal.append({'username': username, 'firstname': firstname, 'lastname': lastname})
|
||||||
|
@ -96,21 +99,21 @@ class LDAPController(metaclass=Singleton):
|
||||||
if len(name) == 1:
|
if len(name) == 1:
|
||||||
if name[0] == "**":
|
if name[0] == "**":
|
||||||
name_result.append(self.client.search_s('ou=user,{}'.format(self.dn), ldap.SCOPE_SUBTREE,
|
name_result.append(self.client.search_s('ou=user,{}'.format(self.dn), ldap.SCOPE_SUBTREE,
|
||||||
attrlist=['cn', 'givenName', 'sn']))
|
attrlist=['uid', 'givenName', 'sn']))
|
||||||
else:
|
else:
|
||||||
name_result.append(self.client.search_s('ou=user,{}'.format(self.dn), ldap.SCOPE_SUBTREE, 'givenName={}'.format(name[0]), ['cn', 'givenName', 'sn']))
|
name_result.append(self.client.search_s('ou=user,{}'.format(self.dn), ldap.SCOPE_SUBTREE, 'givenName={}'.format(name[0]), ['uid', 'givenName', 'sn']))
|
||||||
name_result.append(self.client.search_s('ou=user,{}'.format(self.dn), ldap.SCOPE_SUBTREE, 'sn={}'.format(name[0]),['cn', 'givenName', 'sn']))
|
name_result.append(self.client.search_s('ou=user,{}'.format(self.dn), ldap.SCOPE_SUBTREE, 'sn={}'.format(name[0]),['uid', 'givenName', 'sn']))
|
||||||
else:
|
else:
|
||||||
name_result.append(self.client.search_s('ou=user,{}'.format(self.dn), ldap.SCOPE_SUBTREE,
|
name_result.append(self.client.search_s('ou=user,{}'.format(self.dn), ldap.SCOPE_SUBTREE,
|
||||||
'givenName={}'.format(name[1]), ['cn', 'givenName', 'sn']))
|
'givenName={}'.format(name[1]), ['uid', 'givenName', 'sn']))
|
||||||
name_result.append(self.client.search_s('ou=user,{}'.format(self.dn), ldap.SCOPE_SUBTREE, 'sn={}'.format(name[1]),
|
name_result.append(self.client.search_s('ou=user,{}'.format(self.dn), ldap.SCOPE_SUBTREE, 'sn={}'.format(name[1]),
|
||||||
['cn', 'givenName', 'sn']))
|
['uid', 'givenName', 'sn']))
|
||||||
retVal = []
|
retVal = []
|
||||||
|
|
||||||
for names in name_result:
|
for names in name_result:
|
||||||
for user in names:
|
for user in names:
|
||||||
if 'cn' in user[1]:
|
if 'uid' in user[1]:
|
||||||
username = user[1]['cn'][0].decode('utf-8')
|
username = user[1]['uid'][0].decode('utf-8')
|
||||||
if not self.__isUserInList(retVal, username):
|
if not self.__isUserInList(retVal, username):
|
||||||
firstname = user[1]['givenName'][0].decode('utf-8')
|
firstname = user[1]['givenName'][0].decode('utf-8')
|
||||||
lastname = user[1]['sn'][0].decode('utf-8')
|
lastname = user[1]['sn'][0].decode('utf-8')
|
||||||
|
|
|
@ -0,0 +1,46 @@
|
||||||
|
from . import LOGGER, Singleton, db, ldapController as ldap
|
||||||
|
from geruecht.exceptions import PermissionDenied
|
||||||
|
|
||||||
|
class UserController(metaclass=Singleton):
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def addAmount(self, username, amount, year, month):
|
||||||
|
user = self.getUser(username)
|
||||||
|
user.addAmount(amount, year=year, month=month)
|
||||||
|
creditLists = user.updateGeruecht()
|
||||||
|
for creditList in creditLists:
|
||||||
|
db.updateCreditList(creditList)
|
||||||
|
return user.getGeruecht(year)
|
||||||
|
|
||||||
|
def addCredit(self, username, credit, year, month):
|
||||||
|
user = self.getUser(username)
|
||||||
|
user.addCredit(credit, year=year, month=month)
|
||||||
|
creditLists = user.updateGeruecht()
|
||||||
|
for creditList in creditLists:
|
||||||
|
db.updateCreditList(creditList)
|
||||||
|
return user.getGeruecht(year)
|
||||||
|
|
||||||
|
def getAllUsersfromDB(self):
|
||||||
|
return db.getAllUser()
|
||||||
|
|
||||||
|
def getUser(self, username):
|
||||||
|
user = db.getUser(username)
|
||||||
|
groups = ldap.getGroup(username)
|
||||||
|
user_data = ldap.getUserData(username)
|
||||||
|
user_data['group'] = groups
|
||||||
|
if user is None:
|
||||||
|
db.insertUser(user_data)
|
||||||
|
else:
|
||||||
|
db.updateUser(user_data)
|
||||||
|
user = db.getUser(username)
|
||||||
|
return user
|
||||||
|
|
||||||
|
def loginUser(self, username, password):
|
||||||
|
try:
|
||||||
|
user = self.getUser(username)
|
||||||
|
ldap.login(username, password)
|
||||||
|
return user
|
||||||
|
except PermissionDenied as err:
|
||||||
|
raise err
|
|
@ -0,0 +1,2 @@
|
||||||
|
class PermissionDenied(Exception):
|
||||||
|
pass
|
|
@ -1,7 +1,8 @@
|
||||||
from flask import Blueprint, request, jsonify
|
from flask import Blueprint, request, jsonify
|
||||||
from geruecht.finanzer import LOGGER
|
from geruecht.finanzer import LOGGER
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from geruecht import MONEY, db, accesTokenController
|
from geruecht.controller import accesTokenController, userController
|
||||||
|
from geruecht.model import MONEY
|
||||||
|
|
||||||
finanzer = Blueprint("finanzer", __name__)
|
finanzer = Blueprint("finanzer", __name__)
|
||||||
|
|
||||||
|
@ -22,53 +23,18 @@ def _getFinanzer():
|
||||||
accToken = accesTokenController.validateAccessToken(token, MONEY)
|
accToken = accesTokenController.validateAccessToken(token, MONEY)
|
||||||
if accToken:
|
if accToken:
|
||||||
LOGGER.debug("Get all Useres")
|
LOGGER.debug("Get all Useres")
|
||||||
users = db.getAllUser()
|
users = userController.getAllUsersfromDB()
|
||||||
dic = {}
|
dic = {}
|
||||||
for user in users:
|
for user in users:
|
||||||
LOGGER.debug("Add User {} to ReturnValue".format(user))
|
LOGGER.debug("Add User {} to ReturnValue".format(user))
|
||||||
dic[user.cn] = user.toJSON()
|
dic[user.uid] = user.toJSON()
|
||||||
creditList = db.getCreditListFromUser(user)
|
dic[user.uid]['creditList'] = {credit.year: credit.toJSON() for credit in user.geruechte}
|
||||||
dic[user.cn]['creditList'] = {credit.year: credit.toJSON() for credit in creditList}
|
|
||||||
LOGGER.debug("ReturnValue is {}".format(dic))
|
LOGGER.debug("ReturnValue is {}".format(dic))
|
||||||
LOGGER.info("Send main for Finanzer")
|
LOGGER.info("Send main for Finanzer")
|
||||||
return jsonify(dic)
|
return jsonify(dic)
|
||||||
LOGGER.info("Permission Denied")
|
LOGGER.info("Permission Denied")
|
||||||
return jsonify({"error": "permission denied"}), 401
|
return jsonify({"error": "permission denied"}), 401
|
||||||
|
|
||||||
@finanzer.route("/getFinanzerYears", methods=['POST'])
|
|
||||||
def _getFinanzerYear():
|
|
||||||
""" Get all geruechte from User
|
|
||||||
|
|
||||||
This function returns all geruechte from user with posted userID
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
JSON-File with geruechte of special user
|
|
||||||
or ERROR 401 Permission Denied
|
|
||||||
"""
|
|
||||||
LOGGER.info("Get all Geruechte from User.")
|
|
||||||
token = request.headers.get("Token")
|
|
||||||
LOGGER.debug("Verify AccessToken with Token {}".format(token))
|
|
||||||
accToken = accesTokenController.validateAccessToken(token, MONEY)
|
|
||||||
|
|
||||||
dic = {}
|
|
||||||
if accToken:
|
|
||||||
data = request.get_json()
|
|
||||||
LOGGER.debug("Get data {}".format(data))
|
|
||||||
userID = data['userId']
|
|
||||||
LOGGER.debug("UserID is {}".format(userID))
|
|
||||||
user = db.getUser(userID)
|
|
||||||
LOGGER.debug("User is {}".format(user))
|
|
||||||
dic[user.cn] = {}
|
|
||||||
LOGGER.debug("Build ReturnValue")
|
|
||||||
for geruecht in user.geruechte:
|
|
||||||
LOGGER.debug("Add Geruecht {} to ReturnValue".format(geruecht))
|
|
||||||
dic[user.cn][geruecht.year] = geruecht.toJSON()
|
|
||||||
LOGGER.debug("ReturnValue is {}".format(dic))
|
|
||||||
LOGGER.info("Send Geruechte from User {}".format(user))
|
|
||||||
return jsonify(dic)
|
|
||||||
LOGGER.info("Permission Denied")
|
|
||||||
return jsonify({"error": "permission denied"}), 401
|
|
||||||
|
|
||||||
@finanzer.route("/finanzerAddAmount", methods=['POST'])
|
@finanzer.route("/finanzerAddAmount", methods=['POST'])
|
||||||
def _addAmount():
|
def _addAmount():
|
||||||
""" Add Amount to User
|
""" Add Amount to User
|
||||||
|
@ -103,11 +69,7 @@ def _addAmount():
|
||||||
LOGGER.error("KeyError in month. Month is set to default.")
|
LOGGER.error("KeyError in month. Month is set to default.")
|
||||||
month = datetime.now().month
|
month = datetime.now().month
|
||||||
LOGGER.debug("Year is {} and Month is {}".format(year, month))
|
LOGGER.debug("Year is {} and Month is {}".format(year, month))
|
||||||
user = db.getUser(userID)
|
retVal = userController.addAmount(userID, amount, year=year, month=month).toJSON()
|
||||||
LOGGER.debug("User is {}".format(user))
|
|
||||||
LOGGER.debug("Add amount to User {} in year {} and month {}".format(user, year, month))
|
|
||||||
user.addAmount(amount, year=year, month=month)
|
|
||||||
retVal = user.getGeruecht(year=year).toJSON()
|
|
||||||
LOGGER.info("Send updated Geruecht")
|
LOGGER.info("Send updated Geruecht")
|
||||||
return jsonify(retVal)
|
return jsonify(retVal)
|
||||||
LOGGER.info("Permission Denied")
|
LOGGER.info("Permission Denied")
|
||||||
|
@ -151,11 +113,7 @@ def _addCredit():
|
||||||
month = datetime.now().month
|
month = datetime.now().month
|
||||||
|
|
||||||
LOGGER.debug("Year is {} and Month is {}".format(year, month))
|
LOGGER.debug("Year is {} and Month is {}".format(year, month))
|
||||||
user = db.getUser(userID)
|
retVal = userController.addCredit(userID, credit, year=year, month=month).toJSON()
|
||||||
LOGGER.debug("User is {}".format(user))
|
|
||||||
LOGGER.debug("Add credit to User {} in year {} and month {}".format(user, year, month))
|
|
||||||
user.addCredit(credit, year=year, month=month)
|
|
||||||
retVal = user.getGeruecht(year=year).toJSON()
|
|
||||||
LOGGER.info("Send updated Geruecht")
|
LOGGER.info("Send updated Geruecht")
|
||||||
return jsonify(retVal)
|
return jsonify(retVal)
|
||||||
LOGGER.info("Permission Denied")
|
LOGGER.info("Permission Denied")
|
||||||
|
|
|
@ -0,0 +1,21 @@
|
||||||
|
import logging
|
||||||
|
from logging.handlers import WatchedFileHandler
|
||||||
|
import sys
|
||||||
|
|
||||||
|
FORMATTER = logging.Formatter("%(asctime)s — %(name)s — %(levelname)s — %(message)s")
|
||||||
|
|
||||||
|
logFileHandler = WatchedFileHandler("testlog.log")
|
||||||
|
logFileHandler.setFormatter(FORMATTER)
|
||||||
|
|
||||||
|
logStreamHandler = logging.StreamHandler(stream=sys.stdout)
|
||||||
|
logStreamHandler.setFormatter(FORMATTER)
|
||||||
|
|
||||||
|
def getLogger(logger_name):
|
||||||
|
logger = logging.getLogger(logger_name)
|
||||||
|
logger.setLevel(logging.DEBUG)
|
||||||
|
logger.addHandler(logFileHandler)
|
||||||
|
logger.addHandler(logStreamHandler)
|
||||||
|
|
||||||
|
logger.propagate = False
|
||||||
|
|
||||||
|
return logger
|
|
@ -0,0 +1,4 @@
|
||||||
|
MONEY = "moneymaster"
|
||||||
|
GASTRO = "gastro"
|
||||||
|
USER = "user"
|
||||||
|
BAR = "bar"
|
|
@ -1,6 +1,5 @@
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from geruecht import getLogger
|
from geruecht import getLogger
|
||||||
import geruecht
|
|
||||||
|
|
||||||
LOGGER = getLogger(__name__)
|
LOGGER = getLogger(__name__)
|
||||||
def create_empty_data():
|
def create_empty_data():
|
||||||
|
@ -92,8 +91,6 @@ class CreditList():
|
||||||
|
|
||||||
self.user_id = int(data['user_id'])
|
self.user_id = int(data['user_id'])
|
||||||
|
|
||||||
self.db = geruecht.getDatabesController()
|
|
||||||
|
|
||||||
def getSchulden(self):
|
def getSchulden(self):
|
||||||
""" Get Schulden
|
""" Get Schulden
|
||||||
|
|
||||||
|
@ -217,9 +214,6 @@ class CreditList():
|
||||||
elif month == 12:
|
elif month == 12:
|
||||||
self.dez_schulden += amount
|
self.dez_schulden += amount
|
||||||
retValue = (self.dez_guthaben, self.dez_schulden)
|
retValue = (self.dez_guthaben, self.dez_schulden)
|
||||||
|
|
||||||
#db.session.commit()
|
|
||||||
self.db.updateCreditList(self)
|
|
||||||
LOGGER.debug("Credit and Amount is {}".format(retValue))
|
LOGGER.debug("Credit and Amount is {}".format(retValue))
|
||||||
return retValue
|
return retValue
|
||||||
|
|
||||||
|
@ -273,8 +267,6 @@ class CreditList():
|
||||||
elif month == 12:
|
elif month == 12:
|
||||||
self.dez_guthaben += credit
|
self.dez_guthaben += credit
|
||||||
retValue = (self.dez_guthaben, self.dez_schulden)
|
retValue = (self.dez_guthaben, self.dez_schulden)
|
||||||
self.db.updateCreditList(self)
|
|
||||||
#db.session.commit()
|
|
||||||
LOGGER.debug("Credit and Amount is {}".format(retValue))
|
LOGGER.debug("Credit and Amount is {}".format(retValue))
|
||||||
return retValue
|
return retValue
|
||||||
|
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
from geruecht import db
|
from geruecht.controller import db
|
||||||
|
|
||||||
class PriceList(db.Model):
|
class PriceList(db.Model):
|
||||||
""" Database Model for PriceList
|
""" Database Model for PriceList
|
||||||
|
|
|
@ -1,5 +1,4 @@
|
||||||
from geruecht import getLogger
|
from geruecht.logger import getLogger
|
||||||
import geruecht
|
|
||||||
from geruecht.model.creditList import CreditList, create_empty_data
|
from geruecht.model.creditList import CreditList, create_empty_data
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
|
@ -22,7 +21,7 @@ class User():
|
||||||
"""
|
"""
|
||||||
def __init__(self, data):
|
def __init__(self, data):
|
||||||
self.id = int(data['id'])
|
self.id = int(data['id'])
|
||||||
self.cn = data['cn']
|
self.uid = data['uid']
|
||||||
self.dn = data['dn']
|
self.dn = data['dn']
|
||||||
self.firstname = data['firstname']
|
self.firstname = data['firstname']
|
||||||
self.lastname = data['lastname']
|
self.lastname = data['lastname']
|
||||||
|
@ -31,17 +30,12 @@ class User():
|
||||||
self.group = data['gruppe']
|
self.group = data['gruppe']
|
||||||
elif type(data['gruppe']) == str:
|
elif type(data['gruppe']) == str:
|
||||||
self.group = data['gruppe'].split(',')
|
self.group = data['gruppe'].split(',')
|
||||||
|
if 'creditLists' in data:
|
||||||
|
self.geruechte = data['creditLists']
|
||||||
|
|
||||||
self.db = geruecht.getDatabesController()
|
def initGeruechte(self, creditLists):
|
||||||
self.ldap = geruecht.getLDAPController()
|
if type(creditLists) == list:
|
||||||
self.geruechte = []
|
self.geruechte = creditLists
|
||||||
geruechte = self.db.getCreditListFromUser(self)
|
|
||||||
if type(geruechte) == list:
|
|
||||||
self.geruechte = geruechte
|
|
||||||
elif type(geruechte) == CreditList:
|
|
||||||
self.geruechte.append(geruechte)
|
|
||||||
self.updateGeruecht()
|
|
||||||
#geruechte = db.relationship('CreditList', backref='user', lazy=True)
|
|
||||||
|
|
||||||
def createGeruecht(self, amount=0, year=datetime.now().year):
|
def createGeruecht(self, amount=0, year=datetime.now().year):
|
||||||
""" Create Geruecht
|
""" Create Geruecht
|
||||||
|
@ -63,8 +57,6 @@ class User():
|
||||||
data['year_date'] = year
|
data['year_date'] = year
|
||||||
credit = CreditList(data)
|
credit = CreditList(data)
|
||||||
self.geruechte.append(credit)
|
self.geruechte.append(credit)
|
||||||
self.db.updateCreditList(credit)
|
|
||||||
credit = self.db.getCreditListFromUser(self, year=year)
|
|
||||||
LOGGER.debug("Created Geruecht {}".format(credit))
|
LOGGER.debug("Created Geruecht {}".format(credit))
|
||||||
return credit
|
return credit
|
||||||
|
|
||||||
|
@ -89,8 +81,6 @@ class User():
|
||||||
LOGGER.debug("No Geruecht found for User {}. Will create one".format(self))
|
LOGGER.debug("No Geruecht found for User {}. Will create one".format(self))
|
||||||
geruecht = self.createGeruecht(year=year)
|
geruecht = self.createGeruecht(year=year)
|
||||||
|
|
||||||
self.updateGeruecht()
|
|
||||||
|
|
||||||
return self.getGeruecht(year=year)
|
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):
|
||||||
|
@ -111,10 +101,6 @@ class User():
|
||||||
geruecht = self.getGeruecht(year=year)
|
geruecht = self.getGeruecht(year=year)
|
||||||
retVal = geruecht.addAmount(amount, month=month)
|
retVal = geruecht.addAmount(amount, month=month)
|
||||||
|
|
||||||
self.db.updateCreditList(geruecht)
|
|
||||||
|
|
||||||
self.updateGeruecht()
|
|
||||||
|
|
||||||
return retVal
|
return retVal
|
||||||
|
|
||||||
def addCredit(self, credit, year=datetime.now().year, month=datetime.now().month):
|
def addCredit(self, credit, year=datetime.now().year, month=datetime.now().month):
|
||||||
|
@ -135,10 +121,6 @@ class User():
|
||||||
geruecht = self.getGeruecht(year=year)
|
geruecht = self.getGeruecht(year=year)
|
||||||
retVal = geruecht.addCredit(credit, month=month)
|
retVal = geruecht.addCredit(credit, month=month)
|
||||||
|
|
||||||
self.db.updateCreditList(geruecht)
|
|
||||||
|
|
||||||
self.updateGeruecht()
|
|
||||||
|
|
||||||
return retVal
|
return retVal
|
||||||
|
|
||||||
def updateGeruecht(self):
|
def updateGeruecht(self):
|
||||||
|
@ -154,7 +136,8 @@ class User():
|
||||||
geruecht.last_schulden = 0
|
geruecht.last_schulden = 0
|
||||||
if index != 0:
|
if index != 0:
|
||||||
geruecht.last_schulden = (self.geruechte[index - 1].getSchulden() * -1)
|
geruecht.last_schulden = (self.geruechte[index - 1].getSchulden() * -1)
|
||||||
self.db.updateCreditList(geruecht)
|
|
||||||
|
return self.geruechte
|
||||||
|
|
||||||
def sortYear(self, geruecht):
|
def sortYear(self, geruecht):
|
||||||
""" Sort Year
|
""" Sort Year
|
||||||
|
@ -177,38 +160,16 @@ class User():
|
||||||
A Dic with static Attributes.
|
A Dic with static Attributes.
|
||||||
"""
|
"""
|
||||||
dic = {
|
dic = {
|
||||||
"userId": self.cn,
|
"userId": self.uid,
|
||||||
"cn": self.cn,
|
"uid": self.uid,
|
||||||
"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
|
"username": self.uid
|
||||||
}
|
}
|
||||||
return dic
|
return dic
|
||||||
|
|
||||||
def updateUser(self):
|
|
||||||
data = self.ldap.getUserData(self.cn)
|
|
||||||
data['group'] = self.ldap.getGroup(self.cn)
|
|
||||||
self.db.updateUser(data)
|
|
||||||
|
|
||||||
def login(self, password):
|
|
||||||
""" Login for the User
|
|
||||||
|
|
||||||
Only check the given Password:
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
A Bool. True if the password is correct and False if it isn't.
|
|
||||||
"""
|
|
||||||
LOGGER.debug("Login User {}".format(self))
|
|
||||||
try:
|
|
||||||
self.ldap.login(self.cn, password)
|
|
||||||
|
|
||||||
self.updateUser()
|
|
||||||
return True
|
|
||||||
except:
|
|
||||||
return False
|
|
||||||
|
|
||||||
def __repr__(self):
|
def __repr__(self):
|
||||||
return "User({}, {}, {})".format(self.cn, self.dn, self.group)
|
return "User({}, {}, {})".format(self.uid, self.dn, self.group)
|
||||||
|
|
||||||
|
|
|
@ -1,8 +1,10 @@
|
||||||
from geruecht import app, db, accesTokenController, MONEY, BAR, USER, GASTRO, LOGGER
|
from geruecht import app, LOGGER
|
||||||
from geruecht import ldapController as ldap
|
from geruecht.exceptions import PermissionDenied
|
||||||
from geruecht.model.user import User
|
from geruecht.controller import accesTokenController, userController
|
||||||
|
from geruecht.model import MONEY, BAR, USER, GASTRO
|
||||||
from flask import request, jsonify
|
from flask import request, jsonify
|
||||||
|
|
||||||
|
|
||||||
def login(user, password):
|
def login(user, password):
|
||||||
return user.login(password)
|
return user.login(password)
|
||||||
|
|
||||||
|
@ -40,35 +42,15 @@ def _login():
|
||||||
username = data['username']
|
username = data['username']
|
||||||
password = data['password']
|
password = data['password']
|
||||||
LOGGER.info("search {} in database".format(username))
|
LOGGER.info("search {} in database".format(username))
|
||||||
user = db.getUser(username)
|
try:
|
||||||
if user is None:
|
user = userController.loginUser(username, password)
|
||||||
LOGGER.info("User {} not found. Authenticate over LDAP and create User.")
|
token = accesTokenController.createAccesToken(user)
|
||||||
try:
|
dic = user.toJSON()
|
||||||
ldap.login(username, password)
|
dic["token"] = token
|
||||||
LOGGER.info("Authentification successfull. Search Group")
|
dic["accessToken"] = token
|
||||||
groups = ldap.getGroup(username)
|
LOGGER.info("User {} success login.".format(username))
|
||||||
LOGGER.info("Get userdata from LDAP")
|
return jsonify(dic)
|
||||||
user_data = ldap.getUserData(username)
|
except PermissionDenied as err:
|
||||||
user_data['group'] = groups
|
return jsonify({"error": str(err)}), 401
|
||||||
LOGGER.info('Insert user {} into database')
|
|
||||||
db.insertUser(user_data)
|
|
||||||
|
|
||||||
except Exception as 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))
|
|
||||||
if user:
|
|
||||||
LOGGER.debug("Check login for User {}".format(user))
|
|
||||||
if login(user, password):
|
|
||||||
token = accesTokenController.createAccesToken(user)
|
|
||||||
dic = user.toJSON()
|
|
||||||
dic["token"] = token
|
|
||||||
dic["accessToken"] = token
|
|
||||||
LOGGER.info("User {} success login.".format(username))
|
|
||||||
return jsonify(dic)
|
|
||||||
else:
|
|
||||||
LOGGER.info("User {} failed login.".format(username))
|
|
||||||
return jsonify({"error": "wrong password"}), 401
|
|
||||||
LOGGER.info("User {} does not exist.".format(username))
|
LOGGER.info("User {} does not exist.".format(username))
|
||||||
return jsonify({"error": "wrong username"}), 402
|
return jsonify({"error": "wrong username"}), 401
|
||||||
|
|
BIN
geruecht/site.db
BIN
geruecht/site.db
Binary file not shown.
Loading…
Reference in New Issue