A Python content management system designed for kirsle.net featuring a blog, comments and photo albums. https://rophako.kirsle.net/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

178 lines
5.3KB

  1. #!/usr/bin/env python
  2. """Flask app for Rophako."""
  3. from flask import Flask, g, request, session, render_template, send_file, abort
  4. from flask_sslify import SSLify
  5. import jinja2
  6. import os.path
  7. import time
  8. import sys
  9. # Get the Flask app object ready right away so other modules can import it
  10. # without getting a circular import error.
  11. app = Flask(__name__,
  12. static_url_path="/.static",
  13. )
  14. # We use a custom Jinja loader to support multiple template paths for custom
  15. # and default templates. The base list of template paths to check includes
  16. # your custom path (from config.SITE_ROOT), the "rophako/www" path for normal
  17. # pages, and then the blueprint paths for all imported plugins. This list will
  18. # be extended while blueprints are being loaded and passed in below to the
  19. # jinja2.ChoiceLoader.
  20. BLUEPRINT_PATHS = []
  21. from rophako.settings import Config
  22. Config.load_settings()
  23. Config.load_plugins()
  24. from rophako import __version__
  25. from rophako.plugin import load_plugin
  26. from rophako.log import logger
  27. import rophako.model.tracking as Tracking
  28. import rophako.utils
  29. app.DEBUG = Config.site.debug == "true"
  30. app.secret_key = Config.security.secret_key.decode("string_escape")
  31. # Security?
  32. if Config.security.force_ssl == "true":
  33. app.config['SESSION_COOKIE_SECURE'] = True
  34. sslify = SSLify(app)
  35. # Load all the built-in essential plugins.
  36. load_plugin("rophako.modules.admin")
  37. load_plugin("rophako.modules.account")
  38. # Custom Jinja handler to support custom- and default-template folders for
  39. # rendering templates.
  40. template_paths = [
  41. Config.site.site_root, # Site specific.
  42. "rophako/www", # Default/fall-back
  43. ]
  44. template_paths.extend(BLUEPRINT_PATHS)
  45. app.jinja_loader = jinja2.ChoiceLoader([ jinja2.FileSystemLoader(x) for x in template_paths])
  46. app.jinja_env.globals["csrf_token"] = rophako.utils.generate_csrf_token
  47. app.jinja_env.globals["include_page"] = rophako.utils.include
  48. # Preload the emoticon data.
  49. import rophako.model.emoticons as Emoticons
  50. Emoticons.load_theme()
  51. @app.before_request
  52. def before_request():
  53. """Called before all requests. Initialize global template variables."""
  54. # Default template vars.
  55. g.info = {
  56. "time": time.time(),
  57. "app": {
  58. "name": "Rophako",
  59. "version": __version__,
  60. "python_version": "{}.{}".format(sys.version_info.major, sys.version_info.minor),
  61. "author": "Noah Petherbridge",
  62. "photo_url": Config.photo.root_public,
  63. },
  64. "uri": request.path,
  65. "session": {
  66. "login": False, # Not logged in, until proven otherwise.
  67. "username": "guest",
  68. "uid": 0,
  69. "name": "Guest",
  70. "role": "user",
  71. },
  72. "tracking": Tracking.track_visit(request, session),
  73. }
  74. # Default session vars.
  75. if not "login" in session:
  76. session.update(g.info["session"])
  77. # CSRF protection.
  78. if request.method == "POST":
  79. token = session.pop("_csrf", None)
  80. if not token or str(token) != str(request.form.get("token")):
  81. abort(403)
  82. # Refresh their login status from the DB.
  83. if session["login"]:
  84. import rophako.model.user as User
  85. if not User.exists(uid=session["uid"]):
  86. # Weird! Log them out.
  87. from rophako.modules.account import logout
  88. logout()
  89. return
  90. db = User.get_user(uid=session["uid"])
  91. session["username"] = db["username"]
  92. session["name"] = db["name"]
  93. session["role"] = db["role"]
  94. # Copy session params into g.info. The only people who should touch the
  95. # session are the login/out pages.
  96. for key in session:
  97. g.info["session"][key] = session[key]
  98. @app.context_processor
  99. def after_request():
  100. """Called just before render_template. Inject g.info into the template vars."""
  101. return g.info
  102. @app.route("/<path:path>")
  103. def catchall(path):
  104. """The catch-all path handler. If it exists in the www folders, it's sent,
  105. otherwise we give the 404 error page."""
  106. # Search for this file.
  107. for root in [Config.site.site_root, "rophako/www"]:
  108. abspath = os.path.abspath("{}/{}".format(root, path))
  109. if os.path.isfile(abspath):
  110. return send_file(abspath)
  111. # The exact file wasn't found, look for some extensions and index pages.
  112. suffixes = [
  113. ".html",
  114. "/index.html",
  115. ".md", # Markdown formatted pages.
  116. "/index.md",
  117. ]
  118. for suffix in suffixes:
  119. if not "." in path and os.path.isfile(abspath + suffix):
  120. # HTML, or Markdown?
  121. if suffix.endswith(".html"):
  122. return rophako.utils.template(path + suffix)
  123. else:
  124. return rophako.utils.markdown_template(abspath + suffix)
  125. return not_found("404")
  126. @app.route("/")
  127. def index():
  128. return catchall("index")
  129. @app.errorhandler(Exception)
  130. def catch_exception(error):
  131. """Catch unexpected Python exceptions and e-mail them out."""
  132. logger.error("INTERNAL SERVER ERROR: {}".format(str(error)))
  133. # E-mail it out.
  134. rophako.utils.handle_exception(error)
  135. return rophako.utils.template("errors/500.html")
  136. @app.errorhandler(404)
  137. def not_found(error):
  138. return render_template('errors/404.html', **g.info), 404
  139. @app.errorhandler(403)
  140. def forbidden(error):
  141. return render_template('errors/403.html', **g.info), 403