oauth邮箱绑定功能

sh_branch
liangliangyy 9 years ago
parent ebde6b6271
commit dcf7dd31d3

@ -19,6 +19,8 @@ from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import html
import logging
import _thread
from django.core.mail import EmailMultiAlternatives
logger = logging.getLogger('djangoblog')
from importlib import import_module
@ -120,3 +122,17 @@ class common_markdown():
mdp = mistune.Markdown(escape=True, renderer=renderer)
return mdp(value)
def send_email(subject, html_content, tomail):
msg = EmailMultiAlternatives(subject, html_content, from_email='no-reply@lylinux.net', to=tomail)
msg.content_subtype = "html"
def send_comment_email(msg):
try:
msg.send()
except:
print('send email error')
pass
_thread.start_new_thread(send_comment_email, (msg,))

@ -0,0 +1,26 @@
#!/usr/bin/env python
# encoding: utf-8
"""
@version: ??
@author: liangliangyy
@license: MIT Licence
@contact: liangliangyy@gmail.com
@site: https://www.lylinux.org/
@software: PyCharm
@file: forms.py
@time: 2017/3/7 下午8:58
"""
from django.contrib.auth.forms import forms
from django.forms import widgets
class RequireEmailForm(forms.Form):
email = forms.EmailField(label='电子邮箱', required=True)
oauthid = forms.IntegerField(widget=forms.HiddenInput, required=False)
def __init__(self, *args, **kwargs):
super(RequireEmailForm, self).__init__(*args, **kwargs)
self.fields['email'].widget = widgets.EmailInput(attrs={'placeholder': "email", "class": "form-control"})

@ -4,7 +4,7 @@ from django.db import models
from django.conf import settings
class oauthuser(models.Model):
class OAuthUser(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name='用户', blank=True, null=True)
openid = models.CharField(max_length=50)
nikename = models.CharField(max_length=50, verbose_name='昵称')

@ -14,7 +14,7 @@
"""
from abc import ABCMeta, abstractmethod, abstractproperty
from oauth.models import oauthuser
from oauth.models import OAuthUser
from django.conf import settings
import requests
import json
@ -226,7 +226,7 @@ class GitHubOauthManager(BaseOauthManager):
print(rsp)
try:
datas = json.loads(rsp)
user = oauthuser()
user = OAuthUser()
user.picture = datas['avatar_url']
user.nikename = datas['name']
user.openid = datas['id']

@ -1,13 +1,3 @@
from django.test import TestCase
# Create your tests here.
class OAuthTet(TestCase):
def setUp(self):
pass
from oauth.oauthmanager import WBOauthManager
from django.conf import settings
settings.OAHUTH['sina']
manager=WBOauthManager(client_id=settings.OAHUTH['sina']['appkey'],client_secret=settings.OAHUTH['sina']['appsecret'],callback_url=settings.OAHUTH['sina']['callbackurl'])

@ -17,7 +17,10 @@ from django.conf.urls import url
from django.views.decorators.cache import cache_page
from . import views
urlpatterns = [url(r'^oauth/authorize$', views.authorize), ]
urlpatterns = [
url(r'^oauth/authorize$', views.authorize),
url(r'^oauth/requireemail/(?P<oauthid>\d+)', views.RequireEmailView.as_view(), name='require_email'),
]
"""
urlpatterns = [

@ -5,8 +5,12 @@ from .oauthmanager import WBOauthManager, GoogleOauthManager, get_manager_by_typ
from django.conf import settings
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth import get_user_model
from .models import oauthuser
from .models import OAuthUser
from django.contrib.auth import login
from django.shortcuts import get_object_or_404
from django.views.generic import FormView, RedirectView
from oauth.forms import RequireEmailForm
from django.core.urlresolvers import reverse
def authorize(request):
@ -25,16 +29,81 @@ def authorize(request):
author = None
if user:
email = user.email
email = None
if email:
author = get_user_model().objects.get(email=email)
if not author:
author = get_user_model().objects.create_user(username=user["name"], email=email)
author = get_user_model().objects.create_user(username=user.nikename, email=email)
user.author = author
user.save()
login(request, author)
return HttpResponseRedirect('/')
if not email:
author = get_user_model().objects.create_user(username=user["name"], email=email)
author = get_user_model().objects.create_user(username=user.nikename)
user.author = author
user.save()
url = reverse('oauth:require_email', kwargs=
{
'oauthid': user.id
})
print(url)
return HttpResponseRedirect(url)
"""
def require_email(request, oauthid):
oauthuser = get_object_or_404(OAuthUser, pk=oauthid)
if oauthuser.email:
return HttpResponseRedirect('/')
"""
class RequireEmailView(FormView):
form_class = RequireEmailForm
template_name = 'oauth/require_email.html'
def get(self, request, *args, **kwargs):
oauthid = self.kwargs['oauthid']
oauthuser = get_object_or_404(OAuthUser, pk=oauthid)
if oauthuser.email:
pass
# return HttpResponseRedirect('/')
return super(RequireEmailView, self).get(request, *args, **kwargs)
def get_initial(self):
oauthid = self.kwargs['oauthid']
return {
'email': '',
'oauthid': oauthid
}
def get_context_data(self, **kwargs):
oauthid = self.kwargs['oauthid']
oauthuser = get_object_or_404(OAuthUser, pk=oauthid)
if oauthuser.picture:
kwargs['picture'] = oauthuser.picture
return super(RequireEmailView, self).get_context_data(**kwargs)
def form_valid(self, form):
email = form.cleaned_data['email']
oauthid = form.cleaned_data['oauthid']
oauthuser = get_object_or_404(OAuthUser, pk=oauthid)
from DjangoBlog.utils import send_email
url = '123'
content = """
<p>请点击下面链接绑定您的邮箱</p>
<a href="{url}" rel="bookmark">{url}</a>
再次感谢您
<br />
如果上面链接无法打开请将此链接复制至浏览器
{url}
""".format(url=url)
send_email('绑定您的电子邮箱', content, [email, ])
return HttpResponseRedirect('/')
"""

@ -0,0 +1,46 @@
{% extends 'share_layout/base_account.html' %}
{% load static %}
{% block content %}
<div class="container">
<h2 class="form-signin-heading text-center">Binding E-mail account</h2>
<div class="card card-signin">
{% if picture %}
<img class="img-circle profile-img" src="{{ picture }}" alt="">
{% else %}
<img class="img-circle profile-img" src="{% static 'blog/img/avatar.png' %}" alt="">
{% endif %}
<form class="form-signin" action="" 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 }}
{{ field.errors }}
{% endfor %}
<button class="btn btn-lg btn-primary btn-block" type="submit">Submit</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>
<p class="text-center">
<a href="{% url "account:login" %}">Sign In</a>
</p>
</div> <!-- /container -->
{% endblock %}
Loading…
Cancel
Save