Skip to content

Commit eca4e71

Browse files
committed
注册增加邮箱验证 close liangliangyy#267
1 parent b17fc84 commit eca4e71

File tree

6 files changed

+108
-20
lines changed

6 files changed

+108
-20
lines changed

accounts/forms.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
from django.forms import widgets
1717
from django.conf import settings
1818
from django.contrib.auth import get_user_model
19+
from django.core.exceptions import ValidationError
1920

2021

2122
class LoginForm(AuthenticationForm):
@@ -37,6 +38,12 @@ def __init__(self, *args, **kwargs):
3738
self.fields['password2'].widget = widgets.PasswordInput(
3839
attrs={'placeholder': "repeat password", "class": "form-control"})
3940

41+
def clean_email(self):
42+
email = self.cleaned_data['email']
43+
if get_user_model().objects.filter(email=email).exists():
44+
raise ValidationError("该邮箱已经存在.")
45+
return email
46+
4047
class Meta:
4148
model = get_user_model()
4249
fields = ("username", "email")

accounts/tests.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
from accounts.models import BlogUser
77
from django.urls import reverse
88
from DjangoBlog.utils import *
9+
from django.conf import settings
910

1011

1112
# Create your tests here.
@@ -53,6 +54,12 @@ def test_validate_register(self):
5354
'password2': 'password123!q@wE#R$T',
5455
})
5556
self.assertEquals(1, len(BlogUser.objects.filter(email='user123@user.com')))
57+
user = BlogUser.objects.filter(email='user123@user.com')[0]
58+
sign = get_md5(get_md5(settings.SECRET_KEY + str(user.id)))
59+
path = reverse('accounts:result')
60+
url = '{path}?type=validation&id={id}&sign={sign}'.format(path=path, id=user.id, sign=sign)
61+
response = self.client.get(url)
62+
self.assertEqual(response.status_code, 200)
5663

5764
self.client.login(username='user1233', password='password123!q@wE#R$T')
5865
user = BlogUser.objects.filter(email='user123@user.com')[0]

accounts/urls.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,14 +15,15 @@
1515

1616
from django.conf.urls import url
1717
from django.contrib.auth import views as auth_view
18-
18+
from django.urls import path
1919
from . import views
2020
from .forms import LoginForm
2121

22-
app_name="accounts"
22+
app_name = "accounts"
2323

2424
urlpatterns = [
2525
url(r'^login/$', views.LoginView.as_view(success_url='/'), name='login', kwargs={'authentication_form': LoginForm}),
2626
url(r'^register/$', views.RegisterView.as_view(success_url="/"), name='register'),
27-
url(r'^logout/$', views.LogoutView.as_view(), name='logout')
27+
url(r'^logout/$', views.LogoutView.as_view(), name='logout'),
28+
path(r'account/result.html', views.account_result, name='result')
2829
]

accounts/views.py

Lines changed: 68 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@
55
# from django.views.generic.edit import FormView
66
from django.views.generic import FormView, RedirectView
77
from django.contrib.auth import get_user_model
8-
from django.http import HttpResponseRedirect
8+
from django.shortcuts import get_object_or_404
9+
from django.http import HttpResponseRedirect, HttpResponseForbidden
910
from django.urls import reverse
1011
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
1112
from django.contrib.auth import REDIRECT_FIELD_NAME
@@ -16,6 +17,8 @@
1617
from django.utils.decorators import method_decorator
1718
from django.views.decorators.debug import sensitive_post_parameters
1819
from django.utils.http import is_safe_url
20+
from DjangoBlog.utils import send_email, get_md5, get_current_site
21+
from django.conf import settings
1922

2023
logger = logging.getLogger(__name__)
2124

@@ -27,10 +30,37 @@ class RegisterView(FormView):
2730
template_name = 'account/registration_form.html'
2831

