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.

app.py 5.5KB

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