perf: 优化短信 (#6826)

* perf: 优化短信

* refactor: 适配新的短信模板配置

Co-authored-by: ibuler <ibuler@qq.com>
Co-authored-by: xinwen <coderWen@126.com>
This commit is contained in:
fit2bot
2021-09-13 20:15:59 +08:00
committed by GitHub
parent 55a5dd1e34
commit 7a45f4d129
12 changed files with 58 additions and 81 deletions

View File

@@ -11,34 +11,6 @@ from common.exceptions import JMSException
logger = get_logger(__file__)
class SMS_MESSAGE(TextChoices):
"""
定义短信的各种消息类型,会存到类似 `ALIBABA_SMS_SIGN_AND_TEMPLATES` settings 里
{
'verification_code': {'sign_name': 'Jumpserver', 'template_code': 'SMS_222870834'}
...
}
"""
"""
验证码签名和模板。模板例子:
`您的验证码:${code},您正进行身份验证,打死不告诉别人!`
其中必须包含 `code` 变量
"""
VERIFICATION_CODE = 'verification_code'
def get_sign_and_tmpl(self, config: dict):
try:
data = config[self]
return data['sign_name'], data['template_code']
except KeyError as e:
raise JMSException(
code=f'{settings.SMS_BACKEND}_sign_and_tmpl_bad',
detail=_('Invalid SMS sign and template: {}').format(e)
)
class BACKENDS(TextChoices):
ALIBABA = 'alibaba', _('Alibaba cloud')
TENCENT = 'tencent', _('Tencent cloud')
@@ -49,11 +21,7 @@ class BaseSMSClient:
短信终端的基类
"""
SIGN_AND_TMPL_SETTING_FIELD: str
@property
def sign_and_tmpl(self):
return getattr(settings, self.SIGN_AND_TMPL_SETTING_FIELD, {})
SIGN_AND_TMPL_SETTING_FIELD_PREFIX: str
@classmethod
def new_from_settings(cls):
@@ -86,5 +54,12 @@ class SMS:
)
def send_verify_code(self, phone_number, code):
sign_name, template_code = SMS_MESSAGE.VERIFICATION_CODE.get_sign_and_tmpl(self.client.sign_and_tmpl)
sign_name = getattr(settings, f'{self.client.SIGN_AND_TMPL_SETTING_FIELD_PREFIX}_VERIFY_SIGN_NAME')
template_code = getattr(settings, f'{self.client.SIGN_AND_TMPL_SETTING_FIELD_PREFIX}_VERIFY_TEMPLATE_CODE')
if not (sign_name and template_code):
raise JMSException(
code='verify_code_sign_tmpl_invalid',
detail=_('SMS verification code signature or template invalid')
)
return self.send_sms([phone_number], sign_name, template_code, OrderedDict(code=code))

View File

@@ -15,7 +15,7 @@ logger = get_logger(__file__)
class AlibabaSMS(BaseSMSClient):
SIGN_AND_TMPL_SETTING_FIELD = 'ALIBABA_SMS_SIGN_AND_TEMPLATES'
SIGN_AND_TMPL_SETTING_FIELD_PREFIX = 'ALIBABA'
@classmethod
def new_from_settings(cls):

View File

@@ -20,7 +20,7 @@ class TencentSMS(BaseSMSClient):
"""
https://cloud.tencent.com/document/product/382/43196#.E5.8F.91.E9.80.81.E7.9F.AD.E4.BF.A1
"""
SIGN_AND_TMPL_SETTING_FIELD = 'TENCENT_SMS_SIGN_AND_TEMPLATES'
SIGN_AND_TMPL_SETTING_FIELD_PREFIX = 'TENCENT'
@classmethod
def new_from_settings(cls):