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.
 
 
 
 
 

183 lines
5.5 KiB

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