1.生成token验证码方案 ,使用itsdangerous 大宝剑,
可以序列化出验证码,并能设置过期时间
安装 itsdangerous
pip install itsdangerous
对用户名和邮箱进行序列化生成token码,有效期3600秒,过期后这个token码不能进行解码
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer from django.conf import settings def generate_verify_email_url(user): """ 生成邮箱验证链接 :param user: 当前登录用户 :return: verify_url """ serializer = Serializer(settings.SECRET_KEY, expires_in=3600) data = {'user_id': user.id, 'email': user.email} token = serializer.dumps(data).decode()
#settings.EMAIL_VERIFY_URL是个固定的链接地址
verify_url = settings.EMAIL_VERIFY_URL + '?token=' + token
return verify_url
2.解码
对上边生成的token码进行解码,过期不能解码,需要使用相同的序列化器配置
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer,BadData from django.conf import settings def check_verify_email_token(token): """ 验证token并提取user :param token: 用户信息签名后的结果 :return: user, None """ serializer = Serializer(settings.SECRET_KEY, expires_in=3600) try: data = serializer.loads(token) except BadData: return None else: user_id = data.get('user_id') email = data.get('email') try: user = User.objects.get(id=user_id, email=email) except User.DoesNotExist: return None else: return user