From ab792ab2aa936f3fd8c32cbfd35f3c18cba36296 Mon Sep 17 00:00:00 2001 From: Michael Weimann Date: Sun, 13 Jun 2021 19:41:32 +0200 Subject: [PATCH] add token auth --- README.md | 7 +++++++ ki/models.py | 6 ++++++ ki/routes.py | 42 +++++++++++++++++++++++++++++++++++++++--- 3 files changed, 52 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 0c1088c..d400144 100644 --- a/README.md +++ b/README.md @@ -52,6 +52,13 @@ curl -s \ http://localhost:5000/users/login | jq ``` +``` +curl -s \ + -D "/dev/stderr" \ + -H "Authorization: Bearer 22e6c5fc-8a5a-440e-b1f4-018deb9fd24e" \ + http://localhost:5000/users/1/profile +``` + ### Produktionsumgebung Für die Produktionsumgebung wird [waitress](https://docs.pylonsproject.org/projects/waitress/en/latest/) benutzt. diff --git a/ki/models.py b/ki/models.py index f9a6c20..002f4bd 100644 --- a/ki/models.py +++ b/ki/models.py @@ -24,6 +24,12 @@ class User(db.Model): skills = relationship("UserSkill", back_populates="user") languages = relationship("UserLanguage", back_populates="user") + def to_dict(self): + return { + "id": self.id, + "nickname": self.nickname + } + class Token(db.Model): __tablename__ = "token" diff --git a/ki/routes.py b/ki/routes.py index f06b2c4..3cd76e4 100644 --- a/ki/routes.py +++ b/ki/routes.py @@ -1,11 +1,35 @@ import os -from flask import jsonify, make_response, request, send_file +from flask import g, make_response, request, send_file +from functools import wraps from ki.auth import auth -from ki.models import Language, Skill +from ki.models import Language, Skill, Token, User from app import app +def token_auth(func): + @wraps(func) + def _token_auth(*args, **kwargs): + auth_header = request.headers.get("Authorization") + + if (auth_header is None): + return make_response({}, 401) + + if not auth_header.startswith("Bearer"): + return make_response({}, 401) + + token = Token.query.filter(Token.token == auth_header[7:]).first() + + if token is None: + return make_response({}, 403) + + g.user = token.user + + return func(*args, **kwargs) + + return _token_auth + + def models_to_list(models): models_list = [] @@ -65,9 +89,10 @@ def handle_icon_request(model, id, path): def hello_world(): return "KI" + @app.route("/users/login", methods=["POST"]) def login(): - username = request.json.get("username", "") + username = request.json.get("username", "") password = request.json.get("password", "") token = auth(username, password) @@ -77,6 +102,17 @@ def login(): return make_response({"token": token.token}) +@app.route("/users//profile") +@token_auth +def get_user_profile(user_id): + user = User.query.filter(User.id == int(user_id)).first() + + if user is None: + return make_response({}, 404) + + return make_response({"user": user.to_dict()}) + + @app.route("/skills") def get_skills(): return handle_completion_request(Skill, "skills")