cake-erp-challenge/api/views/trainer.py

113 lines
3.4 KiB
Python
Raw Normal View History

2021-10-17 17:59:27 -04:00
from sqlalchemy.exc import NoResultFound, IntegrityError
from api.models.trainer import Trainer, trainer_schema, trainer_schemas, InvalidTeam
from api.app import db
from api.app import app
2021-10-17 17:59:27 -04:00
from flask import request, jsonify
2021-10-18 15:49:47 -04:00
from .errors import *
from .parse_args import parse_limit, parse_offset, ParsingException, parse_json_obj
from werkzeug.security import check_password_hash
import datetime
import jwt
2021-10-17 17:59:27 -04:00
def get_trainer(id):
try:
return trainer_schema.dump(Trainer.query.get(id))
except:
2021-10-18 15:49:47 -04:00
return ("", 404)
2021-10-17 17:59:27 -04:00
def get_trainers():
args = request.args
try:
2021-10-18 15:49:47 -04:00
limit = parse_limit()
offset = parse_offset()
except ParsingException as e:
return ParsingError(e.message)
2021-10-17 17:59:27 -04:00
nickname = args.get("nickname", "")
nickname_contains = args.get("nickname_contains", "")
try:
if nickname:
if nickname_contains:
return ConflictingParameters("nickname and nickname_contains are mutually exclusive")
2021-10-17 17:59:27 -04:00
query = Trainer.query.filter_by(nickname=nickname).limit(limit).offset(offset)
2021-10-17 17:59:27 -04:00
return trainer_schemas.dumps(query.all())
else: # se nickname_contains também está vazio, retornará todos trainers
pattern = '%'+nickname_contains+'%'
query = Trainer.query.filter(Trainer.nickname.like(pattern)).limit(limit).offset(offset)
2021-10-17 17:59:27 -04:00
return trainer_schemas.dumps(query.all())
except NoResultFound:
return jsonify([])
def get_trainer_by_email(email):
try:
return Trainer.query.filter_by(email=email).one()
except:
return None
2021-10-17 17:59:27 -04:00
def post_trainer():
try:
2021-10-18 15:49:47 -04:00
json = parse_json_obj()
2021-10-17 17:59:27 -04:00
nickname = json["nickname"]
first_name = json["first_name"]
last_name = json["last_name"]
email = json["email"]
password = json["password"]
team = json["team"]
trainer = Trainer(
nickname=nickname,
first_name=first_name,
last_name=last_name,
email=email,
password=password,
team=team
)
db.session.add(trainer)
db.session.commit()
return trainer_schema.dump(trainer)
2021-10-18 15:49:47 -04:00
except ParsingException as e:
return ParsingError(e.message)
2021-10-17 17:59:27 -04:00
except InvalidTeam:
return ParsingError("Field team is invalid")
2021-10-17 17:59:27 -04:00
except KeyError:
return ParsingError("Missing JSON object fields")
2021-10-17 17:59:27 -04:00
except IntegrityError:
2021-10-18 15:49:47 -04:00
return ConflictingResources("Trainer with the same nickname or email already exists")
def auth_trainer():
try:
2021-10-18 15:49:47 -04:00
auth = parse_json_obj()
email = auth["email"]
password = auth["password"]
2021-10-18 15:49:47 -04:00
except ParsingException as e:
return ParsingError(e.message)
except KeyError:
return AuthenticationFailure("Login required")
trainer = get_trainer_by_email(email)
if not trainer:
return AuthenticationFailure("Trainer not found")
if trainer and check_password_hash(trainer.password, password):
token = jwt.encode(
{
"username": trainer.nickname,
"exp": datetime.datetime.now() + datetime.timedelta(hours=12)
},
2021-10-18 15:49:47 -04:00
app.config["SECRET_KEY"], algorithm="HS256")
return jsonify(
{
"id": trainer.id,
"token": token
})
return AuthenticationFailure("Invalid login")