Skip to content

Commit dcf7dd3

Browse files
committed
oauth邮箱绑定功能
1 parent ebde6b6 commit dcf7dd3

File tree

8 files changed

+167
-17
lines changed

8 files changed

+167
-17
lines changed

DjangoBlog/utils.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@
1919
from pygments.lexers import get_lexer_by_name
2020
from pygments.formatters import html
2121
import logging
22+
import _thread
23+
from django.core.mail import EmailMultiAlternatives
2224

2325
logger = logging.getLogger('djangoblog')
2426
from importlib import import_module
@@ -120,3 +122,17 @@ def get_markdown(value):
120122

121123
mdp = mistune.Markdown(escape=True, renderer=renderer)
122124
return mdp(value)
125+
126+
127+
def send_email(subject, html_content, tomail):
128+
msg = EmailMultiAlternatives(subject, html_content, from_email='no-reply@lylinux.net', to=tomail)
129+
msg.content_subtype = "html"
130+
131+
def send_comment_email(msg):
132+
try:
133+
msg.send()
134+
except:
135+
print('send email error')
136+
pass
137+
138+
_thread.start_new_thread(send_comment_email, (msg,))

oauth/forms.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
#!/usr/bin/env python
2+
# encoding: utf-8
3+
4+
5+
"""
6+
@version: ??
7+
@author: liangliangyy
8+
@license: MIT Licence
9+
@contact: liangliangyy@gmail.com
10+
@site: https://www.lylinux.org/
11+
@software: PyCharm
12+
@file: forms.py
13+
@time: 2017/3/7 下午8:58
14+
"""
15+
16+
from django.contrib.auth.forms import forms
17+
from django.forms import widgets
18+
19+
20+
class RequireEmailForm(forms.Form):
21+
email = forms.EmailField(label='电子邮箱', required=True)
22+
oauthid = forms.IntegerField(widget=forms.HiddenInput, required=False)
23+
24+
def __init__(self, *args, **kwargs):
25+
super(RequireEmailForm, self).__init__(*args, **kwargs)
26+
self.fields['email'].widget = widgets.EmailInput(attrs={'placeholder': "email", "class": "form-control"})

oauth/models.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
from django.conf import settings
55

66

7-
class oauthuser(models.Model):
7+
class OAuthUser(models.Model):
88
author = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name='用户', blank=True, null=True)
99
openid = models.CharField(max_length=50)
1010
nikename = models.CharField(max_length=50, verbose_name='昵称')

