oauth2client.contrib.django_util.decorators module¶
Decorators for Django OAuth2 Flow.
Contains two decorators, oauth_required
and oauth_enabled
.
oauth_required
will ensure that a user has an oauth object containing
credentials associated with the request, and if not, redirect to the
authorization flow.
oauth_enabled
will attach the oauth2 object containing credentials if it
exists. If it doesn’t, the view will still render, but helper methods will be
attached to start the oauth2 flow.
-
oauth2client.contrib.django_util.decorators.
oauth_enabled
(decorated_function=None, scopes=None, **decorator_kwargs)[source]¶ Decorator to enable OAuth Credentials if authorized, and setup the oauth object on the request object to provide helper functions to start the flow otherwise.
views.py¶from oauth2client.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: {0}".format( request.oauth.credentials.id_token['email']) else: return HttpResponse('Here is an OAuth Authorize link: <a href="{0}">Authorize</a>'.format( request.oauth.get_authorize_redirect()))
Parameters: - decorated_function – View function to decorate.
- scopes – Scopes to require, will default.
- decorator_kwargs – Can include
return_url
to specify the URL to return to after OAuth2 authorization is complete.
Returns: The decorated view function.
-
oauth2client.contrib.django_util.decorators.
oauth_required
(decorated_function=None, scopes=None, **decorator_kwargs)[source]¶ Decorator to require OAuth2 credentials for a view.
views.py¶from oauth2client.django_util.decorators import oauth_required @oauth_required def requires_default_scopes(request): email = request.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: {0}, calendar: {1}".format(email, str(events)))
Parameters: - decorated_function – View function to decorate, must have the Django request object as the first argument.
- scopes – Scopes to require, will default.
- decorator_kwargs – Can include
return_url
to specify the URL to return to after OAuth2 authorization is complete.
Returns: An OAuth2 Authorize view if credentials are not found or if the credentials are missing the required scopes. Otherwise, the decorated view.