oauth2client.contrib.django_util package

Module contents

Utilities for the Django web framework

Provides Django views and helpers the make using the OAuth2 web server flow easier. It includes an oauth_required decorator to automatically ensure that user credentials are available, and an oauth_enabled decorator to check if the user has authorized, and helper shortcuts to create the authorization URL otherwise.

Configuration

To configure, you’ll need a set of OAuth2 web application credentials from Google Developer’s Console <https://console.developers.google.com/project/_/apiui/credential>.

Add the helper to your INSTALLED_APPS:

settings.py
 INSTALLED_APPS = (
     # other apps
     "oauth2client.contrib.django_util"
 )

Add the client secrets created earlier to the settings. You can either specify the path to the credentials file in JSON format

settings.py
GOOGLE_OAUTH2_CLIENT_SECRETS_JSON=/path/to/client-secret.json

Or, directly configure the client Id and client secret.

settings.py
GOOGLE_OAUTH2_CLIENT_ID=client-id-field
GOOGLE_OAUTH2_CLIENT_SECRET=client-secret-field

By default, the default scopes for the required decorator only contains the email scopes. You can change that default in the settings.

settings.py
GOOGLE_OAUTH2_SCOPES = ('email', 'https://www.googleapis.com/auth/calendar',)

By default, the decorators will add an oauth object to the Django request object, and include all of its state and helpers inside that object. If the oauth name conflicts with another usage, it can be changed

settings.py
# changes request.oauth to request.google_oauth
GOOGLE_OAUTH2_REQUEST_ATTRIBUTE = 'google_oauth'

Add the oauth2 routes to your application’s urls.py urlpatterns.

urls.py
from oauth2client.contrib.django_util.site import urls as oauth2_urls

urlpatterns += [url(r'^oauth2/', include(oauth2_urls))]

To require OAuth2 credentials for a view, use the oauth2_required decorator. This creates a credentials object with an id_token, and allows you to create an http object to build service clients with. These are all attached to the request.oauth

views.py
from oauth2client.contrib.django_util.decorators import oauth_required

@oauth_required
def requires_default_scopes(request):
   email = request.oauth.credentials.id_token['email']
   service = build(serviceName='calendar', version='v3',
                 http=request.oauth.http,
                developerKey=API_KEY)
   events = service.events().list(calendarId='primary').execute()['items']
   return HttpResponse("email: %s , calendar: %s" % (email, str(events)))

To make OAuth2 optional and provide an authorization link in your own views.

views.py
from oauth2client.contrib.django_util.decorators import oauth_enabled

@oauth_enabled
def optional_oauth2(request):
    if request.oauth.has_credentials():
        # this could be passed into a view
        # request.oauth.http is also initialized
        return HttpResponse("User email: %s"
         % request.oauth.credentials.id_token['email'])
    else:
        return HttpResponse('Here is an OAuth Authorize link:
        <a href="%s">Authorize</a>' % request.oauth.get_authorize_redirect())

If a view needs a scope not included in the default scopes specified in the settings, you can use [incremental auth](https://developers.google.com/identity/sign-in/web/incremental-auth) and specify additional scopes in the decorator arguments.

views.py
@oauth_enabled(scopes=['https://www.googleapis.com/auth/drive'])
def drive_required(request):
    if request.oauth.has_credentials():
        service = build(serviceName='drive', version='v2',
             http=request.oauth.http,
             developerKey=API_KEY)
        events = service.files().list().execute()['items']
        return HttpResponse(str(events))
    else:
        return HttpResponse('Here is an OAuth Authorize link:
        <a href="%s">Authorize</a>' % request.oauth.get_authorize_redirect())

To provide a callback on authorization being completed, use the oauth2_authorized signal:

views.py
from oauth2client.contrib.django_util.signals import oauth2_authorized

def test_callback(sender, request, credentials, **kwargs):
    print "Authorization Signal Received %s" % credentials.id_token['email']

oauth2_authorized.connect(test_callback)
class oauth2client.contrib.django_util.OAuth2Settings(settings_instance)[source]

Bases: object

Initializes Django OAuth2 Helper Settings

This class loads the OAuth2 Settings from the Django settings, and then provides those settings as attributes to the rest of the views and decorators in the module.

scopes

A list of OAuth2 scopes that the decorators and views will use as defaults

request_prefix

The name of the attribute that the decorators use to attach the UserOAuth2 object to the Django request object.

client_id

The OAuth2 Client ID

client_secret

The OAuth2 Client Secret

class oauth2client.contrib.django_util.UserOAuth2(request, scopes=None, return_url=None)[source]

Bases: object

Class to create oauth2 objects on Django request objects containing credentials and helper methods.

credentials

Gets the authorized credentials for this flow, if they exist

get_authorize_redirect()[source]

Creates a URl to start the OAuth2 authorization flow

has_credentials()[source]

Returns True if there are valid credentials for the current user and required scopes.

http

Helper method to create an HTTP client authorized with OAuth2 credentials