oauth/oauthmanager.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
"""
1515

1616
from abc import ABCMeta, abstractmethod, abstractproperty
17-
from oauth.models import oauthuser
17+
from oauth.models import OAuthUser
1818
from django.conf import settings
1919
import requests
2020
import json
@@ -226,7 +226,7 @@ def get_oauth_userinfo(self):
226226
print(rsp)
227227
try:
228228
datas = json.loads(rsp)
229-
user = oauthuser()
229+
user = OAuthUser()
230230
user.picture = datas['avatar_url']
231231
user.nikename = datas['name']
232232
user.openid = datas['id']

oauth/tests.py

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,3 @@
11
from django.test import TestCase
22

33
# Create your tests here.
4-
5-
class OAuthTet(TestCase):
6-
def setUp(self):
7-
pass
8-
9-
10-
from oauth.oauthmanager import WBOauthManager
11-
from django.conf import settings
12-
settings.OAHUTH['sina']
13-
manager=WBOauthManager(client_id=settings.OAHUTH['sina']['appkey'],client_secret=settings.OAHUTH['sina']['appsecret'],callback_url=settings.OAHUTH['sina']['callbackurl'])

oauth/urls.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,10 @@
1717
from django.views.decorators.cache import cache_page
1818
from . import views
1919

20-
urlpatterns = [url(r'^oauth/authorize$', views.authorize), ]
20+
urlpatterns = [
21+
url(r'^oauth/authorize$', views.authorize),
22+
url(r'^oauth/requireemail/(?P<oauthid>\d+)', views.RequireEmailView.as_view(), name='require_email'),
23+
]
2124

2225
"""
2326
urlpatterns = [

oauth/views.py

Lines changed: 72 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,12 @@
55
from django.conf import settings
66
from django.http import HttpResponse, HttpResponseRedirect
77
from django.contrib.auth import get_user_model
8-
from .models import oauthuser
8+
from .models import OAuthUser
99
from django.contrib.auth import login
10+
from django.shortcuts import get_object_or_404
11+
from django.views.generic import FormView, RedirectView
12+
from oauth.forms import RequireEmailForm
13+
from django.core.urlresolvers import reverse
1014

1115

1216
def authorize(request):
@@ -25,16 +29,81 @@ def authorize(request):
2529
author = None
2630
if user:
2731
email = user.email
32+
email = None
2833
if email:
2934
author = get_user_model().objects.get(email=email)
3035
if not author:
31-
author = get_user_model().objects.create_user(username=user["name"], email=email)
36+
author = get_user_model().objects.create_user(username=user.nikename, email=email)
3237
user.author = author
3338
user.save()
3439
login(request, author)
3540
return HttpResponseRedirect('/')
3641
if not email:
37-
author = get_user_model().objects.create_user(username=user["name"], email=email)
42+
author = get_user_model().objects.create_user(username=user.nikename)
43+
user.author = author
44+
user.save()
45+
url = reverse('oauth:require_email', kwargs=
46+
{
47+
'oauthid': user.id
48+
})
49+
print(url)
50+
return HttpResponseRedirect(url)
51+
52+
53+
"""
54+
def require_email(request, oauthid):
55+
oauthuser = get_object_or_404(OAuthUser, pk=oauthid)
56+
if oauthuser.email:
57+
return HttpResponseRedirect('/')
58+
59+
"""
60+
61+
62+
class RequireEmailView(FormView):
63+
form_class = RequireEmailForm
64+
template_name = 'oauth/require_email.html'
65+
66+
def get(self, request, *args, **kwargs):
67+
oauthid = self.kwargs['oauthid']
68+
oauthuser = get_object_or_404(OAuthUser, pk=oauthid)
69+
if oauthuser.email:
70+
pass
71+
# return HttpResponseRedirect('/')
72+
73+
return super(RequireEmailView, self).get(request, *args, **kwargs)
74+
75+
def get_initial(self):
76+
oauthid = self.kwargs['oauthid']
77+
return {
78+
'email': '',
79+
'oauthid': oauthid
80+
}
81+
82+
def get_context_data(self, **kwargs):
83+
oauthid = self.kwargs['oauthid']
84+
oauthuser = get_object_or_404(OAuthUser, pk=oauthid)
85+
if oauthuser.picture:
86+
kwargs['picture'] = oauthuser.picture
87+
return super(RequireEmailView, self).get_context_data(**kwargs)
88+
89+
def form_valid(self, form):
90+
email = form.cleaned_data['email']
91+
oauthid = form.cleaned_data['oauthid']
92+
oauthuser = get_object_or_404(OAuthUser, pk=oauthid)
93+
from DjangoBlog.utils import send_email
94+
url = '123'
95+
content = """
96+
<p>请点击下面链接绑定您的邮箱</p>
97+
98+
<a href="{url}" rel="bookmark">{url}</a>
99+
100+
再次感谢您!
101+
<br />
102+
如果上面链接无法打开,请将此链接复制至浏览器。
103+
{url}
104+
""".format(url=url)
105+
send_email('绑定您的电子邮箱', content, [email, ])
106+
return HttpResponseRedirect('/')
38107

39108

40109
"""

templates/oauth/require_email.html

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
{% extends 'share_layout/base_account.html' %}
2+
3+
{% load static %}
4+
{% block content %}
5+
<div class="container">
6+
7+
<h2 class="form-signin-heading text-center">Binding E-mail account</h2>
8+
9+
<div class="card card-signin">
10+
{% if picture %}
11+
<img class="img-circle profile-img" src="{{ picture }}" alt="">
12+
{% else %}
13+
<img class="img-circle profile-img" src="{% static 'blog/img/avatar.png' %}" alt="">
14+
{% endif %}
15+
<form class="form-signin" action="" method="post">
16+
{% csrf_token %}
17+
{% comment %}<label for="inputEmail" class="sr-only">Email address</label>
18+
<input type="email" id="inputEmail" class="form-control" placeholder="Email" required autofocus>
19+
<label for="inputPassword" class="sr-only">Password</label>
20+
<input type="password" id="inputPassword" class="form-control" placeholder="Password" required>{% endcomment %}
21+
{{ form.non_field_errors }}
22+
{% for field in form %}
23+
{{ field }}
24+
{{ field.errors }}
25+
{% endfor %}
26+
27+
28+
<button class="btn btn-lg btn-primary btn-block" type="submit">Submit</button>
29+
30+
{% comment %}
31+
<div class="checkbox">
32+
<a class="pull-right">Need help?</a>
33+
<label>
34+
<input type="checkbox" value="remember-me"> Stay signed in
35+
</label>
36+
</div>
37+
{% endcomment %}
38+
</form>
39+
</div>
40+
41+
<p class="text-center">
42+
<a href="{% url "account:login" %}">Sign In</a>
43+
</p>
44+
45+
</div> <!-- /container -->
46+
{% endblock %}

0 commit comments

Comments
 (0)