add new logger

This commit is contained in:
Tim Gröger 2020-03-09 19:54:51 +01:00
parent 39095af891
commit 57f0f17a90
9 changed files with 104 additions and 45 deletions

View File

@ -4,18 +4,18 @@
Initialize also a singelton for the AccesTokenControler and start the Thread. Initialize also a singelton for the AccesTokenControler and start the Thread.
""" """
from .logger import getLogger from .logger import getDebugLogger, getInfoLogger
from geruecht.controller import dbConfig, ldapConfig from geruecht.controller import dbConfig, ldapConfig
from flask_mysqldb import MySQL from flask_mysqldb import MySQL
from flask_ldapconn import LDAPConn from flask_ldapconn import LDAPConn
LOGGER = getLogger(__name__) DEBUG = getDebugLogger('INIT', True)
LOGGER.info("Initialize App") DEBUG.info("Initialize App")
from flask import Flask from flask import Flask
from flask_cors import CORS from flask_cors import CORS
LOGGER.info("Build APP") DEBUG.info("Build APP")
app = Flask(__name__) app = Flask(__name__)
CORS(app) CORS(app)
app.config['SECRET_KEY'] = '0a657b97ef546da90b2db91862ad4e29' app.config['SECRET_KEY'] = '0a657b97ef546da90b2db91862ad4e29'
@ -40,7 +40,7 @@ from geruecht.user.routes import user
from geruecht.vorstand.routes import vorstand from geruecht.vorstand.routes import vorstand
from geruecht.gastro.routes import gastrouser from geruecht.gastro.routes import gastrouser
LOGGER.info("Registrate bluebrints") DEBUG.info("Registrate bluebrints")
app.register_blueprint(baruser) app.register_blueprint(baruser)
app.register_blueprint(finanzer) app.register_blueprint(finanzer)
app.register_blueprint(user) app.register_blueprint(user)

View File

