cake-erp-challenge/api/util/authentication.py

26 lines
870 B
Python
Raw Permalink Normal View History

2021-10-18 23:43:26 -04:00
from functools import wraps
from flask import request
from api.app import app
from .fetch import get_trainer_by_nick_fail, NotFound
2021-10-19 00:06:08 -04:00
from api.views.errors import AuthenticationFailure
2021-10-18 23:43:26 -04:00
import jwt
2021-10-18 23:45:21 -04:00
# autenticação do trainer (decorator)
2021-10-18 23:43:26 -04:00
def token_required(f):
@wraps(f)
def decorated(*args, **kwargs):
try:
token = request.headers["authorization"]
data = jwt.decode(token, app.config["SECRET_KEY"], algorithms=["HS256"])
trainer = get_trainer_by_nick_fail(data["username"])
except (TypeError, KeyError):
return AuthenticationFailure("JWT token required")
except NotFound:
return AuthenticationFailure("Trainer not found")
except:
return AuthenticationFailure("JWT token is invalid or expired")
return f(trainer, *args, **kwargs)
return decorated