Skip to content

Commit ebde6b6

Browse files
committed
oauth暂存
1 parent ea09e9a commit ebde6b6

File tree

6 files changed

+99
-23
lines changed

6 files changed

+99
-23
lines changed

DjangoBlog/settings.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -195,24 +195,24 @@
195195
CACHE_MIDDLEWARE_KEY_PREFIX = "djangoblog"
196196
CACHE_MIDDLEWARE_ALIAS = 'default'
197197

198-
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
199-
SESSION_CACHE_ALIAS = 'default'
198+
# SESSION_ENGINE = "django.contrib.sessions.backends.cache"
199+
# SESSION_CACHE_ALIAS = 'default'
200200

201201
OAHUTH = {
202202
'sina': {
203203
'appkey': '3161614143',
204204
'appsecret': 'ee17c099317f872eeddb25204ea46721',
205-
'callbackurl': 'http://www.lylinux.net/oauth/weibo'
205+
'callbackurl': 'http://www.lylinux.net/oauth/authorize?type=weibo'
206206
},
207207
'google': {
208208
'appkey': os.environ.get('GOOGLE_APP_KEY'),
209209
'appsecret': os.environ.get('GOOGLE_APP_SECRET'),
210-
'callbackurl': 'http://www.lylinux.net/oauth/googleauthorize'
210+
'callbackurl': 'http://www.lylinux.net/oauth/authorize?type=google'
211211
},
212212
'github': {
213213
'appkey': os.environ.get('GITHUB_APP_KEY'),
214214
'appsecret': os.environ.get('GITHUB_APP_SECRET'),
215-
'callbackurl': 'http://www.lylinux.net/oauth/githubauthorize'
215+
'callbackurl': 'http://www.lylinux.net/oauth/authorize?type=github'
216216
}
217217
}
218218

oauth/models.py

+16-1
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,22 @@
44
from django.conf import settings
55

66

7+
class oauthuser(models.Model):
8+
author = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name='用户', blank=True, null=True)
9+
openid = models.CharField(max_length=50)
10+
nikename = models.CharField(max_length=50, verbose_name='昵称')
11+
token = models.CharField(max_length=50)
12+
picture = models.CharField(max_length=50, blank=True, null=True)
13+
type = models.CharField(blank=False, null=False, max_length=50)
14+
email = models.CharField(max_length=50, null=True, blank=True)
15+
16+
def __str__(self):
17+
return self.nikename
18+
19+
20+
"""
721
class BaseModel(models.Model):
8-
author = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name='用户')
22+
author = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name='用户', blank=True, null=True)
923
openid = models.CharField(max_length=50)
1024
nikename = models.CharField(max_length=50, verbose_name='昵称')
1125
token = models.CharField(max_length=50)
@@ -34,3 +48,4 @@ class GoogleUserInfo(BaseModel):
3448
class Meta:
3549
verbose_name = "Google"
3650
verbose_name_plural = verbose_name
51+
"""

oauth/oauthmanager.py

+37-7
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
"""
1515

1616
from abc import ABCMeta, abstractmethod, abstractproperty
17+
from oauth.models import oauthuser
1718
from django.conf import settings
1819
import requests
1920
import json
@@ -192,7 +193,7 @@ def get_authorization_url(self):
192193
'client_id': self.client_id,
193194
'response_type': 'code',
194195
'redirect_uri': self.callback_url,
195-
'scope': 'user:email',
196+
'scope': 'user'
196197
}
197198
url = self.AUTH_URL + "?" + urllib.parse.urlencode(params, quote_via=urllib.parse.quote)
198199
return url
@@ -208,16 +209,45 @@ def get_access_token_by_code(self, code):
208209
}
209210
rsp = self.do_post(self.TOKEN_URL, params)
210211
print(rsp)
211-
obj = json.loads(rsp)
212-
self.access_token = str(obj['access_token'])
213-
self.openid = str(obj['id_token'])
212+
try:
213+
from urllib import parse
214+
r = parse.parse_qs(rsp)
215+
self.access_token = (r['access_token'][0])
216+
return self.access_token
217+
except:
218+
return None
214219

215220
def get_oauth_userinfo(self):
216-
if not self.is_authorized:
217-
return None
221+
218222
params = {
219223
'access_token': self.access_token
220224
}
221225
rsp = self.do_get(self.API_URL, params)
222226
print(rsp)
223-
return json.loads(rsp)
227+
try:
228+
datas = json.loads(rsp)
229+
user = oauthuser()
230+
user.picture = datas['avatar_url']
231+
user.nikename = datas['name']
232+
user.openid = datas['id']
233+
user.type = 'github'
234+
if datas['email']:
235+
user.email = datas['email']
236+
237+
return user
238+
except:
239+
logger.info('github oauth error.rsp:' + rsp)
240+
return None
241+
242+
243+
def get_oauth_apps():
244+
applications = BaseOauthManager.__subclasses__()
245+
return list(map(lambda x: x(), applications))
246+
247+
248+
def get_manager_by_type(type):
249+
applications = get_oauth_apps()
250+
finds = list(filter(lambda x: x.ICON_NAME.lower() == type.lower(), applications))
251+
if finds:
252+
return finds[0]
253+
return None

oauth/templatetags/oauth_tags.py

+3-8
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
@file: oauth_tags.py
1313
@time: 2017/3/4 下午3:22
1414
"""
15-
from oauth.oauthmanager import *
15+
from oauth.oauthmanager import get_oauth_apps
1616

