여기에 내가 그것을 작동하게하는 관리 방법입니다. 피
import httplib2
from django.conf import settings
from django.contrib.auth import login as auth_login
from django.contrib.auth import logout as auth_logout
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse_lazy
from django.http import (HttpResponse, HttpResponseBadRequest,
HttpResponseRedirect)
from django.shortcuts import redirect
from oauth2client.contrib import xsrfutil
from oauth2client.contrib.django_orm import Storage
from .models import Credentials
def get_flow(request):
flow = OAuth2WebServerFlow(
client_id=settings.GOOGLE_CLIENT_ID,
client_secret=settings.GOOGLE_CLIENT_SECRET,
scope=settings.GOOGLE_SCOPE,
redirect_uri=settings.OAUTH_REDIRECT_URI,
access_type='offline',
state=''
)
return flow
def login(request):
next = request.GET.get('next', 'home')
request.session['next'] = next
if not request.user.is_authenticated():
flow = get_flow(request)
flow.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY,
request.user)
request.session['flow'] = pickle.dumps(flow).decode('iso-8859-1')
redirect_uri = flow.step1_get_authorize_url()
return redirect(redirect_uri)
else:
return redirect(reverse_lazy(next))
def oauth2redirect(request):
# Make sure that the request is from who we think it is
if not xsrfutil.validate_token(settings.SECRET_KEY,
request.GET.get('state').encode('utf8'),
request.user):
return HttpResponseBadRequest()
code = request.GET.get('code')
error = request.GET.get('error')
if code:
flow = get_flow(request)
credentials = flow.step2_exchange(code)
request.session['creds'] = credentials.to_json()
email = credentials.id_token.get("email")
user_exists = False
try:
user = User.objects.get(email=email)
user_exists = True
except User.DoesNotExist:
user = create_user(credentials)
# Since we've oauth2'd the user, we should set the backend appropriately
# This is usually done by the authenticate() method.
user.backend = 'django.contrib.auth.backends.ModelBackend'
# Refresh token is needed for renewing google api access token
if credentials.refresh_token:
user.refresh_token = credentials.refresh_token
user.save()
storage = Storage(Credentials, 'id', user, 'credential')
storage.put(credentials)
# Register that the user has successfully logged in
auth_login(request, user)
next = request.session.get('next', reverse_lazy('/'))
return HttpResponseRedirect(next)
elif code is None and error:
return HttpResponse(str(error))
else:
return HttpResponseBadRequest()
@login_required
def logout(request):
user = request.user
credentials = Credentials.objects.get(id=user.id)
credentials.revoke(httplib2.Http())
credentials.delete()
storage = Storage(Credentials, 'id', user, 'credential')
storage.delete()
auth_logout(request)
return HttpResponseRedirect('/')
python-social-auth를 코드로 대체했거나 함께 사용 했습니까? – HenryM
나는 python-social-auth를 사용하지 않았다. – Kiran
나는 달릴 수조차 없다. 내가'manage.py migrate'를 시도 할 때'ImportError : django_orm이라는 모듈이 없습니다'라는 메시지가 나타납니다. – HenryM