You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
django/src/DjangoBlog-master/accounts/utils.py

64 lines
2.1 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import typing
from datetime import timedelta
from django.core.cache import cache
from django.utils.translation import gettext
from django.utils.translation import gettext_lazy as _
from djangoblog.utils import send_email
# 验证码的生存时间Time To Live设置为5分钟
_code_ttl = timedelta(minutes=5)
def send_verify_email(to_mail: str, code: str, subject: str = _("Verify Email")):
"""发送验证邮件
Args:
to_mail: 接收邮箱地址
subject: 邮件主题,默认为"Verify Email"
code: 需要发送的验证码
"""
# 生成邮件HTML内容包含验证码信息并支持国际化
html_content = _(
"You are resetting the password, the verification code is%(code)s, valid within 5 minutes, please keep it "
"properly") % {'code': code}
# 调用邮件发送工具函数发送邮件
send_email([to_mail], subject, html_content)
def verify(email: str, code: str) -> typing.Optional[str]:
"""验证邮箱和验证码是否匹配
Args:
email: 需要验证的邮箱地址
code: 用户输入的验证码
Return:
如果验证失败返回错误信息字符串验证成功返回None
Note:
当前错误处理方式不够合理,建议改为抛出异常的方式,
这样调用方可以通过try-except来处理错误而不是检查返回值
"""
# 从缓存中获取该邮箱对应的验证码
cache_code = get_code(email)
# 比较缓存中的验证码和用户输入的验证码
if cache_code != code:
return gettext("Verification code error")
# 验证成功返回None
def set_code(email: str, code: str):
"""将验证码存储到缓存中
Args:
email: 作为缓存键的邮箱地址
code: 需要存储的验证码
"""
cache.set(email, code, _code_ttl.seconds)
def get_code(email: str) -> typing.Optional[str]:
"""从缓存中获取验证码
Args:
email: 作为缓存键的邮箱地址
Return:
返回缓存中的验证码如果不存在或已过期则返回None
"""
return cache.get(email)