Exemplo n.º 1
0
def oauth2_callback(request):
    """ View that handles the user's return from OAuth2 provider.

    This view verifies the CSRF state and OAuth authorization code, and on
    success stores the credentials obtained in the storage provider,
    and redirects to the return_url specified in the authorize view and
    stored in the session.

    Args:
        request: Django request.

    Returns:
         A redirect response back to the return_url.
    """
    if 'error' in request.GET:
        reason = request.GET.get(
            'error_description', request.GET.get('error', ''))
        return http.HttpResponseBadRequest(
            'Authorization failed {0}'.format(reason))

    try:
        encoded_state = request.GET['state']
        code = request.GET['code']
    except KeyError:
        return http.HttpResponseBadRequest(
            'Request missing state or authorization code')

    try:
        server_csrf = request.session[_CSRF_KEY]
    except KeyError:
        return http.HttpResponseBadRequest(
            'No existing session for this flow.')

    try:
        state = json.loads(encoded_state)
        client_csrf = state['csrf_token']
        return_url = state['return_url']
    except (ValueError, KeyError):
        return http.HttpResponseBadRequest('Invalid state parameter.')

    if client_csrf != server_csrf:
        return http.HttpResponseBadRequest('Invalid CSRF token.')

    flow = _get_flow_for_token(client_csrf, request)

    if not flow:
        return http.HttpResponseBadRequest('Missing Oauth2 flow.')

    try:
        credentials = flow.step2_exchange(code)
    except client.FlowExchangeError as exchange_error:
        return http.HttpResponseBadRequest(
            'An error has occurred: {0}'.format(exchange_error))

    get_storage(request).put(credentials)

    signals.oauth2_authorized.send(sender=signals.oauth2_authorized,
                                   request=request, credentials=credentials)

    return shortcuts.redirect(return_url)
Exemplo n.º 2
0
def oauth2_callback(request):
    """ View that handles the user's return from OAuth2 provider.

    This view verifies the CSRF state and OAuth authorization code, and on
    success stores the credentials obtained in the storage provider,
    and redirects to the return_url specified in the authorize view and
    stored in the session.

    Args:
        request: Django request.

    Returns:
         A redirect response back to the return_url.
    """
    if 'error' in request.GET:
        reason = request.GET.get(
            'error_description', request.GET.get('error', ''))
        return http.HttpResponseBadRequest(
            'Authorization failed {0}'.format(reason))

    try:
        encoded_state = request.GET['state']
        code = request.GET['code']
    except KeyError:
        return http.HttpResponseBadRequest(
            'Request missing state or authorization code')

    try:
        server_csrf = request.session[_CSRF_KEY]
    except KeyError:
        return http.HttpResponseBadRequest(
            'No existing session for this flow.')

    try:
        state = json.loads(encoded_state)
        client_csrf = state['csrf_token']
        return_url = state['return_url']
    except (ValueError, KeyError):
        return http.HttpResponseBadRequest('Invalid state parameter.')

    if client_csrf != server_csrf:
        return http.HttpResponseBadRequest('Invalid CSRF token.')

    flow = _get_flow_for_token(client_csrf, request)

    if not flow:
        return http.HttpResponseBadRequest('Missing Oauth2 flow.')

    try:
        credentials = flow.step2_exchange(code)
    except client.FlowExchangeError as exchange_error:
        return http.HttpResponseBadRequest(
            'An error has occurred: {0}'.format(exchange_error))

    get_storage(request).put(credentials)

    signals.oauth2_authorized.send(sender=signals.oauth2_authorized,
                                   request=request, credentials=credentials)

    return shortcuts.redirect(return_url)
Exemplo n.º 3
0
def oauth2_authorize(request):
    """ View to start the OAuth2 Authorization flow.

     This view starts the OAuth2 authorization flow. If scopes is passed in
     as a  GET URL parameter, it will authorize those scopes, otherwise the
     default scopes specified in settings. The return_url can also be
     specified as a GET parameter, otherwise the referer header will be
     checked, and if that isn't found it will return to the root path.

    Args:
       request: The Django request object.

    Returns:
         A redirect to Google OAuth2 Authorization.
    """
    return_url = request.GET.get('return_url', None)

    # Model storage (but not session storage) requires a logged in user
    if django_util.oauth2_settings.storage_model:
        if not request.user.is_authenticated():
            return redirect('{0}?next={1}'.format(
                settings.LOGIN_URL, parse.quote(request.get_full_path())))
        # This checks for the case where we ended up here because of a logged
        # out user but we had credentials for it in the first place
        elif get_storage(request).get() is not None:
            return redirect(return_url)

    scopes = request.GET.getlist('scopes', django_util.oauth2_settings.scopes)

    if not return_url:
        return_url = request.META.get('HTTP_REFERER', '/')
    flow = _make_flow(request=request, scopes=scopes, return_url=return_url)
    auth_url = flow.step1_get_authorize_url()
    return shortcuts.redirect(auth_url)
Exemplo n.º 4
0
def oauth2_authorize(request):
    """ View to start the OAuth2 Authorization flow.

     This view starts the OAuth2 authorization flow. If scopes is passed in
     as a  GET URL parameter, it will authorize those scopes, otherwise the
     default scopes specified in settings. The return_url can also be
     specified as a GET parameter, otherwise the referer header will be
     checked, and if that isn't found it will return to the root path.

    Args:
       request: The Django request object.

    Returns:
         A redirect to Google OAuth2 Authorization.
    """
    return_url = request.GET.get('return_url', None)

    # Model storage (but not session storage) requires a logged in user
    if django_util.oauth2_settings.storage_model:
        if not request.user.is_authenticated():
            return redirect('{0}?next={1}'.format(
                settings.LOGIN_URL, parse.quote(request.get_full_path())))
        # This checks for the case where we ended up here because of a logged
        # out user but we had credentials for it in the first place
        elif get_storage(request).get() is not None:
            return redirect(return_url)

    scopes = request.GET.getlist('scopes', django_util.oauth2_settings.scopes)

    if not return_url:
        return_url = request.META.get('HTTP_REFERER', '/')
    flow = _make_flow(request=request, scopes=scopes, return_url=return_url)
    auth_url = flow.step1_get_authorize_url()
    return shortcuts.redirect(auth_url)
Exemplo n.º 5
0
 def test_session_delete_nothing(self):
     request = MockObjectWithSession(self.session)
     django_storage = get_storage(request)
     django_storage.delete()
Exemplo n.º 6
0
 def test_session_delete(self):
     self.session[_CREDENTIALS_KEY] = "test_val"
     request = MockObjectWithSession(self.session)
     django_storage = get_storage(request)
     django_storage.delete()
     self.assertIsNone(self.session.get(_CREDENTIALS_KEY))
Exemplo n.º 7
0
 def test_session_delete_nothing(self):
     request = MockObjectWithSession(self.session)
     django_storage = django_util.get_storage(request)
     django_storage.delete()
Exemplo n.º 8
0
 def test_session_delete(self):
     self.session[django_util._CREDENTIALS_KEY] = "test_val"
     request = MockObjectWithSession(self.session)
     django_storage = django_util.get_storage(request)
     django_storage.delete()
     self.assertIsNone(self.session.get(django_util._CREDENTIALS_KEY))