@ -1,7 +1,7 @@
import yaml import yaml
import sys import sys
from .logger import getLogger from .logger import getDebugLogger, getInfoLogger
LOGGER = getLogger(__name__) DEBUG = getDebugLogger("CONFIG", True)
default = { default = {
'AccessTokenLifeTime': 1800, 'AccessTokenLifeTime': 1800,
@ -27,49 +27,50 @@ class ConifgParser():
self.__error__('Wrong Configuration for Database. You should configure databaseconfig with "URL", "user", "passwd", "database"') self.__error__('Wrong Configuration for Database. You should configure databaseconfig with "URL", "user", "passwd", "database"')
self.db = self.config['Database'] self.db = self.config['Database']
LOGGER.debug("Set Databaseconfig: {}".format(self.db)) DEBUG.debug("Set Databaseconfig: {}".format(self.db))
if 'LDAP' not in self.config: if 'LDAP' not in self.config:
self.__error__('Wrong Configuration for LDAP. You should configure ldapconfig with "URL" and "dn"') self.__error__('Wrong Configuration for LDAP. You should configure ldapconfig with "URL" and "dn"')
if 'URL' not in self.config['LDAP'] or 'dn' not in self.config['LDAP']: if 'URL' not in self.config['LDAP'] or 'dn' not in self.config['LDAP']:
self.__error__('Wrong Configuration for LDAP. You should configure ldapconfig with "URL" and "dn"') self.__error__('Wrong Configuration for LDAP. You should configure ldapconfig with "URL" and "dn"')
if 'port' not in self.config['LDAP']: if 'port' not in self.config['LDAP']:
LOGGER.info('No Config for port in LDAP found. Set it to default: {}'.format(389)) DEBUG.info('No Config for port in LDAP found. Set it to default: {}'.format(389))
self.config['LDAP']['port'] = 389 self.config['LDAP']['port'] = 389
self.ldap = self.config['LDAP'] self.ldap = self.config['LDAP']
LOGGER.info("Set LDAPconfig: {}".format(self.ldap)) DEBUG.info("Set LDAPconfig: {}".format(self.ldap))
if 'AccessTokenLifeTime' in self.config: if 'AccessTokenLifeTime' in self.config:
self.accessTokenLifeTime = int(self.config['AccessTokenLifeTime']) self.accessTokenLifeTime = int(self.config['AccessTokenLifeTime'])
LOGGER.info("Set AccessTokenLifeTime: {}".format(self.accessTokenLifeTime)) DEBUG.info("Set AccessTokenLifeTime: {}".format(self.accessTokenLifeTime))
else: else:
self.accessTokenLifeTime = default['AccessTokenLifeTime'] self.accessTokenLifeTime = default['AccessTokenLifeTime']
LOGGER.info("No Config for AccessTokenLifetime found. Set it to default: {}".format(self.accessTokenLifeTime)) DEBUG.info("No Config for AccessTokenLifetime found. Set it to default: {}".format(self.accessTokenLifeTime))
if 'Mail' not in self.config: if 'Mail' not in self.config:
self.config['Mail'] = default['Mail'] self.config['Mail'] = default['Mail']
LOGGER.info('No Conifg for Mail found. Set it to defaul: {}'.format(self.config['Mail'])) DEBUG.info('No Conifg for Mail found. Set it to defaul: {}'.format(self.config['Mail']))
if 'URL' not in self.config['Mail']: if 'URL' not in self.config['Mail']:
self.config['Mail']['URL'] = default['Mail']['URL'] self.config['Mail']['URL'] = default['Mail']['URL']
LOGGER.info("No Config for URL in Mail found. Set it to default") DEBUG.info("No Config for URL in Mail found. Set it to default")
if 'port' not in self.config['Mail']: if 'port' not in self.config['Mail']:
self.config['Mail']['port'] = default['Mail']['port'] self.config['Mail']['port'] = default['Mail']['port']
LOGGER.info("No Config for port in Mail found. Set it to default") DEBUG.info("No Config for port in Mail found. Set it to default")
else: else:
self.config['Mail']['port'] = int(self.config['Mail']['port']) self.config['Mail']['port'] = int(self.config['Mail']['port'])
DEBUG.info("No Conifg for port in Mail found. Set it to default")
if 'user' not in self.config['Mail']: if 'user' not in self.config['Mail']:
self.config['Mail']['user'] = default['Mail']['user'] self.config['Mail']['user'] = default['Mail']['user']
LOGGER.info("No Config for user in Mail found. Set it to default") DEBUG.info("No Config for user in Mail found. Set it to default")
if 'passwd' not in self.config['Mail']: if 'passwd' not in self.config['Mail']:
self.config['Mail']['passwd'] = default['Mail']['passwd'] self.config['Mail']['passwd'] = default['Mail']['passwd']
LOGGER.info("No Config for passwd in Mail found. Set it to default") DEBUG.info("No Config for passwd in Mail found. Set it to default")
if 'email' not in self.config['Mail']: if 'email' not in self.config['Mail']:
self.config['Mail']['email'] = default['Mail']['email'] self.config['Mail']['email'] = default['Mail']['email']
LOGGER.info("No Config for email in Mail found. Set it to default") DEBUG.info("No Config for email in Mail found. Set it to default")
if 'crypt' not in self.config['Mail']: if 'crypt' not in self.config['Mail']:
self.config['Mail']['crypt'] = default['Mail']['crypt'] self.config['Mail']['crypt'] = default['Mail']['crypt']
LOGGER.info("No Config for crypt in Mail found. Set it to default") DEBUG.info("No Config for crypt in Mail found. Set it to default")
self.mail = self.config['Mail'] self.mail = self.config['Mail']
LOGGER.info('Set Mailconfig: {}'.format(self.mail)) DEBUG.info('Set Mailconfig: {}'.format(self.mail))
def getLDAP(self): def getLDAP(self):
@ -85,7 +86,7 @@ class ConifgParser():
return self.mail return self.mail
def __error__(self, msg): def __error__(self, msg):
LOGGER.error(msg) DEBUG.error(msg)
sys.exit(-1) sys.exit(-1)
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -3,7 +3,7 @@ from datetime import datetime
from email.mime.multipart import MIMEMultipart from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText from email.mime.text import MIMEText
from email.header import Header from email.header import Header
from geruecht import getLogger from geruecht.logger import getLogger
LOGGER = getLogger('E-MailController') LOGGER = getLogger('E-MailController')

View File

@ -1,4 +1,6 @@
from functools import wraps from functools import wraps
from .logger import getInfoLogger, getDebugLogger
DEBUG = getDebugLogger("login-decorator", True)
def login_required(**kwargs): def login_required(**kwargs):
import geruecht.controller.accesTokenController as ac import geruecht.controller.accesTokenController as ac
from geruecht.model import BAR, USER, MONEY, GASTRO from geruecht.model import BAR, USER, MONEY, GASTRO
@ -11,11 +13,14 @@ def login_required(**kwargs):
@wraps(func) @wraps(func)
def wrapper(*args, **kwargs): def wrapper(*args, **kwargs):
token = request.headers.get('Token') token = request.headers.get('Token')
DEBUG.info("get token {{}}".format(token))
accToken = accessController.validateAccessToken(token, groups) accToken = accessController.validateAccessToken(token, groups)
kwargs['accToken'] = accToken kwargs['accToken'] = accToken
if accToken: if accToken:
DEBUG.info("token {{}} is valid".format(token))
return func(*args, **kwargs) return func(*args, **kwargs)
else: else:
DEBUG.warning("token {{}} is not valid".format(token))
return jsonify({"error": "error", "message": "permission denied"}), 401 return jsonify({"error": "error", "message": "permission denied"}), 401
return wrapper return wrapper
return real_decorator return real_decorator

View File

@ -1,3 +1,3 @@
from geruecht import getLogger from geruecht.logger import getLogger
LOGGER = getLogger(__name__) LOGGER = getLogger(__name__)

View File

@ -4,18 +4,32 @@ import sys
FORMATTER = logging.Formatter("%(asctime)s%(name)s%(levelname)s%(message)s") FORMATTER = logging.Formatter("%(asctime)s%(name)s%(levelname)s%(message)s")
logFileHandler = WatchedFileHandler("testlog.log") logFileHandler = WatchedFileHandler("geruecht/log/debug.log")
logFileHandler.setFormatter(FORMATTER) logFileHandler.setFormatter(FORMATTER)
logStreamHandler = logging.StreamHandler(stream=sys.stdout) logStreamHandler = logging.StreamHandler(stream=sys.stdout)
logStreamHandler.setFormatter(FORMATTER) logStreamHandler.setFormatter(FORMATTER)
def getLogger(logger_name): def getLogger(logger_name):
return getDebugLogger(logger_name)
def getInfoLogger(logger_name):
logger = logging.getLogger(logger_name) logger = logging.getLogger(logger_name)
logger.setLevel(logging.INFO)
logger.addHandler(logStreamHandler)
logFileHandler = WatchedFileHandler("geruecht/log/info/{}.log".format(logger_name))
logFileHandler.setFormatter(FORMATTER)
logger.addHandler(logFileHandler)
return logger
def getDebugLogger(logger_name, path=False):
logger = logging.getLogger(logger_name)
if path:
logSecondFileHandler = WatchedFileHandler("geruecht/log/debug/{}.log".format(logger_name))
logSecondFileHandler.setFormatter(FORMATTER)
logger.addHandler(logSecondFileHandler)
logger.setLevel(logging.DEBUG) logger.setLevel(logging.DEBUG)
logger.addHandler(logFileHandler) logger.addHandler(logFileHandler)
logger.addHandler(logStreamHandler)
logger.propagate = False logger.propagate = False
return logger return logger

View File

@ -1,5 +1,5 @@
from datetime import datetime from datetime import datetime
from geruecht import getLogger from geruecht.logger import getLogger
LOGGER = getLogger(__name__) LOGGER = getLogger(__name__)
@ -49,7 +49,7 @@ class AccessToken():
return other - self.timestamp return other - self.timestamp
def __str__(self): def __str__(self):
return "AccessToken({}, {}, {}".format(self.user, self.token, self.timestamp) return "AccessToken(user={}, token={}, timestamp={}, lifetime={}".format(self.user, self.token, self.timestamp, self.lifetime)
def __repr__(self): def __repr__(self):
return "AccessToken({}, {}, {}".format(self.user, self.token, self.timestamp) return "AccessToken(user={}, token={}, timestamp={}, lifetime={}".format(self.user, self.token, self.timestamp, self.lifetime)

View File

@ -1,5 +1,5 @@
from datetime import datetime from datetime import datetime
from geruecht import getLogger from geruecht.logger import getLogger
LOGGER = getLogger(__name__) LOGGER = getLogger(__name__)
def create_empty_data(): def create_empty_data():

View File

@ -1,4 +1,5 @@
from geruecht import app, LOGGER from geruecht import app
from geruecht.logger import getDebugLogger, getInfoLogger
from geruecht.decorator import login_required from geruecht.decorator import login_required
from geruecht.exceptions import PermissionDenied from geruecht.exceptions import PermissionDenied
import geruecht.controller.accesTokenController as ac import geruecht.controller.accesTokenController as ac
@ -9,6 +10,9 @@ from flask import request, jsonify
accesTokenController = ac.AccesTokenController() accesTokenController = ac.AccesTokenController()
userController = uc.UserController() userController = uc.UserController()
debug = getDebugLogger("MAIN-ROUTE", True)
info = getInfoLogger("MAIN-ROUTE")
def login(user, password): def login(user, password):
return user.login(password) return user.login(password)
@ -33,85 +37,117 @@ def _valid():
@app.route("/pricelist", methods=['GET']) @app.route("/pricelist", methods=['GET'])
def _getPricelist(): def _getPricelist():
try: try:
debug.info("get pricelist")
retVal = userController.getPricelist() retVal = userController.getPricelist()
print(retVal) debug.info("return pricelist {{}}".format(retVal))
return jsonify(retVal) return jsonify(retVal)
except Exception as err: except Exception as err:
return jsonify({"error": str(err)}) debug.warning("exception in get pricelist.", exc_info=True)
return jsonify({"error": str(err)}), 500
@app.route('/drinkTypes', methods=['GET']) @app.route('/drinkTypes', methods=['GET'])
def getTypes(): def getTypes():
try: try:
debug.info("get drinktypes")
retVal = userController.getAllDrinkTypes() retVal = userController.getAllDrinkTypes()
debug.info("return drinktypes {{}}".format(retVal))
return jsonify(retVal) return jsonify(retVal)
except Exception as err: except Exception as err:
debug.warning("exception in get drinktypes.", exc_info=True)
return jsonify({"error": str(err)}), 500 return jsonify({"error": str(err)}), 500
@app.route('/getAllStatus', methods=['GET']) @app.route('/getAllStatus', methods=['GET'])
@login_required(groups=[USER, MONEY, GASTRO, BAR, VORSTAND]) @login_required(groups=[USER, MONEY, GASTRO, BAR, VORSTAND])
def _getAllStatus(**kwargs): def _getAllStatus(**kwargs):
try: try:
debug.info("get all status for users")
retVal = userController.getAllStatus() retVal = userController.getAllStatus()
debug.info("return all status for users {{}}".format(retVal))
return jsonify(retVal) return jsonify(retVal)
except Exception as err: except Exception as err:
debug.warning("exception in get all status for users.", exc_info=True)
return jsonify({"error": str(err)}), 500 return jsonify({"error": str(err)}), 500
@app.route('/getStatus', methods=['POST']) @app.route('/getStatus', methods=['POST'])
@login_required(groups=[USER, MONEY, GASTRO, BAR, VORSTAND]) @login_required(groups=[USER, MONEY, GASTRO, BAR, VORSTAND])
def _getStatus(**kwargs): def _getStatus(**kwargs):
try: try:
debug.info("get status from user")
data = request.get_json() data = request.get_json()
name = data['name'] name = data['name']
debug.info("get status from user {{}}".format(name))
retVal = userController.getStatus(name) retVal = userController.getStatus(name)
debug.info("return status from user {{}} : {{}}".format(name, retVal))
return jsonify(retVal) return jsonify(retVal)
except Exception as err: except Exception as err:
debug.warning("exception in get status from user.", exc_info=True)
return jsonify({"error": str(err)}), 500 return jsonify({"error": str(err)}), 500
@app.route('/getUsers', methods=['GET']) @app.route('/getUsers', methods=['GET'])
@login_required(groups=[MONEY, GASTRO, VORSTAND]) @login_required(groups=[MONEY, GASTRO, VORSTAND])
def _getUsers(**kwargs): def _getUsers(**kwargs):
try: try:
debug.info("get all users from database")
users = userController.getAllUsersfromDB() users = userController.getAllUsersfromDB()
debug.debug("users are {{}}".format(users))
retVal = [user.toJSON() for user in users] retVal = [user.toJSON() for user in users]
debug.info("return all users from database {{}}".format(retVal))
return jsonify(retVal) return jsonify(retVal)
except Exception as err: except Exception as err:
debug.warning("exception in get all users from database.", exc_info=True)
return jsonify({"error": str(err)}), 500 return jsonify({"error": str(err)}), 500
@app.route("/getLifeTime", methods=['GET']) @app.route("/getLifeTime", methods=['GET'])
@login_required(groups=[MONEY, GASTRO, VORSTAND, EXTERN, USER]) @login_required(groups=[MONEY, GASTRO, VORSTAND, EXTERN, USER])
def _getLifeTime(**kwargs): def _getLifeTime(**kwargs):
try: try:
debug.info("get lifetime of accesstoken")
if 'accToken' in kwargs: if 'accToken' in kwargs:
accToken = kwargs['accToken'] accToken = kwargs['accToken']
return jsonify({"value": accToken.lifetime}) debug.debug("accessToken is {{}}".format(accToken))
retVal = {"value": accToken.lifetime}
debug.info("return get lifetime from accesstoken {{}}".format(retVal))
return jsonify(retVal)
except Exception as err: except Exception as err:
debug.info("exception in get lifetime of accesstoken.", exc_info=True)
return jsonify({"error": str(err)}), 500 return jsonify({"error": str(err)}), 500
@app.route("/saveLifeTime", methods=['POST']) @app.route("/saveLifeTime", methods=['POST'])
@login_required(groups=[MONEY, GASTRO, VORSTAND, EXTERN, USER]) @login_required(groups=[MONEY, GASTRO, VORSTAND, EXTERN, USER])
def _saveLifeTime(**kwargs): def _saveLifeTime(**kwargs):
try: try:
debug.info("save lifetime for accessToken")
if 'accToken' in kwargs: if 'accToken' in kwargs:
accToken = kwargs['accToken'] accToken = kwargs['accToken']
debug.debug("accessToken is {{}}".format(accToken))
data = request.get_json() data = request.get_json()
lifetime = data['value'] lifetime = data['value']
debug.debug("lifetime is {{}}".format(lifetime))
debug.info("set lifetime {{}} to accesstoken {{}}".format(lifetime, accToken))
accToken.lifetime = lifetime accToken.lifetime = lifetime
debug.info("update accesstoken timestamp")
accToken.updateTimestamp() accToken.updateTimestamp()
retVal = {"value": accToken.lifetime}
return jsonify({"value": accToken.lifetime}) debug.info("return save lifetime for accessToken {{}}".format(retVal))
return jsonify(retVal)
except Exception as err: except Exception as err:
debug.warning("exception in save lifetime for accesstoken.", exc_info=True)
return jsonify({"error": str(err)}), 500 return jsonify({"error": str(err)}), 500
@app.route("/logout", methods=['GET']) @app.route("/logout", methods=['GET'])
@login_required(groups=[MONEY, GASTRO, VORSTAND, EXTERN, USER]) @login_required(groups=[MONEY, GASTRO, VORSTAND, EXTERN, USER])
def _logout(**kwargs): def _logout(**kwargs):
try: try:
debug.info("logout user")
if 'accToken' in kwargs: if 'accToken' in kwargs:
accToken = kwargs['accToken'] accToken = kwargs['accToken']
debug.debug("accesstoken is {{}}".format(accToken))
debug.info("delete accesstoken")
accesTokenController.deleteAccessToken(accToken) accesTokenController.deleteAccessToken(accToken)
debug.info("return ok logout user")
return jsonify({"ok": "ok"}) return jsonify({"ok": "ok"})
except Exception as err: except Exception as err:
debug.warning("exception in logout user.", exc_info=True)
return jsonify({"error": str(err)}), 500 return jsonify({"error": str(err)}), 500
@app.route("/login", methods=['POST']) @app.route("/login", methods=['POST'])
@ -124,25 +160,28 @@ def _login():
Returns: Returns:
A JSON-File with createt Token or Errors A JSON-File with createt Token or Errors
""" """
LOGGER.info("Start log in.") debug.info("Start log in.")
data = request.get_json() data = request.get_json()
print(data) debug.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']
LOGGER.info("search {} in database".format(username))
try: try:
debug.info("search {{}} in database".format(username))
user, ldap_conn = userController.loginUser(username, password) user, ldap_conn = userController.loginUser(username, password)
debug.debug("user is {{}}".format(user))
user.password = password user.password = password
token = accesTokenController.createAccesToken(user, ldap_conn) token = accesTokenController.createAccesToken(user, ldap_conn)
debug.debug("accesstoken is {{}}".format(token))
debug.info("validate accesstoken")
dic = accesTokenController.validateAccessToken(token, [USER, EXTERN]).user.toJSON() dic = accesTokenController.validateAccessToken(token, [USER, EXTERN]).user.toJSON()
dic["token"] = token dic["token"] = token
dic["accessToken"] = token dic["accessToken"] = token
LOGGER.info("User {} success login.".format(username)) debug.info("User {{}} success login.".format(username))
debug.info("return login {{}}".format(dic))
return jsonify(dic) return jsonify(dic)
except PermissionDenied as err: except PermissionDenied as err:
debug.warning("permission denied exception in logout", exc_info=True)
return jsonify({"error": str(err)}), 401 return jsonify({"error": str(err)}), 401
except Exception as err: except Exception as err:
debug.warning("exception in logout.", exc_info=True)
return jsonify({"error": "permission denied"}), 401 return jsonify({"error": "permission denied"}), 401
LOGGER.info("User {} does not exist.".format(username))
return jsonify({"error": "wrong username"}), 401