poll widget: Add server validation.

This commit is contained in:
Steve Howell
2021-06-13 15:00:45 +00:00
committed by Tim Abbott
parent ab9c17ed3d
commit e739bee00a
4 changed files with 207 additions and 4 deletions

View File

@@ -456,6 +456,49 @@ def check_widget_content(widget_content: object) -> Dict[str, Any]:
raise ValidationError("unknown widget type: " + widget_type)
def validate_poll_data(poll_data: object, is_widget_author: bool) -> None:
check_dict([("type", check_string)])("poll data", poll_data)
assert isinstance(poll_data, dict)
if poll_data["type"] == "vote":
checker = check_dict_only(
[
("type", check_string),
("key", check_string),
("vote", check_int_in([1, -1])),
]
)
checker("poll data", poll_data)
return
if poll_data["type"] == "question":
if not is_widget_author:
raise ValidationError("You can't edit a question unless you are the author.")
checker = check_dict_only(
[
("type", check_string),
("question", check_string),
]
)
checker("poll data", poll_data)
return
if poll_data["type"] == "new_option":
checker = check_dict_only(
[
("type", check_string),
("option", check_string),
("idx", check_int),
]
)
checker("poll data", poll_data)
return
raise ValidationError(f"Unknown type for poll data: {poll_data['type']}")
# Converter functions for use with has_request_variables
def to_non_negative_int(s: str, max_int_size: int = 2 ** 32 - 1) -> int:
x = int(s)

View File

@@ -79,6 +79,30 @@ def do_widget_post_save_actions(send_request: SendMessageRequest) -> None:
send_request.submessages = SubMessage.get_raw_db_rows([message_id])
def get_widget_type(*, message_id: int) -> Optional[str]:
submessage = (
SubMessage.objects.filter(
message_id=message_id,
msg_type="widget",
)
.only("content")
.first()
)
if submessage is None:
return None
try:
data = json.loads(submessage.content)
except Exception:
return None
try:
return data["widget_type"]
except Exception:
return None
def is_widget_message(message: Message) -> bool:
# Right now all messages that are widgetized use submessage, and vice versa.
return message.submessage_set.exists()