web.py 6.7 KB

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