git_brcal/src/server/BreCal/api/shipcalls.py

104 lines
4.1 KiB
Python

from flask import Blueprint, request
from webargs.flaskparser import parser
from marshmallow import Schema, fields, ValidationError
from ..schemas import model
from .. import impl
from ..services.auth_guard import auth_guard, check_jwt
from BreCal.validators.input_validation import validate_posted_shipcall_data, check_if_user_is_bsmd_type
from BreCal.validators.input_validation_shipcall import InputValidationShipcall
from BreCal.database.sql_handler import execute_sql_query_standalone
from BreCal.services.jwt_handler import decode_jwt
from BreCal.validators.validation_error import create_validation_error_response, create_werkzeug_error_response, create_dynamic_exception_response
from . import verify_if_request_is_json
import logging
import json
import traceback
import werkzeug
bp = Blueprint('shipcalls', __name__)
@bp.route('/shipcalls', methods=['get'])
@auth_guard() # no restriction by role
def GetShipcalls():
try:
if 'Authorization' in request.headers:
token = request.headers.get('Authorization') # see impl/login to see the token encoding, which is a JWT token.
"""
from BreCal.services.jwt_handler import decode_jwt
jwt = token.split('Bearer ')[1] # string key
payload = decode_jwt(jwt) # dictionary, which includes 'id' (user id) and 'participant_id'
# oneline:
payload = decode_jwt(request.headers.get("Authorization").split("Bearer ")[-1])
"""
payload = decode_jwt(request.headers.get("Authorization").split("Bearer ")[-1])
options = {}
options["past_days"] = request.args.get("past_days", default=1, type=int)
options["participant_id"] = payload["participant_id"]
return impl.shipcalls.GetShipcalls(options)
else:
return create_dynamic_exception_response(ex=None, status_code=403, message="not authenticated")
except Exception as ex:
return create_dynamic_exception_response(ex=ex, status_code=400)
@bp.route('/shipcalls', methods=['post'])
@auth_guard() # no restriction by role
def PostShipcalls():
try:
verify_if_request_is_json(request)
content = request.get_json(force=True)
loadedModel = model.ShipcallSchema().load(data=content, many=False, partial=True)
# read the user data from the JWT token (set when login is performed)
user_data = check_jwt()
# validate the posted shipcall data & the user's authority
InputValidationShipcall.evaluate_post_data(user_data, loadedModel, content)
return impl.shipcalls.PostShipcalls(loadedModel)
except ValidationError as ex:
return create_validation_error_response(ex=ex, status_code=400)
except Exception as ex:
logging.error(traceback.format_exc())
return create_dynamic_exception_response(ex=ex, status_code=400, message="bad format")
@bp.route('/shipcalls', methods=['put'])
@auth_guard() # no restriction by role
def PutShipcalls():
try:
verify_if_request_is_json(request)
content = request.get_json(force=True)
loadedModel = model.ShipcallSchema().load(data=content, many=False, partial=True)
# read the user data from the JWT token (set when login is performed)
user_data = check_jwt()
if not InputValidationShipcall.exists_shipcall_by_id(loadedModel.get("id")):
return create_dynamic_exception_response(ex=None, status_code=404, message="no shipcall found with the provided id")
# validate the PUT shipcall data and the user's authority
InputValidationShipcall.evaluate_put_data(user_data, loadedModel, content)
return impl.shipcalls.PutShipcalls(loadedModel, content)
except ValidationError as ex:
return create_validation_error_response(ex=ex, status_code=400)
except werkzeug.exceptions.Forbidden as ex:
return create_werkzeug_error_response(ex=ex, status_code=403)
except Exception as ex:
logging.error(traceback.format_exc())
return create_dynamic_exception_response(ex=None, status_code=400, message="bad format")