add token auth

This commit is contained in:
weeman 2021-06-13 19:41:32 +02:00
parent 51a1898176
commit ab792ab2aa
Signed by: weeman
GPG Key ID: 34F0524D4DA694A1
3 changed files with 52 additions and 3 deletions

View File

@ -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.

View File

@ -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"

View File

@ -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/<user_id>/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")