Skip to content

Instantly share code, notes, and snippets.

@cs01
Last active November 3, 2016 00:47
Show Gist options
  • Save cs01/c894f796e1abce8bf16e8bb4e36dc026 to your computer and use it in GitHub Desktop.
Save cs01/c894f796e1abce8bf16e8bb4e36dc026 to your computer and use it in GitHub Desktop.
django view file for google oauth2
"""Example Django views file to use Google's oauth2
Prequisites:
1. You have a the Google+ API enabled at console.developers.google.com
2. You have a OAuth 2.0 client ID
3. In the Client ID you have authorized
- JavaScript origin of http://127.0.0.1:8000
- Redirect URI of http://127.0.0.1:8000/google_callback
4. You have downloaded OAuth 2.0 client credentials to google_auth_data.json
5. You have a urls that direct requests to googlelogin and to google_callback
6. You have run
pip install --upgrade google-api-python-client
pip install httplib2
"""
import httplib2
import oauth2client
from django.http import HttpResponseRedirect, JsonResponse
from apiclient.discovery import build
OAUTH2FLOW_LOGIN = oauth2client.client.flow_from_clientsecrets('google_auth_data.json',
redirect_uri='http://127.0.0.1:8000/google_callback',
scope='email')
GOOGLE_LOGIN_AUTH_URI = OAUTH2FLOW_LOGIN.step1_get_authorize_url()
def googlelogin(request):
return HttpResponseRedirect(GOOGLE_LOGIN_AUTH_URI)
def get_data_from_google_code(code, flow):
"""
Args:
code: authorization code from Google, used to get credentials
flow(oauth2client.client.flow_from_clientsecrets): Used to obtain actual credentials
"""
# Credentials allow access to Google assets that are within the flow's scope
credentials = flow.step2_exchange(code)
# Apply credential to headers, then make a new, authorized request
http = credentials.authorize(httplib2.Http())
google_request = build('plus', 'v1').people().get(userId='me')
google_oauth2_response = google_request.execute(http)
# Finally parse out useful data from the response with the authorized headers
email = google_oauth2_response['emails'][0]['value']
firstname = google_oauth2_response['name']['givenName']
lastname = google_oauth2_response['name']['familyName']
return {'email': email, 'firstname': firstname, 'lastname': lastname}
def google_callback(request):
'''This url callback is definined in Google API's developer console.
Args:
request (HTTP request): an HTTP request that was modified
by google with authorization code as a GET parameter
'''
if 'code' in request.GET:
data = get_data_from_google_code(request.GET['code'], OAUTH2FLOW_LOGIN)
JsonResponse(data)
else:
JsonResponse({'message': 'an error occured when logging in with your google account'})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment