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.
"""
from .logger import getLogger
from .logger import getDebugLogger, getInfoLogger
from geruecht.controller import dbConfig, ldapConfig
from flask_mysqldb import MySQL
from flask_ldapconn import LDAPConn
LOGGER = getLogger(__name__)
LOGGER.info("Initialize App")
DEBUG = getDebugLogger('INIT', True)
DEBUG.info("Initialize App")
from flask import Flask
from flask_cors import CORS
LOGGER.info("Build APP")
DEBUG.info("Build APP")
app = Flask(__name__)
CORS(app)
app.config['SECRET_KEY'] = '0a657b97ef546da90b2db91862ad4e29'
@ -40,7 +40,7 @@ from geruecht.user.routes import user
from geruecht.vorstand.routes import vorstand
from geruecht.gastro.routes import gastrouser
LOGGER.info("Registrate bluebrints")
DEBUG.info("Registrate bluebrints")
app.register_blueprint(baruser)
app.register_blueprint(finanzer)
app.register_blueprint(user)

View File

@ -1,7 +1,7 @@
import yaml
import sys
from .logger import getLogger
LOGGER = getLogger(__name__)
from .logger import getDebugLogger, getInfoLogger
DEBUG = getDebugLogger("CONFIG", True)
default = {
'AccessTokenLifeTime': 1800,
@ -27,49 +27,50 @@ class ConifgParser():
self.__error__('Wrong Configuration for Database. You should configure databaseconfig with "URL", "user", "passwd", "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:
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']:
self.__error__('Wrong Configuration for LDAP. You should configure ldapconfig with "URL" and "dn"')
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.ldap = self.config['LDAP']
LOGGER.info("Set LDAPconfig: {}".format(self.ldap))
DEBUG.info("Set LDAPconfig: {}".format(self.ldap))
if 'AccessTokenLifeTime' in self.config:
self.accessTokenLifeTime = int(self.config['AccessTokenLifeTime'])
LOGGER.info("Set AccessTokenLifeTime: {}".format(self.accessTokenLifeTime))
DEBUG.info("Set AccessTokenLifeTime: {}".format(self.accessTokenLifeTime))
else:
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:
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']:
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']:
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:
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']:
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']:
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']:
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']:
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']
LOGGER.info('Set Mailconfig: {}'.format(self.mail))
DEBUG.info('Set Mailconfig: {}'.format(self.mail))
def getLDAP(self):
@ -85,7 +86,7 @@ class ConifgParser():
return self.mail
def __error__(self, msg):
LOGGER.error(msg)
DEBUG.error(msg)
sys.exit(-1)
if __name__ == '__main__':

View File

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

View File

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

View File

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

View File

@ -4,18 +4,32 @@ import sys
FORMATTER = logging.Formatter("%(asctime)s — %(name)s%(levelname)s%(message)s")
logFileHandler = WatchedFileHandler("testlog.log")
logFileHandler = WatchedFileHandler("geruecht/log/debug.log")
logFileHandler.setFormatter(FORMATTER)
logStreamHandler = logging.StreamHandler(stream=sys.stdout)
logStreamHandler.setFormatter(FORMATTER)
def getLogger(logger_name):
return getDebugLogger(logger_name)
def getInfoLogger(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.addHandler(logFileHandler)
logger.addHandler(logStreamHandler)
logger.propagate = False
return logger

View File

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