An ebook/comic library service and web client
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

70 lines
2.1 KiB

  1. """User API blueprint and endpoint definitions."""
  2. from flask import Blueprint, abort, request
  3. from atheneum.api.decorators import return_json
  4. from atheneum.api.model import APIResponse
  5. from atheneum.middleware import authentication_middleware
  6. from atheneum.model import User
  7. from atheneum.service import user_service, transformation_service, patch_service
  8. from atheneum.service.role_service import Role
  9. USER_BLUEPRINT = Blueprint(
  10. name='user', import_name=__name__, url_prefix='/user')
  11. @USER_BLUEPRINT.route('/<name>', methods=['GET'])
  12. @return_json
  13. @authentication_middleware.require_token_auth
  14. @authentication_middleware.require_role(required_role=Role.USER)
  15. def get_user(name: str) -> APIResponse:
  16. """
  17. Get a user.
  18. :return: user if exists, else 404
  19. """
  20. user = user_service.find_by_name(name)
  21. if user is not None:
  22. return APIResponse(user, 200)
  23. return abort(404)
  24. @USER_BLUEPRINT.route('/<name>', methods=['PUT'])
  25. @return_json
  26. @authentication_middleware.require_token_auth
  27. @authentication_middleware.require_role(required_role=Role.USER)
  28. def patch_user(name: str) -> APIResponse:
  29. """
  30. Patch a user.
  31. :return: user if patched, 4xx error on patching issue, 404 on nonexistent
  32. """
  33. user = user_service.find_by_name(name)
  34. if user is not None:
  35. user_patch: User = transformation_service.deserialize_model(
  36. User, request.json)
  37. try:
  38. user = patch_service.patch(user, user_patch)
  39. except ValueError:
  40. return abort(400)
  41. return APIResponse(user, 200)
  42. return abort(404)
  43. @USER_BLUEPRINT.route('/', methods=['POST'])
  44. @return_json
  45. @authentication_middleware.require_token_auth
  46. @authentication_middleware.require_role(required_role=Role.ADMIN)
  47. def register_user() -> APIResponse:
  48. """
  49. Register a user with the service.
  50. :return: The newly registered User
  51. """
  52. new_user: User = transformation_service.deserialize_model(
  53. User, request.json)
  54. registered_user = user_service.register(
  55. name=new_user.name,
  56. password=None,
  57. role=new_user.role
  58. )
  59. return APIResponse(payload=registered_user, status=200)