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.

308 lines
9.2KB

  1. # -*- coding: utf-8 -*-
  2. from flask import (g, session, request, render_template, flash, redirect,
  3. url_for, current_app)
  4. from functools import wraps
  5. import codecs
  6. import uuid
  7. import datetime
  8. import time
  9. import re
  10. import importlib
  11. import smtplib
  12. import markdown
  13. import json
  14. import urlparse
  15. import traceback
  16. import socket
  17. from rophako.log import logger
  18. from rophako.settings import Config
  19. def login_required(f):
  20. """Wrapper for pages that require a logged-in user."""
  21. @wraps(f)
  22. def decorated_function(*args, **kwargs):
  23. if not g.info["session"]["login"]:
  24. session["redirect_url"] = request.url
  25. flash("You must be logged in to do that!")
  26. return redirect(url_for("account.login"))
  27. return f(*args, **kwargs)
  28. return decorated_function
  29. def admin_required(f):
  30. """Wrapper for admin-only pages. Implies login_required."""
  31. @wraps(f)
  32. def decorated_function(*args, **kwargs):
  33. if not g.info["session"]["login"]:
  34. # Not even logged in?
  35. session["redirect_url"] = request.url
  36. flash("You must be logged in to do that!")
  37. return redirect(url_for("account.login"))
  38. if g.info["session"]["role"] != "admin":
  39. logger.warning("User tried to access an Admin page, but wasn't allowed!")
  40. return redirect(url_for("index"))
  41. return f(*args, **kwargs)
  42. return decorated_function
  43. def ajax_response(status, msg):
  44. """Return a standard JSON response."""
  45. status = "ok" if status else "error"
  46. return json.dumps(dict(
  47. status=status,
  48. msg=msg,
  49. ))
  50. def template(name, **kwargs):
  51. """Render a template to the browser."""
  52. html = render_template(name, **kwargs)
  53. # Get the elapsed time for the request.
  54. time_elapsed = "%.03f" % (time.time() - g.info["time"])
  55. html = re.sub(r'\%time_elapsed\%', time_elapsed, html)
  56. return html
  57. def markdown_template(path):
  58. """Render a Markdown page to the browser.
  59. The first line in the Markdown page should be an H1 header beginning with
  60. the # sign. This will set the page's <title> to match the header value.
  61. Pages can include lines that begin with the keyword `:meta` to apply
  62. meta information to control the Markdown parser. Supported meta lines
  63. and examples:
  64. To 'blacklist' extensions, i.e. to turn off line breaks inside a paragraph
  65. getting translated into a <br> tag (the key is the minus sign):
  66. :meta extensions -nl2br
  67. To add an extension, i.e. the abbreviations from PHP Markdown Extra:
  68. :meta extensions abbr"""
  69. # The path is the absolute path to the Markdown file, so open it directly.
  70. fh = codecs.open(path, "r", "utf-8")
  71. body = fh.read()
  72. fh.close()
  73. # Look for meta information in the file.
  74. lines = body.split("\n")
  75. content = list() # New set of lines, without meta info.
  76. extensions = set()
  77. blacklist = set() # Blacklisted extensions
  78. for line in lines:
  79. if line.startswith(":meta"):
  80. parts = line.split(" ")
  81. if len(parts) >= 3:
  82. # Supported meta commands.
  83. if parts[1] == "extensions":
  84. # Extension toggles.
  85. for extension in parts[2:]:
  86. if extension.startswith("-"):
  87. extension = extension[1:]
  88. blacklist.add(extension)
  89. else:
  90. extensions.add(extension)
  91. else:
  92. content.append(line)
  93. # Extract a title from the first line.
  94. first = content[0]
  95. if first.startswith("#"):
  96. first = first[1:].strip()
  97. rendered = render_markdown("\n".join(content),
  98. extensions=extensions,
  99. blacklist=blacklist,
  100. )
  101. return template("markdown.inc.html",
  102. title=first,
  103. markdown=rendered,
  104. )
  105. def render_markdown(body, html_escape=True, extensions=None, blacklist=None):
  106. """Render a block of Markdown text.
  107. This will default to escaping literal HTML characters. Set
  108. `html_escape=False` to trust HTML.
  109. * extensions should be a set() of extensions to add.
  110. * blacklist should be a set() of extensions to blacklist."""
  111. args = dict(
  112. lazy_ol=False, # If a numbered list starts at e.g. 4, show the <ol> there
  113. extensions=[
  114. "fenced_code", # GitHub style code blocks
  115. "tables", # http://michelf.ca/projects/php-markdown/extra/#table
  116. "smart_strong", # Handles double__underscore better.
  117. "codehilite", # Code highlighting with Pygment!
  118. "nl2br", # Line breaks inside a paragraph become <br>
  119. "sane_lists", # Make lists less surprising
  120. ],
  121. extension_configs={
  122. "codehilite": {
  123. "linenums": False,
  124. }
  125. }
  126. )
  127. if html_escape:
  128. args["safe_mode"] = "escape"
  129. # Additional extensions?
  130. if extensions is not None:
  131. for ext in extensions:
  132. args["extensions"].append(ext)
  133. if blacklist is not None:
  134. for ext in blacklist:
  135. args["extensions"].remove(str(ext))
  136. return u'<div class="markdown">{}</div>'.format(
  137. markdown.markdown(body, **args)
  138. )
  139. def send_email(to, subject, message, sender=None, reply_to=None):
  140. """Send an e-mail out."""
  141. if sender is None:
  142. sender = Config.mail.sender
  143. if type(to) != list:
  144. to = [to]
  145. logger.info("Send email to {}".format(to))
  146. if Config.mail.method == "smtp":
  147. # Send mail with SMTP.
  148. for email in to:
  149. # Construct the mail headers.
  150. headers = [
  151. "From: {}".format(sender),
  152. "To: {}".format(email),
  153. ]
  154. if reply_to is not None:
  155. headers.append("Reply-To: {}".format(reply_to))
  156. headers.append("Subject: {}".format(subject))
  157. # Prepare the mail for transport.
  158. try:
  159. server = smtplib.SMTP(Config.mail.server, Config.mail.port)
  160. msg = "\n".join(headers) + "\n\n" + message
  161. server.sendmail(sender, email, msg)
  162. server.quit()
  163. except socket.error:
  164. pass
  165. def handle_exception(error):
  166. """Send an e-mail to the site admin when an exception occurs."""
  167. if current_app.config.get("DEBUG"):
  168. print traceback.format_exc()
  169. raise
  170. import rophako.jsondb as JsonDB
  171. # Don't spam too many e-mails in a short time frame.
  172. cache = JsonDB.get_cache("exception_catcher")
  173. if cache:
  174. last_exception = int(cache)
  175. if int(time.time()) - last_exception < 120:
  176. # Only one e-mail per 2 minutes, minimum
  177. logger.error("RAPID EXCEPTIONS, DROPPING")
  178. return
  179. JsonDB.set_cache("exception_catcher", int(time.time()))
  180. username = "anonymous"
  181. try:
  182. if hasattr(g, "info") and "session" in g.info and "username" in g.info["session"]:
  183. username = g.info["session"]["username"]
  184. except:
  185. pass
  186. # Get the timestamp.
  187. timestamp = time.ctime(time.time())
  188. # Exception's traceback.
  189. error = str(error.__class__.__name__) + ": " + str(error)
  190. stacktrace = error + "\n\n" \
  191. + "==== Start Traceback ====\n" \
  192. + traceback.format_exc() \
  193. + "==== End Traceback ====\n\n" \
  194. + "Request Information\n" \
  195. + "-------------------\n" \
  196. + "Address: " + remote_addr() + "\n" \
  197. + "User Agent: " + request.user_agent.string + "\n" \
  198. + "Referrer: " + request.referrer
  199. # Construct the subject and message
  200. subject = "Internal Server Error on {} - {} - {}".format(
  201. Config.site.site_name,
  202. username,
  203. timestamp,
  204. )
  205. message = "{} has experienced an exception on the route: {}".format(
  206. username,
  207. request.path,
  208. )
  209. message += "\n\n" + stacktrace
  210. # Send the e-mail.
  211. send_email(
  212. to=Config.site.notify_address,
  213. subject=subject,
  214. message=message,
  215. )
  216. def generate_csrf_token():
  217. """Generator for CSRF tokens."""
  218. if "_csrf" not in session:
  219. session["_csrf"] = str(uuid.uuid4())
  220. return session["_csrf"]
  221. def include(endpoint, *args, **kwargs):
  222. """Include another sub-page inside a template."""
  223. # The 'endpoint' should be in the format 'module.function', i.e. 'blog.index'.
  224. module, function = endpoint.split(".")
  225. # Dynamically import the module and call its function.
  226. m = importlib.import_module("rophako.modules.{}".format(module))
  227. html = getattr(m, function)(*args, **kwargs)
  228. return html
  229. def remote_addr():
  230. """Retrieve the end user's remote IP address."""
  231. # TODO: eventually support configurations with X-Forwarded-For, but for
  232. # now at least we're centralizing this in one spot.
  233. return request.remote_addr
  234. def server_name():
  235. """Get the server's hostname."""
  236. urlparts = list(urlparse.urlparse(request.url_root))
  237. return urlparts[1]
  238. def pretty_time(time_format, unix):
  239. """Pretty-print a time stamp."""
  240. date = datetime.datetime.fromtimestamp(unix)
  241. return date.strftime(time_format)
  242. def sanitize_name(name):
  243. """Sanitize a name that may be used in the filesystem.
  244. Only allows numbers, letters, and some symbols."""
  245. return re.sub(r'[^A-Za-z0-9 .\-_]+', '', name)