2932
def form_valid(self, form):
30-
user = form.save(False)
31-
user.save(True)
32-
url = reverse('accounts:login')
33-
return HttpResponseRedirect(url)
33+
if form.is_valid():
34+
user = form.save(False)
35+
user.is_active = False
36+
user.save(True)
37+
site = get_current_site().domain
38+
sign = get_md5(get_md5(settings.SECRET_KEY + str(user.id)))
39+
40+
if settings.DEBUG:
41+
site = '127.0.0.1:8000'
42+
path = reverse('account:result')
43+
url = "http://{site}{path}?type=validation&id={id}&sign={sign}".format(site=site, path=path, id=user.id,
44+
sign=sign)
45+
46+
content = """
47+
<p>请点击下面链接验证您的邮箱</p>
48+
49+
<a href="{url}" rel="bookmark">{url}</a>
50+
51+
再次感谢您!
52+
<br />
53+
如果上面链接无法打开,请将此链接复制至浏览器。
54+
{url}
55+
""".format(url=url)
56+
send_email(emailto=[user.email, ], title='验证您的电子邮箱', content=content)
57+
58+
url = reverse('accounts:result') + '?type=register&id=' + str(user.id)
59+
return HttpResponseRedirect(url)
60+
else:
61+
return self.render_to_response({
62+
'form': form
63+
})
3464

3565

3666
class LogoutView(RedirectView):
@@ -91,3 +121,36 @@ def get_success_url(self):
91121
if not is_safe_url(url=redirect_to, allowed_hosts=[self.request.get_host()]):
92122
redirect_to = self.success_url
93123
return redirect_to
124+
125+
126+
def account_result(request):
127+
type = request.GET.get('type')
128+
id = request.GET.get('id')
129+
130+
user = get_object_or_404(get_user_model(), id=id)
131+
logger.info(type)
132+
if user.is_active:
133+
return HttpResponseRedirect('/')
134+
if type and type in ['register', 'validation']:
135+
if type == 'register':
136+
content = '''
137+
恭喜您注册成功,一封验证邮件已经发送到您 {email} 的邮箱,请验证您的邮箱后登录本站。
138+
'''.format(email=user.email)
139+
title = '注册成功'
140+
else:
141+
c_sign = get_md5(get_md5(settings.SECRET_KEY + str(user.id)))
142+
sign = request.GET.get('sign')
143+
if sign != c_sign:
144+
return HttpResponseForbidden()
145+
user.is_active = True
146+
user.save()
147+
content = '''
148+
恭喜您已经成功的完成邮箱验证,您现在可以使用您的账号来登录本站。
149+
'''
150+
title = '验证成功'
151+
return render(request, 'account/result.html', {
152+
'title': title,
153+
'content': content
154+
})
155+
else:
156+
return HttpResponseRedirect('/')

templates/account/registration_form.html

Lines changed: 0 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,6 @@ <h2 class="form-signin-heading text-center">Create Your Account</h2>
99
<img class="img-circle profile-img" src="{% static 'blog/img/avatar.png' %}" alt="">
1010
<form class="form-signin" action="{% url 'account:register' %}" method="post">
1111
{% csrf_token %}
12-
{% comment %}<label for="inputEmail" class="sr-only">Email address</label>
13-
<input type="email" id="inputEmail" class="form-control" placeholder="Email" required autofocus>
14-
<label for="inputPassword" class="sr-only">Password</label>
15-
<input type="password" id="inputPassword" class="form-control" placeholder="Password" required>{% endcomment %}
1612
{{ form.non_field_errors }}
1713
{% for field in form %}
1814
{{ field }}
@@ -22,14 +18,6 @@ <h2 class="form-signin-heading text-center">Create Your Account</h2>
2218

2319
<button class="btn btn-lg btn-primary btn-block" type="submit">Create Your Account</button>
2420

25-
{% comment %}
26-
<div class="checkbox">
27-
<a class="pull-right">Need help?</a>
28-
<label>
29-
<input type="checkbox" value="remember-me"> Stay signed in
30-
</label>
31-
</div>
32-
{% endcomment %}
3321
</form>
3422
</div>
3523

templates/account/result.html

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
{% extends 'share_layout/base.html' %}
2+
{% block header %}
3+
<title> {{ title }}</title>
4+
{% endblock %}
5+
{% block content %}
6+
<div id="primary" class="site-content">
7+
<div id="content" role="main">
8+
9+
<header class="archive-header">
10+
11+
<h2 class="archive-title"> {{ content }}</h2>
12+
</header><!-- .archive-header -->
13+
<br/>
14+
<header class="archive-header" style="text-align: center">
15+
16+
<a href="{% url "account:login" %}">登录</a>
17+
|
18+
<a href="/">回到首页</a>
19+
</header><!-- .archive-header -->
20+
</div>
21+
</div>
22+
{% endblock %}

0 commit comments

Comments
 (0)