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.

76 lines
2.3 KiB

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