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.

71 lines
1.6 KiB

  1. from functools import wraps
  2. from typing import Any, Callable, NamedTuple
  3. from flask import Blueprint, jsonify, Response, session
  4. from atheneum.authentication import (
  5. generate_token,
  6. require_basic_auth,
  7. require_token_auth
  8. )
  9. api_blueprint = Blueprint(name='api', import_name=__name__, url_prefix='/api')
  10. class APIResponse(NamedTuple):
  11. payload: Any
  12. status: int
  13. def return_json(func: Callable) -> Callable:
  14. """
  15. If an Response object is not returned, jsonify the result and return it
  16. :param func:
  17. :return:
  18. """
  19. @wraps(func)
  20. def decorate(*args, **kwargs):
  21. result = func(*args, **kwargs)
  22. if isinstance(result, Response):
  23. return result
  24. if isinstance(result, APIResponse):
  25. return jsonify(result.payload), result.status
  26. return jsonify(result)
  27. return decorate
  28. @api_blueprint.route('/login', methods=['POST'])
  29. @return_json
  30. @require_basic_auth
  31. def login() -> APIResponse:
  32. """
  33. Get a token for continued authentication
  34. :return: A login token for continued authentication
  35. """
  36. token = generate_token()
  37. return APIResponse({'token': token}, 200)
  38. @api_blueprint.route('/login/bump', methods=['POST'])
  39. @return_json
  40. @require_token_auth
  41. def login_bump() -> APIResponse:
  42. """
  43. Update the user last seen timestamp
  44. :return: A time stamp for the bumped login
  45. """
  46. return APIResponse(None, 200)
  47. @api_blueprint.route('/logout', methods=['POST'])
  48. @return_json
  49. @require_token_auth
  50. def logout() -> APIResponse:
  51. """
  52. logout and delete a token
  53. :return:
  54. """
  55. session.pop('user')
  56. return APIResponse(None, 200)