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.
|
||||
|
||||
"""
|
||||
import logging
|
||||
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
|
||||
from .logger import getLogger
|
||||
|
||||
LOGGER = getLogger(__name__)
|
||||
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_cors import CORS
|
||||
from .controller.accesTokenController import AccesTokenController
|
||||
|
||||
LOGGER.info("Build APP")
|
||||
app = Flask(__name__)
|
||||
CORS(app)
|
||||
# app.config['SECRET_KEY'] = '0a657b97ef546da90b2db91862ad4e29'
|
||||
accesTokenController = AccesTokenController("GERUECHT")
|
||||
|
||||
|
||||
|
||||
|
||||
from geruecht import routes
|
||||
from geruecht.baruser.routes import baruser
|
||||
|
|
|
@ -1,6 +1,7 @@
|
|||
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 geruecht.model import BAR
|
||||
|
||||
baruser = Blueprint("baruser", __name__)
|
||||
|
||||
|
@ -21,10 +22,10 @@ def _bar():
|
|||
|
||||
dic = {}
|
||||
if accToken:
|
||||
users = db.getAllUser()
|
||||
users = userController.getAllUsersfromDB()
|
||||
for user in users:
|
||||
geruecht = None
|
||||
geruecht = user.getGeruecht()
|
||||
geruecht = user.getGeruecht(datetime.now().year)
|
||||
if geruecht is not None:
|
||||
month = geruecht.getMonth(datetime.now().month)
|
||||
amount = month[0] - month[1]
|
||||
|
@ -33,7 +34,7 @@ def _bar():
|
|||
type = 'credit'
|
||||
else:
|
||||
type = 'amount'
|
||||
dic[user.cn] = {"username": user.cn,
|
||||
dic[user.uid] = {"username": user.uid,
|
||||
"firstname": user.firstname,
|
||||
"lastname": user.lastname,
|
||||
"amount": abs(month[0] - month[1]),
|
||||
|
@ -61,18 +62,13 @@ def _baradd():
|
|||
userID = data['userId']
|
||||
amount = int(data['amount'])
|
||||
|
||||
user = db.getUser(userID)
|
||||
if user is None:
|
||||
groups = ldap.getGroup(userID)
|
||||
user_data = ldap.getUserData(userID)
|
||||
user_data['group'] = groups
|
||||
db.insertUser(user_data)
|
||||
user = db.getUser(userID)
|
||||
month = user.addAmount(amount)
|
||||
|
||||
date = datetime.now()
|
||||
userController.addAmount(userID, amount, year=date.year, month=date.month)
|
||||
user = userController.getUser(userID)
|
||||
month = user.getGeruecht(year=date.year).getMonth(month=date.month)
|
||||
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
|
||||
|
||||
@baruser.route("/barGetUsers")
|
||||
|
|
|
@ -1,3 +1,30 @@
|
|||
from geruecht import getLogger
|
||||
from geruecht.logger import getLogger
|
||||
|
||||
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 datetime import datetime, timedelta
|
||||
import hashlib
|
||||
import logging
|
||||
from logging.handlers import WatchedFileHandler
|
||||
from geruecht import Singleton
|
||||
from . import Singleton
|
||||
|
||||
class AccesTokenController(metaclass=Singleton):
|
||||
""" Control all createt AccesToken
|
||||
|
@ -26,17 +24,6 @@ class AccesTokenController(metaclass=Singleton):
|
|||
"""
|
||||
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 = []
|
||||
|
||||
def validateAccessToken(self, token, group):
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
import pymysql
|
||||
from geruecht import Singleton
|
||||
from . import Singleton
|
||||
from geruecht.model.user import User
|
||||
from geruecht.model.creditList import CreditList
|
||||
from datetime import datetime
|
||||
|
@ -36,20 +36,28 @@ class DatabaseController(metaclass=Singleton):
|
|||
raise err
|
||||
|
||||
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):
|
||||
self.connect()
|
||||
retVal = None
|
||||
cursor = self.db.cursor()
|
||||
try:
|
||||
cursor.execute("select * from user where cn='{}'".format(username))
|
||||
cursor.execute("select * from user where uid='{}'".format(username))
|
||||
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
|
||||
|
||||
|
@ -66,8 +74,8 @@ class DatabaseController(metaclass=Singleton):
|
|||
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'], groups))
|
||||
cursor.execute("insert into user (uid, dn, firstname, lastname, gruppe) VALUES ('{}','{}','{}','{}','{}')".format(
|
||||
data['uid'], data['dn'], data['givenName'], data['sn'], groups))
|
||||
self.db.commit()
|
||||
except Exception as err:
|
||||
self.db.rollback()
|
||||
|
@ -80,8 +88,8 @@ class DatabaseController(metaclass=Singleton):
|
|||
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'], groups, data['cn']))
|
||||
cursor.execute("update user set dn='{}', firstname='{}', lastname='{}', gruppe='{}' where uid='{}'".format(
|
||||
data['dn'], data['givenName'], data['sn'], groups, data['uid']))
|
||||
self.db.commit()
|
||||
except Exception as err:
|
||||
self.db.rollback()
|
||||
|
|
|
@ -1,5 +1,7 @@
|
|||
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):
|
||||
'''
|
||||
|
@ -20,15 +22,16 @@ class LDAPController(metaclass=Singleton):
|
|||
def login(self, username, password):
|
||||
self.connect()
|
||||
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()
|
||||
except:
|
||||
self.client.unbind_s()
|
||||
raise Exception("Invalid Password or Username")
|
||||
raise PermissionDenied("Invalid Password or Username")
|
||||
|
||||
def getUserData(self, username):
|
||||
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]
|
||||
for k,v in retVal.items():
|
||||
retVal[k] = v[0].decode('utf-8')
|
||||
|
@ -39,7 +42,7 @@ 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'])
|
||||
main_group_data = self.client.search_s('ou=user,{}'.format(self.dn), ldap.SCOPE_SUBTREE, 'uid={}'.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'])
|
||||
|
@ -71,10 +74,10 @@ class LDAPController(metaclass=Singleton):
|
|||
def getAllUser(self):
|
||||
self.connect()
|
||||
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:
|
||||
if 'cn' in user[1]:
|
||||
username = user[1]['cn'][0].decode('utf-8')
|
||||
if 'uid' in user[1]:
|
||||
username = user[1]['uid'][0].decode('utf-8')
|
||||
firstname = user[1]['givenName'][0].decode('utf-8')
|
||||
lastname = user[1]['sn'][0].decode('utf-8')
|
||||
retVal.append({'username': username, 'firstname': firstname, 'lastname': lastname})
|
||||
|
@ -96,21 +99,21 @@ class LDAPController(metaclass=Singleton):
|
|||
if len(name) == 1:
|
||||
if name[0] == "**":
|
||||
name_result.append(self.client.search_s('ou=user,{}'.format(self.dn), ldap.SCOPE_SUBTREE,
|
||||
attrlist=['cn', 'givenName', 'sn']))
|
||||
attrlist=['uid', 'givenName', 'sn']))
|
||||
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, 'sn={}'.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]),['uid', 'givenName', 'sn']))
|
||||
else:
|
||||
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]),
|
||||
['cn', 'givenName', 'sn']))
|
||||
['uid', 'givenName', 'sn']))
|
||||
retVal = []
|
||||
|
||||
for names in name_result:
|
||||
for user in names:
|
||||
if 'cn' in user[1]:
|
||||
username = user[1]['cn'][0].decode('utf-8')
|
||||
if 'uid' in user[1]:
|
||||
username = user[1]['uid'][0].decode('utf-8')
|
||||
if not self.__isUserInList(retVal, username):
|
||||
firstname = user[1]['givenName'][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 geruecht.finanzer import LOGGER
|
||||
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__)
|
||||
|
||||
|
@ -22,53 +23,18 @@ def _getFinanzer():
|
|||
accToken = accesTokenController.validateAccessToken(token, MONEY)
|
||||
if accToken:
|
||||
LOGGER.debug("Get all Useres")
|
||||
users = db.getAllUser()
|
||||
users = userController.getAllUsersfromDB()
|
||||
dic = {}
|
||||
for user in users:
|
||||
LOGGER.debug("Add User {} to ReturnValue".format(user))
|
||||
dic[user.cn] = user.toJSON()
|
||||
creditList = db.getCreditListFromUser(user)
|
||||
dic[user.cn]['creditList'] = {credit.year: credit.toJSON() for credit in creditList}
|
||||
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
|
||||
|
||||
@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'])
|
||||
def _addAmount():
|
||||
""" Add Amount to User
|
||||
|
@ -103,11 +69,7 @@ def _addAmount():
|
|||
LOGGER.error("KeyError in month. Month is set to default.")
|
||||
month = datetime.now().month
|
||||
LOGGER.debug("Year is {} and Month is {}".format(year, month))
|
||||
user = db.getUser(userID)
|
||||
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()
|
||||
retVal = userController.addAmount(userID, amount, year=year, month=month).toJSON()
|
||||
LOGGER.info("Send updated Geruecht")
|
||||
return jsonify(retVal)
|
||||
LOGGER.info("Permission Denied")
|
||||
|
@ -151,11 +113,7 @@ def _addCredit():
|
|||
month = datetime.now().month
|
||||
|
||||
LOGGER.debug("Year is {} and Month is {}".format(year, month))
|
||||
user = db.getUser(userID)
|
||||
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()
|
||||
retVal = userController.addCredit(userID, credit, year=year, month=month).toJSON()
|
||||
LOGGER.info("Send updated Geruecht")
|
||||
return jsonify(retVal)
|
||||
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 geruecht import getLogger
|
||||
import geruecht
|
||||
|
||||
LOGGER = getLogger(__name__)
|
||||
def create_empty_data():
|
||||
|
@ -92,8 +91,6 @@ class CreditList():
|
|||
|
||||
self.user_id = int(data['user_id'])
|
||||
|
||||
self.db = geruecht.getDatabesController()
|
||||
|
||||
def getSchulden(self):
|
||||
""" Get Schulden
|
||||
|
||||
|
@ -217,9 +214,6 @@ class CreditList():
|
|||
elif month == 12:
|
||||
self.dez_schulden += amount
|
||||
retValue = (self.dez_guthaben, self.dez_schulden)
|
||||
|
||||
#db.session.commit()
|
||||
self.db.updateCreditList(self)
|
||||
LOGGER.debug("Credit and Amount is {}".format(retValue))
|
||||
return retValue
|
||||
|
||||
|
@ -273,8 +267,6 @@ class CreditList():
|
|||
elif month == 12:
|
||||
self.dez_guthaben += credit
|
||||
retValue = (self.dez_guthaben, self.dez_schulden)
|
||||
self.db.updateCreditList(self)
|
||||
#db.session.commit()
|
||||
LOGGER.debug("Credit and Amount is {}".format(retValue))
|
||||
return retValue
|
||||
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
from geruecht import db
|
||||
from geruecht.controller import db
|
||||
|
||||
class PriceList(db.Model):
|
||||
""" Database Model for PriceList
|
||||
|
|
|
@ -1,5 +1,4 @@
|
|||
from geruecht import getLogger
|
||||
import geruecht
|
||||
from geruecht.logger import getLogger
|
||||
from geruecht.model.creditList import CreditList, create_empty_data
|
||||
from datetime import datetime
|
||||
|
||||
|
@ -22,7 +21,7 @@ class User():
|
|||
"""
|
||||
def __init__(self, data):
|
||||
self.id = int(data['id'])
|
||||
self.cn = data['cn']
|
||||
self.uid = data['uid']
|
||||
self.dn = data['dn']
|
||||
self.firstname = data['firstname']
|
||||
self.lastname = data['lastname']
|
||||
|
@ -31,17 +30,12 @@ class User():
|
|||
self.group = data['gruppe']
|
||||
elif type(data['gruppe']) == str:
|
||||
self.group = data['gruppe'].split(',')
|
||||
if 'creditLists' in data:
|
||||
self.geruechte = data['creditLists']
|
||||
|
||||
self.db = geruecht.getDatabesController()
|
||||
self.ldap = geruecht.getLDAPController()
|
||||
self.geruechte = []
|
||||
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 initGeruechte(self, creditLists):
|
||||
if type(creditLists) == list:
|
||||
self.geruechte = creditLists
|
||||
|
||||
def createGeruecht(self, amount=0, year=datetime.now().year):
|
||||
""" Create Geruecht
|
||||
|
@ -63,8 +57,6 @@ class User():
|
|||
data['year_date'] = year
|
||||
credit = CreditList(data)
|
||||
self.geruechte.append(credit)
|
||||
self.db.updateCreditList(credit)
|
||||
credit = self.db.getCreditListFromUser(self, year=year)
|
||||
LOGGER.debug("Created Geruecht {}".format(credit))
|
||||
return credit
|
||||
|
||||
|
@ -89,8 +81,6 @@ class User():
|
|||
LOGGER.debug("No Geruecht found for User {}. Will create one".format(self))
|
||||
geruecht = self.createGeruecht(year=year)
|
||||
|
||||
self.updateGeruecht()
|
||||
|
||||
return self.getGeruecht(year=year)
|
||||
|
||||
def addAmount(self, amount, year=datetime.now().year, month=datetime.now().month):
|
||||
|
@ -111,10 +101,6 @@ class User():
|
|||
geruecht = self.getGeruecht(year=year)
|
||||
retVal = geruecht.addAmount(amount, month=month)
|
||||
|
||||
self.db.updateCreditList(geruecht)
|
||||
|
||||
self.updateGeruecht()
|
||||
|
||||
return retVal
|
||||
|
||||
def addCredit(self, credit, year=datetime.now().year, month=datetime.now().month):
|
||||
|
@ -135,10 +121,6 @@ class User():
|
|||
geruecht = self.getGeruecht(year=year)
|
||||
retVal = geruecht.addCredit(credit, month=month)
|
||||
|
||||
self.db.updateCreditList(geruecht)
|
||||
|
||||
self.updateGeruecht()
|
||||
|
||||
return retVal
|
||||
|
||||
def updateGeruecht(self):
|
||||
|
@ -154,7 +136,8 @@ class User():
|
|||
geruecht.last_schulden = 0
|
||||
if index != 0:
|
||||
geruecht.last_schulden = (self.geruechte[index - 1].getSchulden() * -1)
|
||||
self.db.updateCreditList(geruecht)
|
||||
|
||||
return self.geruechte
|
||||
|
||||
def sortYear(self, geruecht):
|
||||
""" Sort Year
|
||||
|
@ -177,38 +160,16 @@ class User():
|
|||
A Dic with static Attributes.
|
||||
"""
|
||||
dic = {
|
||||
"userId": self.cn,
|
||||
"cn": self.cn,
|
||||
"userId": self.uid,
|
||||
"uid": self.uid,
|
||||
"dn": self.dn,
|
||||
"firstname": self.firstname,
|
||||
"lastname": self.lastname,
|
||||
"group": self.group,
|
||||
"username": self.cn
|
||||
"username": self.uid
|
||||
}
|
||||
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):
|
||||
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 ldapController as ldap
|
||||
from geruecht.model.user import User
|
||||
from geruecht import app, LOGGER
|
||||
from geruecht.exceptions import PermissionDenied
|
||||
from geruecht.controller import accesTokenController, userController
|
||||
from geruecht.model import MONEY, BAR, USER, GASTRO
|
||||
from flask import request, jsonify
|
||||
|
||||
|
||||
def login(user, password):
|
||||
return user.login(password)
|
||||
|
||||
|
@ -40,35 +42,15 @@ def _login():
|
|||
username = data['username']
|
||||
password = data['password']
|
||||
LOGGER.info("search {} in database".format(username))
|
||||
user = db.getUser(username)
|
||||
if user is None:
|
||||
LOGGER.info("User {} not found. Authenticate over LDAP and create User.")
|
||||
try:
|
||||
ldap.login(username, password)
|
||||
LOGGER.info("Authentification successfull. Search Group")
|
||||
groups = ldap.getGroup(username)
|
||||
LOGGER.info("Get userdata from LDAP")
|
||||
user_data = ldap.getUserData(username)
|
||||
user_data['group'] = groups
|
||||
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
|
||||
try:
|
||||
user = userController.loginUser(username, password)
|
||||
token = accesTokenController.createAccesToken(user)
|
||||
dic = user.toJSON()
|
||||
dic["token"] = token
|
||||
dic["accessToken"] = token
|
||||
LOGGER.info("User {} success login.".format(username))
|
||||
return jsonify(dic)
|
||||
except PermissionDenied as err:
|
||||
return jsonify({"error": str(err)}), 401
|
||||
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