注册增加邮箱验证 close #267

sh_branch
liangliangyy 7 years ago
parent b17fc84385
commit eca4e71cff

@ -16,6 +16,7 @@ from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
from django.forms import widgets
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
class LoginForm(AuthenticationForm):
@ -37,6 +38,12 @@ class RegisterForm(UserCreationForm):
self.fields['password2'].widget = widgets.PasswordInput(
attrs={'placeholder': "repeat password", "class": "form-control"})
def clean_email(self):
email = self.cleaned_data['email']
if get_user_model().objects.filter(email=email).exists():
raise ValidationError("该邮箱已经存在.")
return email
class Meta:
model = get_user_model()
fields = ("username", "email")

@ -6,6 +6,7 @@ import datetime
from accounts.models import BlogUser
from django.urls import reverse
from DjangoBlog.utils import *
from django.conf import settings
# Create your tests here.
@ -53,6 +54,12 @@ class AccountTest(TestCase):
'password2': 'password123!q@wE#R$T',
})
self.assertEquals(1, len(BlogUser.objects.filter(email='user123@user.com')))
user = BlogUser.objects.filter(email='user123@user.com')[0]
sign = get_md5(get_md5(settings.SECRET_KEY + str(user.id)))
path = reverse('accounts:result')
url = '{path}?type=validation&id={id}&sign={sign}'.format(path=path, id=user.id, sign=sign)
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
self.client.login(username='user1233', password='password123!q@wE#R$T')
user = BlogUser.objects.filter(email='user123@user.com')[0]

@ -15,14 +15,15 @@
from django.conf.urls import url
from django.contrib.auth import views as auth_view
from django.urls import path
from . import views
from .forms import LoginForm
app_name="accounts"
app_name = "accounts"
urlpatterns = [
url(r'^login/$', views.LoginView.as_view(success_url='/'), name='login', kwargs={'authentication_form': LoginForm}),
url(r'^register/$', views.RegisterView.as_view(success_url="/"), name='register'),
url(r'^logout/$', views.LogoutView.as_view(), name='logout')
url(r'^logout/$', views.LogoutView.as_view(), name='logout'),
path(r'account/result.html', views.account_result, name='result')
]

@ -5,7 +5,8 @@ from django.contrib.auth import authenticate, login, logout
# from django.views.generic.edit import FormView
from django.views.generic import FormView, RedirectView
from django.contrib.auth import get_user_model
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.http import HttpResponseRedirect, HttpResponseForbidden
from django.urls import reverse
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
from django.contrib.auth import REDIRECT_FIELD_NAME
@ -16,6 +17,8 @@ from django.shortcuts import redirect
from django.utils.decorators import method_decorator
from django.views.decorators.debug import sensitive_post_parameters
from django.utils.http import is_safe_url
from DjangoBlog.utils import send_email, get_md5, get_current_site
from django.conf import settings
logger = logging.getLogger(__name__)
@ -27,10 +30,37 @@ class RegisterView(FormView):
template_name = 'account/registration_form.html'
def form_valid(self, form):
user = form.save(False)
user.save(True)
url = reverse('accounts:login')
return HttpResponseRedirect(url)
if form.is_valid():
user = form.save(False)
user.is_active = False
user.save(True)
site = get_current_site().domain
sign = get_md5(get_md5(settings.SECRET_KEY + str(user.id)))
if settings.DEBUG:
site = '127.0.0.1:8000'
path = reverse('account:result')
url = "http://{site}{path}?type=validation&id={id}&sign={sign}".format(site=site, path=path, id=user.id,
sign=sign)
content = """
<p>请点击下面链接验证您的邮箱</p>
<a href="{url}" rel="bookmark">{url}</a>
再次感谢您
<br />
如果上面链接无法打开请将此链接复制至浏览器
{url}
""".format(url=url)
send_email(emailto=[user.email, ], title='验证您的电子邮箱', content=content)
url = reverse('accounts:result') + '?type=register&id=' + str(user.id)
return HttpResponseRedirect(url)
else:
return self.render_to_response({
'form': form
})
class LogoutView(RedirectView):
@ -91,3 +121,36 @@ class LoginView(FormView):
if not is_safe_url(url=redirect_to, allowed_hosts=[self.request.get_host()]):
redirect_to = self.success_url
return redirect_to
def account_result(request):
type = request.GET.get('type')
id = request.GET.get('id')
user = get_object_or_404(get_user_model(), id=id)
logger.info(type)
if user.is_active:
return HttpResponseRedirect('/')
if type and type in ['register', 'validation']:
if type == 'register':
content = '''
恭喜您注册成功一封验证邮件已经发送到您 {email} 的邮箱请验证您的邮箱后登录本站
'''.format(email=user.email)
title = '注册成功'
else:
c_sign = get_md5(get_md5(settings.SECRET_KEY + str(user.id)))
sign = request.GET.get('sign')
if sign != c_sign:
return HttpResponseForbidden()
user.is_active = True
user.save()
content = '''
恭喜您已经成功的完成邮箱验证您现在可以使用您的账号来登录本站
'''
title = '验证成功'
return render(request, 'account/result.html', {
'title': title,
'content': content
})
else:
return HttpResponseRedirect('/')

@ -9,10 +9,6 @@
<img class="img-circle profile-img" src="{% static 'blog/img/avatar.png' %}" alt="">
<form class="form-signin" action="{% url 'account:register' %}" method="post">
{% csrf_token %}
{% comment %}<label for="inputEmail" class="sr-only">Email address</label>
<input type="email" id="inputEmail" class="form-control" placeholder="Email" required autofocus>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" id="inputPassword" class="form-control" placeholder="Password" required>{% endcomment %}
{{ form.non_field_errors }}
{% for field in form %}
{{ field }}
@ -22,14 +18,6 @@
<button class="btn btn-lg btn-primary btn-block" type="submit">Create Your Account</button>
{% comment %}
<div class="checkbox">
<a class="pull-right">Need help?</a>
<label>
<input type="checkbox" value="remember-me"> Stay signed in
</label>
</div>
{% endcomment %}
</form>
</div>

@ -0,0 +1,22 @@
{% extends 'share_layout/base.html' %}
{% block header %}
<title> {{ title }}</title>
{% endblock %}
{% block content %}
<div id="primary" class="site-content">
<div id="content" role="main">
<header class="archive-header">
<h2 class="archive-title"> {{ content }}</h2>
</header><!-- .archive-header -->
<br/>
<header class="archive-header" style="text-align: center">
<a href="{% url "account:login" %}">登录</a>
|
<a href="/">回到首页</a>
</header><!-- .archive-header -->
</div>
</div>
{% endblock %}
Loading…
Cancel
Save