flaschengeist/geruecht/routes.py

75 lines
2.7 KiB
Python
Raw Normal View History

from geruecht import app, db, accesTokenController, MONEY, BAR, USER, GASTRO, LOGGER
from geruecht import ldapController as ldap
2019-04-11 21:56:55 +00:00
from geruecht.model.user import User
from flask import request, jsonify
def login(user, password):
return user.login(password)
2019-04-23 22:08:25 +00:00
@app.route("/valid")
def _valid():
2019-04-23 22:08:25 +00:00
token = request.headers.get("Token")
accToken = accesTokenController.validateAccessToken(token, MONEY)
if accToken:
2019-04-23 22:08:25 +00:00
return jsonify(accToken.user.toJSON())
accToken = accesTokenController.validateAccessToken(token, BAR)
if accToken:
2019-04-23 22:08:25 +00:00
return jsonify(accToken.user.toJSON())
accToken = accesTokenController.validateAccessToken(token, GASTRO)
if accToken:
2019-04-23 22:08:25 +00:00
return jsonify(accToken.user.toJSON())
accToken = accesTokenController.validateAccessToken(token, USER)
if accToken:
return jsonify(accToken.user.toJSON())
return jsonify({"error": "permission denied"}), 401
2019-04-11 21:56:55 +00:00
@app.route("/login", methods=['POST'])
def _login():
2019-04-17 12:46:46 +00:00
""" Login User
2019-04-17 12:46:46 +00:00
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.")
2019-04-11 21:56:55 +00:00
data = request.get_json()
2019-12-22 21:27:39 +00:00
print(data)
LOGGER.debug("JSON from request: {}".format(data))
2019-04-11 21:56:55 +00:00
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")
2019-12-22 21:27:39 +00:00
groups = ldap.getGroup(username)
LOGGER.info("Get userdata from LDAP")
user_data = ldap.getUserData(username)
2019-12-22 21:27:39 +00:00
user_data['group'] = groups
LOGGER.info('Insert user {} into database')
db.insertUser(user_data)
except Exception as err:
2019-12-22 21:27:39 +00:00
return jsonify({"error": str(err)}), 401
LOGGER.info("{} try to log in".format(username))
user = db.getUser(username)
LOGGER.debug("User is {}".format(user))
2019-04-11 21:56:55 +00:00
if user:
LOGGER.debug("Check login for User {}".format(user))
if login(user, password):
2019-04-11 21:56:55 +00:00
token = accesTokenController.createAccesToken(user)
dic = user.toJSON()
dic["token"] = token
2019-12-22 21:27:39 +00:00
dic["accessToken"] = token
LOGGER.info("User {} success login.".format(username))
return jsonify(dic)
else:
LOGGER.info("User {} failed login.".format(username))
2019-04-11 21:56:55 +00:00
return jsonify({"error": "wrong password"}), 401
LOGGER.info("User {} does not exist.".format(username))
return jsonify({"error": "wrong username"}), 402