Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion apps/common/init/init_template.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,22 @@
@date:2025/12/1 17:16
@desc:
"""
import secrets
from typing import Any

from jinja2 import pass_context
from jinja2.sandbox import SandboxedEnvironment
from langchain_core.prompts.string import DEFAULT_FORMATTER_MAPPING, _HAS_JINJA2


@pass_context
def secure_random_filter(context, seq):
try:
return secrets.choice(seq)
except IndexError:
return context.environment.undefined("No random item, sequence was empty.")


def jinja2_formatter(template: str, /, **kwargs: Any) -> str:
"""Format a template using jinja2.

Expand Down Expand Up @@ -47,7 +57,9 @@ def jinja2_formatter(template: str, /, **kwargs: Any) -> str:
# Use a restricted sandbox that blocks ALL attribute/method access
# Only simple variable lookups like {{variable}} are allowed
# Attribute access like {{variable.attr}} or {{variable.method()}} is blocked
return SandboxedEnvironment().from_string(template).render(**kwargs)
environment = SandboxedEnvironment()
environment.filters['random'] = secure_random_filter
return environment.from_string(template).render(**kwargs)


def run():
Expand Down
5 changes: 2 additions & 3 deletions apps/users/serializers/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@
import datetime
import json
import os
import random
import re
import secrets
from collections import defaultdict

import uuid_utils.compat as uuid
Expand Down Expand Up @@ -1173,8 +1173,7 @@ def send(self):
email = self.data.get("email")
state = self.data.get("type")
# 生成随机验证码
code = "".join(list(map(lambda i: random.choice(['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'
]), range(6))))
code = "".join(secrets.choice('1234567890') for _ in range(6))
# 获取邮件模板
language = get_language()
file = open(
Expand Down
Loading