算法流程如下:
1)处理用户注册数据,存入数据库,is_activity字段设置为False,用户未认证之前不允许登陆
2)产生token,生成验证连接URL
3)发送验证邮件
4)用户通过认证邮箱点击验证连接,激活is_activity字段,可以登录
5)若验证连接过期,删除用户在数据库中的注册信息。
#系统root邮箱 settings.py
EMAIL_HOST = ‘smtp.qq.com‘ EMAIL_HOST_USER = ‘17********@qq.com‘ #授权码 EMAIL_HOST_PASSWORD = ‘dxsblqtqohiycgcb‘ EMAIL_PORT = 587 EMAIL_USE_TLS = True #可以域名,可以设置本地 DOMAIN = ‘http://127.0.0.1:8000‘
#注册相关路由 url.py
url(r‘^register/$‘, reg, name=‘reg‘), url(r‘^activate/(?P<token>\w+.[-_\w]*\w+.[-_\w]*\w+)/$‘, activate,name=‘activate‘),
#注册视图函数 user/views.py
def reg(request): try: if request.method == ‘POST‘: print request.method register_form = RegForm(request.POST) if register_form.is_valid(): print ‘数据验证通过!‘ username=register_form.cleaned_data[‘username‘] email=register_form.cleaned_data[‘email‘] password=register_form.cleaned_data[‘password‘] user = UserProfile.objects.create( username=username, email=email, password = password, ) user.save() print ‘注册信息保存成功!‘ # 邮箱验证 token = token_confirm.generate_validate_token(username) token_url = ‘/‘.join([django_settings.DOMAIN, ‘activate‘, token]) message = "\n".join([u‘{0},欢迎加入XX‘.format(username), u‘请访问该链接,完成用户验证:‘,u"< a href = "+token_url+u" > "+token_url+u" < / a > " ]) send_mail(u‘注册用户验证信息‘, message, ‘17******@qq.com‘, [email], fail_silently=False) return render(request, ‘common/success.html‘, {‘reason‘: u"已将激活链接发送到您的注册邮箱,请登录激活,有效期为1个小时"}) else: return render(request, ‘common/failure.html‘, {‘reason‘: register_form.errors}) else: register_form = RegForm() except Exception as e: print ‘错误‘,e
#用户点击邮箱链接,账户激活 user/views.py
def activate(request, token): try: username = token_confirm.confirm_validate_token(token) except:#令牌过期 username = token_confirm.remove_validate_token(token) users = UserProfile.objects.filter(username=username) for user in users: user.delete()#删除注册用户 return render(request, ‘common/failure.html‘, { ‘reason‘: u‘对不起,验证链接已经过期,请重新<a href=\"‘ + unicode(django_settings.DOMAIN) + u‘/register\">注册</a>‘}) try: user = UserProfile.objects.get(username=username) except UserProfile.DoesNotExist: return render(request, ‘common/failure.html‘, {‘reason‘: u"对不起,您所验证的用户不存在,请重新注册"}) user.is_active = True user.save() message = u‘终于等到你!账号激活成功,可以进行<a href=\"‘ + unicode(django_settings.DOMAIN) + u‘/login\">登录</a>操作‘ return render(request, ‘common/success.html‘, {‘reason‘: message})
参考:https://my.oschina.net/keyven/blog/726123
时间: 2024-10-05 18:27:20