web.py 8.0 KB

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