"""User API blueprint and endpoint definitions.""" from flask import Blueprint, abort, request from atheneum.api.decorators import return_json from atheneum.api.model import APIResponse from atheneum.middleware import authentication_middleware from atheneum.model import User from atheneum.service import user_service, transformation_service, patch_service from atheneum.service.role_service import Role USER_BLUEPRINT = Blueprint( name='user', import_name=__name__, url_prefix='/user') @USER_BLUEPRINT.route('/', methods=['GET']) @return_json @authentication_middleware.require_token_auth @authentication_middleware.require_role(required_role=Role.USER) def get_user(name: str) -> APIResponse: """ Get a user. :return: user if exists, else 404 """ user = user_service.find_by_name(name) if user is not None: return APIResponse(user, 200) return abort(404) @USER_BLUEPRINT.route('/', methods=['PUT']) @return_json @authentication_middleware.require_token_auth @authentication_middleware.require_role(required_role=Role.USER) def patch_user(name: str) -> APIResponse: """ Patch a user. :return: user if patched, 4xx error on patching issue, 404 on nonexistent """ user = user_service.find_by_name(name) if user is not None: user_patch: User = transformation_service.deserialize_model( User, request.json) try: user = patch_service.patch(user, user_patch) except ValueError: return abort(400) return APIResponse(user, 200) return abort(404) @USER_BLUEPRINT.route('/', methods=['POST']) @return_json @authentication_middleware.require_token_auth @authentication_middleware.require_role(required_role=Role.ADMIN) def register_user() -> APIResponse: """ Register a user with the service. :return: The newly registered User """ new_user: User = transformation_service.deserialize_model( User, request.json) registered_user = user_service.register( name=new_user.name, password=None, role=new_user.role ) return APIResponse(payload=registered_user, status=200)