1.生成token驗證碼方案 ,使用itsdangerous 大寶劍,python
能夠序列化出驗證碼,並能設置過時時間django
安裝 itsdangerous
url
pip install itsdangerousspa
對用戶名和郵箱進行序列化生成token碼,有效期3600秒,過時後這個token碼不能進行解碼code
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.解碼blog
對上邊生成的token碼進行解碼,過時不能解碼,須要使用相同的序列化器配置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