Merge pull request #12211 from jumpserver/pr@dev@random

perf: 随机密码生成规则添加可排除字符选项
pull/12213/head
huailei 2023-11-28 14:49:35 +08:00 committed by GitHub
commit 01e40fd238
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 15 additions and 2 deletions

View File

@ -15,6 +15,7 @@ class PasswordRulesSerializer(serializers.Serializer):
uppercase = serializers.BooleanField(default=True, label=_('Uppercase')) uppercase = serializers.BooleanField(default=True, label=_('Uppercase'))
digit = serializers.BooleanField(default=True, label=_('Digit')) digit = serializers.BooleanField(default=True, label=_('Digit'))
symbol = serializers.BooleanField(default=True, label=_('Special symbol')) symbol = serializers.BooleanField(default=True, label=_('Special symbol'))
exclude_symbols = serializers.CharField(default='', max_length=16, label=_('Exclude symbol'))
class AccountTemplateSerializer(BaseAccountSerializer): class AccountTemplateSerializer(BaseAccountSerializer):

View File

@ -30,7 +30,8 @@ class SecretGenerator:
'lower': rules['lowercase'], 'lower': rules['lowercase'],
'upper': rules['uppercase'], 'upper': rules['uppercase'],
'digit': rules['digit'], 'digit': rules['digit'],
'special_char': rules['symbol'] 'special_char': rules['symbol'],
'exclude_chars': rules['exclude_symbols']
} }
return random_string(**rules) return random_string(**rules)

View File

@ -32,7 +32,16 @@ def random_replace_char(s, chars, length):
return ''.join(seq) return ''.join(seq)
def random_string(length: int, lower=True, upper=True, digit=True, special_char=False, symbols=string_punctuation): def remove_exclude_char(s, exclude_chars):
for i in exclude_chars:
s = s.replace(i, '')
return s
def random_string(
length: int, lower=True, upper=True, digit=True,
special_char=False, exclude_chars='', symbols=string_punctuation
):
if not any([lower, upper, digit]): if not any([lower, upper, digit]):
raise ValueError('At least one of `lower`, `upper`, `digit` must be `True`') raise ValueError('At least one of `lower`, `upper`, `digit` must be `True`')
if length < 4: if length < 4:
@ -44,11 +53,13 @@ def random_string(length: int, lower=True, upper=True, digit=True, special_char=
(digit, string.digits), (digit, string.digits),
) )
chars = ''.join([i[1] for i in chars_map if i[0]]) chars = ''.join([i[1] for i in chars_map if i[0]])
chars = remove_exclude_char(chars, exclude_chars)
texts = list(secrets.choice(chars) for __ in range(length)) texts = list(secrets.choice(chars) for __ in range(length))
texts = ''.join(texts) texts = ''.join(texts)
# 控制一下特殊字符的数量, 别随机出来太多 # 控制一下特殊字符的数量, 别随机出来太多
if special_char: if special_char:
symbols = remove_exclude_char(symbols, exclude_chars)
symbol_num = length // 16 + 1 symbol_num = length // 16 + 1
texts = random_replace_char(texts, symbols, symbol_num) texts = random_replace_char(texts, symbols, symbol_num)
return texts return texts