Treat scheduled-topic title/markdown as Jinja

This probably isn't particularly safe, but it's fine since I'm the only
one that can create or edit scheduled topics for now. The only available
variable so far is current_time_utc.
This commit is contained in:
Deimos
2020-03-25 16:22:31 -06:00
parent f0305bc0cd
commit 284c3cfd8d
2 changed files with 20 additions and 1 deletions

View File

@@ -11,6 +11,7 @@ pep8:
# "multiple statements on one line" - type declarations seem to trigger sometimes
- E704
- E203 # whitespace around colons in slices
- E722 # bare "except:" - pylint checks for this, shouldn't need to double-ignore
pep257:
disable:

View File

@@ -7,12 +7,14 @@ from datetime import datetime
from typing import List, Optional
from dateutil.rrule import rrule
from jinja2.sandbox import SandboxedEnvironment
from sqlalchemy import CheckConstraint, Column, ForeignKey, Integer, Text, TIMESTAMP
from sqlalchemy.orm import backref, relationship
from sqlalchemy.orm.session import Session
from sqlalchemy.sql.expression import text
from tildes.lib.database import RecurrenceRule, TagList
from tildes.lib.datetime import utc_now
from tildes.models import DatabaseModel
from tildes.models.group import Group
from tildes.models.topic import Topic
@@ -82,7 +84,23 @@ class TopicSchedule(DatabaseModel):
.one()
)
topic = Topic.create_text_topic(self.group, user, self.title, self.markdown)
# treat both the title and markdown as Jinja templates (sandboxed)
jinja_sandbox = SandboxedEnvironment()
jinja_variables = {"current_time_utc": utc_now()}
try:
title_template = jinja_sandbox.from_string(self.title)
title = title_template.render(jinja_variables)
except: # pylint: disable=bare-except
title = self.title
try:
markdown_template = jinja_sandbox.from_string(self.markdown)
markdown = markdown_template.render(jinja_variables)
except: # pylint: disable=bare-except
markdown = self.markdown
topic = Topic.create_text_topic(self.group, user, title, markdown)
topic.tags = self.tags
topic.schedule = self