web.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. import flask
  2. import pystache
  3. from typing import TypeVar, Type
  4. import lc.config as c
  5. import lc.error as e
  6. import lc.model as m
  7. import lc.request as r
  8. T = TypeVar("T", bound=r.Request)
  9. class Endpoint:
  10. def __init__(self):
  11. self.user = None
  12. # try finding the token
  13. token = None
  14. # first check the HTTP headers
  15. if (auth := flask.request.headers.get("Authorization", None)) :
  16. token = auth.split()[1]
  17. # if that fails, check the session
  18. elif flask.session.get("auth", None):
  19. token = flask.session["auth"]
  20. # if that exists and we can deserialize it, then make sure
  21. # it contains a valid user password, too
  22. if token and (payload := c.serializer.loads(token)):
  23. if "name" not in payload or "password" not in payload:
  24. return
  25. try:
  26. u = m.User.by_slug(payload["name"])
  27. except e.LCException:
  28. return
  29. if u.authenticate(payload["password"]):
  30. self.user = u
  31. def api_ok(self, redirect: str, data: dict = {"status": "ok"}):
  32. if flask.request.content_type == "application/json":
  33. return flask.jsonify(data)
  34. elif flask.request.content_type == "application/x-www-form-urlencoded":
  35. raise e.LCRedirect(redirect)
  36. else:
  37. raise e.BadContentType(flask.request.content_type or "unknown")
  38. def request_data(self, cls: Type[T]) -> T:
  39. """Construct a Request model from either a JSON payload or a urlencoded payload"""
  40. if flask.request.content_type == "application/json":
  41. return cls.from_json(flask.request.data)
  42. elif flask.request.content_type == "application/x-www-form-urlencoded":
  43. return cls.from_form(flask.request.form)
  44. else:
  45. raise e.BadContentType(flask.request.content_type or "unknown")
  46. def require_authentication(self, name: str) -> m.User:
  47. """
  48. Check that the currently logged-in user exists and is the
  49. same as the user whose username is given. Raises an exception
  50. otherwise.
  51. """
  52. if not self.user or name != self.user.name:
  53. raise e.BadPermissions()
  54. return self.user
  55. def route(self, *args, **kwargs):
  56. """Forward to the appropriate routing method"""
  57. try:
  58. if flask.request.method == "POST":
  59. # all POST methods are "API methods": if we want to
  60. # display information in response to a post, then we
  61. # should redirect to the page where that information
  62. # can be viewed instead of returning that
  63. # information. (I think.)
  64. return self.api_post(*args, **kwargs)
  65. elif (
  66. flask.request.method in ["GET", "HEAD"]
  67. and flask.request.content_type == "application/json"
  68. ):
  69. # Here we're distinguishing between an API GET (i.e. a
  70. # client trying to get JSON data about an endpoint)
  71. # versus a user-level GET (i.e. a user in a browser.)
  72. # I like using the HTTP headers to distinguish these
  73. # cases, while other APIs tend to have a separate /api
  74. # endpoint to do this.
  75. return flask.jsonify(self.api_get(*args, **kwargs))
  76. # if an exception arose from an "API method", then we should
  77. # report it as JSON
  78. except e.LCException as exn:
  79. return ({"status": exn.http_code(), "error": str(exn)}, exn.http_code())
  80. # also maybe we tried to redirect, so just do that
  81. except e.LCRedirect as exn:
  82. return flask.redirect(exn.to_path())
  83. # if we're here, it means we're just trying to get a typical
  84. # HTML request.
  85. try:
  86. return self.html(*args, **kwargs)
  87. except e.LCException as exn:
  88. page = render(
  89. "main", title="error", content=f"shit's fucked yo: {exn}", user=None,
  90. )
  91. return (page, exn.http_code())
  92. except e.LCRedirect as exn:
  93. return flask.redirect(exn.to_path())
  94. # Decorators result in some weird code in Python, especially 'cause it
  95. # doesn't make higher-order functions terse. Let's break this down a
  96. # bit. This out method, `endpoint`, takes the route...
  97. def endpoint(route: str):
  98. """Route an endpoint using our semi-smart routing machinery"""
  99. # but `endpoint` returns another function which is going to be
  100. # called with the result of the definition after it. The argument
  101. # to what we're calling `do_endpoint` here is going to be the
  102. # class object defined afterwards.
  103. def do_endpoint(endpoint_class: Type[Endpoint]):
  104. # we'll just make that explicit here
  105. assert Endpoint in endpoint_class.__bases__
  106. # finally, we need a function that we'll give to Flask in
  107. # order to actually dispatch to. This is the actual routing
  108. # function, which is why it just creates an instance of the
  109. # endpoint provided above and calls the `route` method on it
  110. def func(*args, **kwargs):
  111. return endpoint_class().route(*args, **kwargs)
  112. # use reflection over the methods defined by the endpoint
  113. # class to decide if it needs to accept POST requests or not.
  114. methods = ["GET"]
  115. if "api_post" in dir(endpoint_class):
  116. methods.append("POST")
  117. # this is just for making error messages nicer
  118. func.__name__ = endpoint_class.__name__
  119. # finally, use the Flask routing machinery to register our callback
  120. return c.app.route(route, methods=methods)(func)
  121. return do_endpoint
  122. LOADER = pystache.loader.Loader(extension="mustache", search_dirs=["templates"])
  123. def render(name: str, **kwargs) -> str:
  124. """Load and use a Mustache template from the project root"""
  125. template = LOADER.load_name(name)
  126. renderer = pystache.Renderer(missing_tags="strict", search_dirs=["templates"])
  127. return renderer.render(template, kwargs)