web.py 7.9 KB

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