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.
 
 
 
 
 

171 lines
5.2 KiB

  1. #!/usr/bin/env python
  2. from __future__ import unicode_literals, absolute_import
  3. """Flask app for Rophako."""
  4. from flask import (Flask, g, request, session, render_template, send_file,
  5. abort, redirect)
  6. from flask_sslify import SSLify
  7. import jinja2
  8. import os.path
  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.plugin import load_plugin
  26. from rophako.log import logger
  27. #import rophako.model.tracking as Tracking
  28. import rophako.utils
  29. # String escaping for the secret key (processes \ escapes properly), the
  30. # escape encoding name varies between Python 2 and 3.
  31. string_escape = "string_escape" if sys.version_info[0] == 2 \
  32. else "unicode_escape"
  33. app.DEBUG = Config.site.debug == "true"
  34. app.secret_key = bytes(Config.security.secret_key.encode("utf-8")) \
  35. .decode(string_escape)
  36. # Security?
  37. if Config.security.force_ssl == "true":
  38. app.config['SESSION_COOKIE_SECURE'] = True
  39. sslify = SSLify(app)
  40. # Load all the built-in essential plugins.
  41. load_plugin("rophako.modules.admin")
  42. load_plugin("rophako.modules.account")
  43. # Custom Jinja handler to support custom- and default-template folders for
  44. # rendering templates.
  45. template_paths = [
  46. Config.site.site_root, # Site specific.
  47. "rophako/www", # Default/fall-back
  48. ]
  49. template_paths.extend(BLUEPRINT_PATHS)
  50. app.jinja_loader = jinja2.ChoiceLoader([ jinja2.FileSystemLoader(x) for x in template_paths])
  51. app.jinja_env.globals["csrf_token"] = rophako.utils.generate_csrf_token
  52. app.jinja_env.globals["include_page"] = rophako.utils.include
  53. app.jinja_env.globals["settings"] = lambda: Config
  54. # Preload the emoticon data.
  55. import rophako.model.emoticons as Emoticons
  56. Emoticons.load_theme()
  57. @app.before_request
  58. def before_request():
  59. """Called before all requests. Initialize global template variables."""
  60. # Default template vars.
  61. g.info = rophako.utils.default_vars()
  62. # Default session vars.
  63. if not "login" in session:
  64. session.update(g.info["session"])
  65. # CSRF protection.
  66. if request.method == "POST":
  67. token = session.pop("_csrf", None)
  68. if not token or str(token) != str(request.form.get("token")):
  69. abort(403)
  70. # Refresh their login status from the DB.
  71. if session["login"]:
  72. import rophako.model.user as User
  73. if not User.exists(uid=session["uid"]):
  74. # Weird! Log them out.
  75. from rophako.modules.account import logout
  76. logout()
  77. return
  78. db = User.get_user(uid=session["uid"])
  79. session["username"] = db["username"]
  80. session["name"] = db["name"]
  81. session["role"] = db["role"]
  82. # Copy session params into g.info. The only people who should touch the
  83. # session are the login/out pages.
  84. for key in session:
  85. g.info["session"][key] = session[key]
  86. @app.context_processor
  87. def after_request():
  88. """Called just before render_template. Inject g.info into the template vars."""
  89. return g.info
  90. @app.route("/<path:path>")
  91. def catchall(path):
  92. """The catch-all path handler. If it exists in the www folders, it's sent,
  93. otherwise we give the 404 error page."""
  94. if path.endswith("/"):
  95. path = path.strip("/") # Remove trailing slashes.
  96. return redirect(path)
  97. # Search for this file.
  98. for root in [Config.site.site_root, "rophako/www"]:
  99. abspath = os.path.abspath("{}/{}".format(root, path))
  100. if os.path.isfile(abspath):
  101. return send_file(abspath)
  102. # The exact file wasn't found, look for some extensions and index pages.
  103. suffixes = [
  104. ".html",
  105. "/index.html",
  106. ".md", # Markdown formatted pages.
  107. "/index.md",
  108. ]
  109. for suffix in suffixes:
  110. if not "." in path and os.path.isfile(abspath + suffix):
  111. # HTML, or Markdown?
  112. if suffix.endswith(".html"):
  113. return rophako.utils.template(path + suffix)
  114. else:
  115. return rophako.utils.markdown_template(abspath + suffix)
  116. return not_found("404")
  117. @app.route("/")
  118. def index():
  119. return catchall("index")
  120. @app.errorhandler(Exception)
  121. def catch_exception(error):
  122. """Catch unexpected Python exceptions and e-mail them out."""
  123. logger.error("INTERNAL SERVER ERROR: {}".format(str(error)))
  124. # E-mail it out.
  125. rophako.utils.handle_exception(error)
  126. return rophako.utils.template("errors/500.html")
  127. @app.errorhandler(404)
  128. def not_found(error):
  129. return render_template('errors/404.html', **g.info), 404
  130. @app.errorhandler(403)
  131. def forbidden(error):
  132. return render_template('errors/403.html', **g.info), 403