web.py 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. import flask
  2. import pystache
  3. import lc.config as c
  4. import lc.error as e
  5. import lc.model as m
  6. class Endpoint:
  7. def __init__(self):
  8. self.user = None
  9. # try finding the token
  10. token = None
  11. # first check the HTTP headers
  12. if (auth := flask.request.headers.get("Authorization", None)) :
  13. token = auth.split()[1]
  14. # if that fails, check the session
  15. elif flask.session.get("auth", None):
  16. token = flask.session["auth"]
  17. # if that exists and we can deserialize it, then make sure
  18. # it contains a valid user password, too
  19. if token and (payload := c.SERIALIZER.loads(token)):
  20. if "name" not in payload or "password" not in payload:
  21. return
  22. try:
  23. u = m.User.by_slug(payload["name"])
  24. except e.LCException:
  25. return
  26. if u.authenticate(payload["password"]):
  27. self.user = u
  28. def request_data(self, cls):
  29. if flask.request.content_type == "application/json":
  30. return cls.from_json(flask.request.data)
  31. elif flask.request.content_type == "application/x-www-form-urlencoded":
  32. return cls.from_form(flask.request.form)
  33. else:
  34. raise e.BadContentType(flask.request.content_type)
  35. def require_authentication(self, name: str) -> m.User:
  36. """
  37. Check that the currently logged-in user exists and is the
  38. same as the user whose username is given. Raises an exception
  39. otherwise.
  40. """
  41. if not self.user or name != self.user.name:
  42. raise e.BadPermissions()
  43. return m.User.by_slug(name)
  44. def route(self, *args, **kwargs):
  45. try:
  46. if flask.request.method == "POST":
  47. return flask.jsonify(self.api_post(*args, **kwargs))
  48. elif (
  49. flask.request.method in ["GET", "HEAD"]
  50. and flask.request.content_type == "application/json"
  51. ):
  52. return flask.jsonify(self.api_get(*args, **kwargs))
  53. except e.LCException as exn:
  54. return ({"status": exn.http_code(), "error": str(exn)}, exn.http_code())
  55. except e.LCRedirect as exn:
  56. return flask.redirect(exn.to_path())
  57. try:
  58. return self.html(*args, **kwargs)
  59. except e.LCException as exn:
  60. page = render(
  61. "main", title="error", content=f"shit's fucked yo: {exn}", user=None,
  62. )
  63. return (page, exn.http_code())
  64. except e.LCRedirect as exn:
  65. return flask.redirect(exn.to_path())
  66. def endpoint(route):
  67. def do_endpoint(cls):
  68. def func(*args, **kwargs):
  69. return cls().route(*args, **kwargs)
  70. methods = ["GET"]
  71. if "api_post" in dir(cls):
  72. methods.append("POST")
  73. func.__name__ = cls.__name__
  74. return c.app.route(route, methods=methods)(func)
  75. return do_endpoint
  76. LOADER = pystache.loader.Loader(extension="mustache", search_dirs=["templates"])
  77. def render(name, **kwargs):
  78. """Load and use a Mustache template from the project root"""
  79. template = LOADER.load_name(name)
  80. renderer = pystache.Renderer(missing_tags="strict", search_dirs=["templates"])
  81. return renderer.render(template, kwargs)