web.py 6.9 KB

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