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