1717
from django import template
1818
from django.conf import settings
@@ -22,13 +22,8 @@
2222

2323
@register.inclusion_tag('oauth/oauth_applications.html')
2424
def load_oauth_applications():
25-
applications = BaseOauthManager.__subclasses__()
26-
apps = []
27-
for application in applications:
28-
app = application()
29-
icon = app.ICON_NAME
30-
authorizeurl = app.get_authorization_url()
31-
apps.append((icon, authorizeurl))
25+
applications = get_oauth_apps()
26+
apps = list(map(lambda x: (x.ICON_NAME, x.get_authorization_url()), applications))
3227
return {
3328
'apps': apps
3429
}

oauth/urls.py

+4
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,14 @@
1717
from django.views.decorators.cache import cache_page
1818
from . import views
1919

20+
urlpatterns = [url(r'^oauth/authorize$', views.authorize), ]
21+
22+
"""
2023
urlpatterns = [
2124
url(r'^oauth/wbauthorize/(?P<sitename>\w+)$', views.wbauthorize),
2225
url(r'^oauth/wboauthurl$', views.wboauthurl),
2326
# url(r'^oauth/wbauthorize/(?P<sitename>\w+)$', views.wbauthorize),
2427
url(r'^oauth/googleoauthurl', views.googleoauthurl),
2528
url(r'^oauth/googleauthorize', views.googleauthorize),
2629
]
30+
"""

oauth/views.py

+34-2
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,43 @@
11
from django.shortcuts import render
22

33
# Create your views here.
4-
from .oauthmanager import WBOauthManager, GoogleOauthManager
4+
from .oauthmanager import WBOauthManager, GoogleOauthManager, get_manager_by_type
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 GoogleUserInfo
8+
from .models import oauthuser
99
from django.contrib.auth import login
1010

1111

12+
def authorize(request):
13+
manager = None
14+
type = request.GET.get('type', None)
15+
if not type:
16+
return HttpResponseRedirect('/')
17+
manager = get_manager_by_type(type)
18+
if not manager:
19+
return HttpResponseRedirect('/')
20+
code = request.GET.get('code', None)
21+
rsp = manager.get_access_token_by_code(code)
22+
if not rsp:
23+
return HttpResponseRedirect(manager.get_authorization_url())
24+
user = manager.get_oauth_userinfo()
25+
author = None
26+
if user:
27+
email = user.email
28+
if email:
29+
author = get_user_model().objects.get(email=email)
30+
if not author:
31+
author = get_user_model().objects.create_user(username=user["name"], email=email)
32+
user.author = author
33+
user.save()
34+
login(request, author)
35+
return HttpResponseRedirect('/')
36+
if not email:
37+
author = get_user_model().objects.create_user(username=user["name"], email=email)
38+
39+
40+
"""
1241
def wbauthorize(request, sitename):
1342
manager = WBOauthManager(client_id=settings.OAHUTH['sina']['appkey'],
1443
client_secret=settings.OAHUTH['sina']['appsecret'],
@@ -55,4 +84,7 @@ def googleauthorize(request):
5584
userinfo.nikename = user["name"]
5685
userinfo.save()
5786
login(request, author)
87+
else:
88+
pass
5889
return HttpResponseRedirect('/')
90+
"""

0 commit comments

Comments
 (0)