From 27b8fcf215081a585f44b10675af93cd248c254a Mon Sep 17 00:00:00 2001 From: Augusto Gunsch Date: Tue, 19 Oct 2021 00:43:26 -0300 Subject: [PATCH] Pequena limpeza --- api/config.py | 2 +- api/routes/routes.py | 7 +++---- api/views/authentication.py | 25 +++++++++++++++++++++++++ api/views/{helper.py => fetch.py} | 29 +---------------------------- api/views/pokemon_owned.py | 2 +- 5 files changed, 31 insertions(+), 34 deletions(-) create mode 100644 api/views/authentication.py rename api/views/{helper.py => fetch.py} (63%) diff --git a/api/config.py b/api/config.py index 4f7d304..93f1e64 100644 --- a/api/config.py +++ b/api/config.py @@ -2,6 +2,6 @@ import string import random random_str = string.ascii_letters + string.digits + string.ascii_uppercase -SECRET_KEY = ''.join(random.choice(random_str) for i in range(12)) +SECRET_KEY = ''.join(random.choice(random_str) for _ in range(12)) SQLALCHEMY_DATABASE_URI = 'sqlite:///database.db' SQLALCHEMY_TRACK_MODIFICATIONS = False diff --git a/api/routes/routes.py b/api/routes/routes.py index 9bbc2b2..70fc7c2 100644 --- a/api/routes/routes.py +++ b/api/routes/routes.py @@ -1,6 +1,5 @@ from api.app import app -from api.views import trainer, pokemon_owned, helper, errors -from flask import request +from api.views import trainer, pokemon_owned, authentication, errors import asyncio @app.route("/trainer/", methods=["GET"]) @@ -24,7 +23,7 @@ def route_get_pokemons_owned(trainerId): return asyncio.run(pokemon_owned.get_pokemons_owned(trainerId)) @app.route("/trainer//pokemon", methods=["POST"]) -@helper.token_required +@authentication.token_required def route_post_pokemons_owned(trainer, trainerId): if trainer.id != trainerId: return errors.ForbiddenError("Trainer id mismatch") @@ -35,7 +34,7 @@ def route_get_pokemon_owned(trainerId, pokemonId): return pokemon_owned.get_pokemon_owned(trainerId, pokemonId) @app.route("/trainer//pokemon/", methods=["DELETE"]) -@helper.token_required +@authentication.token_required def route_delete_pokemon_owned(trainer, trainerId, pokemonId): if trainer.id != trainerId: return errors.ForbiddenError("Trainer id mismatch") diff --git a/api/views/authentication.py b/api/views/authentication.py new file mode 100644 index 0000000..768fd64 --- /dev/null +++ b/api/views/authentication.py @@ -0,0 +1,25 @@ +from functools import wraps +from flask import request +from api.app import app +from .fetch import get_trainer_by_nick_fail, NotFound +from .errors import AuthenticationFailure +import jwt + +# authenticação do trainer (decorator) +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 + diff --git a/api/views/helper.py b/api/views/fetch.py similarity index 63% rename from api/views/helper.py rename to api/views/fetch.py index 843ac3f..73f7054 100644 --- a/api/views/helper.py +++ b/api/views/fetch.py @@ -1,15 +1,6 @@ -from functools import wraps -from flask import request from api.models.trainer import Trainer -from .errors import AuthenticationFailure -from api.app import app import requests import json -import jwt - -class HTTPError(Exception): - def __init__(self, message): - self.message = message class NotFound(Exception): def __init__(self, message): @@ -33,25 +24,7 @@ def get_trainer_by_nick_fail(nickname): def get_pokemon_fail(trainer, id): return get_or_not_found(lambda : trainer.pokemons_list.filter_by(id=id).one()) -# authenticação do trainer (decorator) -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 - -# helpers internos +# helper interno def cant_fetch_error(pokemon): raise NotFound("Could not fetch data for pokemon with id {}".format(pokemon.pokemon_id)) diff --git a/api/views/pokemon_owned.py b/api/views/pokemon_owned.py index 6481a16..32a0b78 100644 --- a/api/views/pokemon_owned.py +++ b/api/views/pokemon_owned.py @@ -2,7 +2,7 @@ from api.models.pokemon_owned import pokemon_owned_schema, pokemon_owned_schemas from api.app import db from .parse_args import parse_limit, parse_offset, ParsingException, parse_json_obj from .errors import ParsingError, FetchError, ConflictingResources -from .helper import * +from .fetch import * from aiohttp import ClientSession import asyncio from sqlalchemy.exc import IntegrityError