web.py 7.9 KB

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