web.py 7.7 KB

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