from geruecht import app, db, accesTokenController, MONEY, BAR, USER, GASTRO, LOGGER from geruecht.model.user import User from geruecht.model.creditList import CreditList from geruecht.model.priceList import PriceList from datetime import datetime from flask import request, jsonify def verifyAccessToken(token, group): """ Verify Accestoken Verify an Accestoken and Group so if the User has permission or not. Retrieves the accestoken if valid else retrieves None Args: token: Token to verify. group: Group like 'moneymaster', 'gastro', 'user' or 'bar' Returns: An the AccesToken for this given Token or None. """ LOGGER.info("Verify AccessToken with token: {} and group: {}".format(token, group)) accToken = accesTokenController.findAccesToken(token) LOGGER.debug("AccessToken is {}".format(accToken)) if accToken is not None: LOGGER.debug("Check if AccesToken {} has same group {}".format(accToken, group)) if accesTokenController.isSameGroup(accToken, group): accToken.updateTimestamp() LOGGER.info("Found AccessToken {} with token: {} and group: {}".format(accToken, token, group)) return accToken LOGGER.info("No AccessToken with token: {} and group: {} found".format(token, group)) return None @app.route("/valid") def _valid(): token = request.headers.get("Token") accToken = verifyAccessToken(token, MONEY) if accToken is not None: return jsonify(accToken.user.toJSON()) accToken = verifyAccessToken(token, BAR) if accToken is not None: return jsonify(accToken.user.toJSON()) accToken = verifyAccessToken(token, GASTRO) if accToken is not None: return jsonify(accToken.user.toJSON()) accToken = verifyAccessToken(token, USER) if accToken is not None: return jsonify(accToken.user.toJSON()) return jsonify({"error": "permission denied"}), 401 @app.route("/login", methods=['POST']) def _login(): """ Login User Nothing to say. Login in User and create an AccessToken for the User. Returns: A JSON-File with createt Token or Errors """ LOGGER.info("Start log in.") data = request.get_json() LOGGER.debug("JSON from request: {}".format(data)) username = data['username'] password = data['password'] LOGGER.info("{} try to log in".format(username)) user = User.query.filter_by(username=username).first() LOGGER.debug("User is {}".format(user)) if user: LOGGER.debug("Check login for User {}".format(user)) if user.login(password): token = accesTokenController.createAccesToken(user) dic = user.toJSON() dic["token"] = 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)) return jsonify({"error": "wrong username"}), 402 @app.route("/getFinanzer") def getFinanzer(): users = User.query.all() dic = {} for user in users: dic[user.userID] = user.toJSON() print(dic) return jsonify(dic)