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.

78 lines
2.3KB

  1. # -*- coding: utf-8 -*-
  2. from flask import g, session, request, render_template, flash, redirect, url_for
  3. from functools import wraps
  4. import uuid
  5. import datetime
  6. import time
  7. import re
  8. import importlib
  9. from rophako.log import logger
  10. def login_required(f):
  11. """Wrapper for pages that require a logged-in user."""
  12. @wraps(f)
  13. def decorated_function(*args, **kwargs):
  14. if not g.info["session"]["login"]:
  15. session["redirect_url"] = request.url
  16. flash("You must be logged in to do that!")
  17. return redirect(url_for("account.login"))
  18. return f(*args, **kwargs)
  19. return decorated_function
  20. def admin_required(f):
  21. """Wrapper for admin-only pages. Implies login_required."""
  22. @wraps(f)
  23. def decorated_function(*args, **kwargs):
  24. if not g.info["session"]["login"]:
  25. # Not even logged in?
  26. session["redirect_url"] = request.url
  27. flash("You must be logged in to do that!")
  28. return redirect(url_for("account.login"))
  29. if g.info["session"]["role"] != "admin":
  30. logger.warning("User tried to access an Admin page, but wasn't allowed!")
  31. return redirect(url_for("index"))
  32. return f(*args, **kwargs)
  33. return decorated_function
  34. def template(name, **kwargs):
  35. """Render a template to the browser."""
  36. html = render_template(name, **kwargs)
  37. # Get the elapsed time for the request.
  38. time_elapsed = "%.03f" % (time.time() - g.info["time"])
  39. html = re.sub(r'\%time_elapsed\%', time_elapsed, html)
  40. return html
  41. def generate_csrf_token():
  42. """Generator for CSRF tokens."""
  43. if "_csrf" not in session:
  44. session["_csrf"] = str(uuid.uuid4())
  45. return session["_csrf"]
  46. def include(endpoint, *args, **kwargs):
  47. """Include another sub-page inside a template."""
  48. # The 'endpoint' should be in the format 'module.function', i.e. 'blog.index'.
  49. module, function = endpoint.split(".")
  50. # Dynamically import the module and call its function.
  51. m = importlib.import_module("rophako.modules.{}".format(module))
  52. html = getattr(m, function)(*args, **kwargs)
  53. return html
  54. def pretty_time(time_format, unix):
  55. """Pretty-print a time stamp."""
  56. date = datetime.datetime.fromtimestamp(unix)
  57. return date.strftime(time_format)