Exemplo n.º 1
0
        def wrapper(request, backend, *args, **kwargs):
            if redirect_name:
                redirect = reverse(redirect_name, args=(backend,))
            else:
                redirect = request.path
            backend = get_backend(backend, request, redirect)

            if not backend:
                return HttpResponseServerError("Incorrect authentication " + "service")

            RAISE_EXCEPTIONS = backend_setting(backend, "SOCIAL_AUTH_RAISE_EXCEPTIONS", setting("DEBUG"))
            try:
                return func(request, backend, *args, **kwargs)
            except Exception, e:  # some error ocurred
                if RAISE_EXCEPTIONS:
                    raise
                log("error", unicode(e), exc_info=True, extra={"request": request})

                url = None
                mod, func_name = PROCESS_EXCEPTIONS.rsplit(".", 1)
                try:
                    process = getattr(import_module(mod), func_name, lambda *args: None)
                except ImportError:
                    pass
                else:
                    url = process(request, backend, e)

                if not url:
                    url = backend_setting(backend, "SOCIAL_AUTH_BACKEND_ERROR_URL", LOGIN_ERROR_URL)
                return HttpResponseRedirect(url)
Exemplo n.º 2
0
def odnoklassniki_api(data, api_url, public_key, client_secret,
                      request_type='oauth'):
    ''' Calls Odnoklassniki REST API method
        http://dev.odnoklassniki.ru/wiki/display/ok/Odnoklassniki+Rest+API
    '''
    data.update({
        'application_key': public_key,
        'format': 'JSON'
    })
    if request_type == 'oauth':
        data['sig'] = odnoklassniki_oauth_sig(data, client_secret)
    elif request_type == 'iframe_session':
        data['sig'] = odnoklassniki_iframe_sig(data,
                                               data['session_secret_key'])
    elif request_type == 'iframe_nosession':
        data['sig'] = odnoklassniki_iframe_sig(data, client_secret)
    else:
        msg = 'Unknown request type {0}. How should it be signed?'
        raise AuthFailed(msg.format(request_type))
    params = urlencode(data)
    request = Request('{0}fb.do?{1}'.format(api_url, params))
    try:
        return simplejson.loads(dsa_urlopen(request).read())
    except (TypeError, KeyError, IOError, ValueError, IndexError):
        log('error', 'Could not load data from Odnoklassniki.',
            exc_info=True, extra=dict(data=params))
        return None
Exemplo n.º 3
0
def vkontakte_api(method, data):
    """Calls VKontakte OpenAPI method
        http://vkontakte.ru/apiclub,
        http://vkontakte.ru/pages.php?o=-1&p=%C2%FB%EF%EE%EB%ED%E5%ED%E8%E5%20
                                             %E7%E0%EF%F0%EE%F1%EE%E2%20%EA%20
                                             API
    """

    # We need to perform server-side call if no access_token
    if not 'access_token' in data:
        if not 'v' in data:
            data['v'] = VKONTAKTE_API_VERSION

        if not 'api_id' in data:
            data['api_id'] = _api_get_val_fun('id', 'VKONTAKTE_APP_ID')

        data['method'] = method
        data['format'] = 'json'

        url = VKONTAKTE_SERVER_API_URL
        secret = _api_get_val_fun('key', 'VKONTAKTE_APP_SECRET')

        param_list = sorted(list(item + '=' + data[item] for item in data))
        data['sig'] = md5(''.join(param_list) + secret).hexdigest()
    else:
        url = VKONTAKTE_API_URL + method

    params = urlencode(data)
    url += '?' + params
    try:
        return simplejson.load(dsa_urlopen(url))
    except (TypeError, KeyError, IOError, ValueError, IndexError):
        log('error', 'Could not load data from VKontakte.',
            exc_info=True, extra=dict(data=data))
        return None
Exemplo n.º 4
0
    def auth_complete(self, *args, **kwargs):
        """Completes loging process, must return user instance"""
        if not 'assertion' in self.data:
            raise AuthMissingParameter(self, 'assertion')

        data = urlencode({
            'assertion': self.data['assertion'],
            'audience': self.request.get_host()
        })

        try:
            response = simplejson.load(
                dsa_urlopen(BROWSER_ID_SERVER, data=data))
        except ValueError:
            log('error',
                'Could not load user data from BrowserID.',
                exc_info=True)
        else:
            if response.get('status') == 'failure':
                log('debug', 'Authentication failed.')
                raise AuthFailed(self)

            kwargs.update({
                'auth': self,
                'response': response,
                self.AUTH_BACKEND.name: True
            })
            return authenticate(*args, **kwargs)
Exemplo n.º 5
0
    def auth_complete(self, *args, **kwargs):
        """Completes loging process, must return user instance"""
        if not 'assertion' in self.data:
            raise AuthMissingParameter(self, 'assertion')

        data = urlencode({
            'assertion': self.data['assertion'],
            'audience': self.request.get_host()
        })

        try:
            response = simplejson.load(dsa_urlopen(BROWSER_ID_SERVER,
                                                   data=data))
        except ValueError:
            log('error', 'Could not load user data from BrowserID.',
                exc_info=True)
        else:
            if response.get('status') == 'failure':
                log('debug', 'Authentication failed.')
                raise AuthFailed(self)

            kwargs.update({
                'auth': self,
                'response': response,
                self.AUTH_BACKEND.name: True
            })
            return authenticate(*args, **kwargs)
Exemplo n.º 6
0
    def user_data(self, access_token, response, *args, **kwargs):
        """Loads user data from service"""
        params = {"oauth_token": access_token, "format": "json", "text": 1}

        url = self.get_api_url() + "?" + urlencode(params)
        try:
            return simplejson.load(dsa_urlopen(url))
        except (ValueError, IndexError):
            log("error", "Could not load data from Yandex.", exc_info=True, extra=dict(data=params))
            return None
Exemplo n.º 7
0
    def user_data(self, access_token, response, *args, **kwargs):
        """Loads user data from service"""
        params = {'oauth_token': access_token,
                  'format': 'json',
                  'text': 1,
                  }

        url = self.get_api_url() + '?' + urlencode(params)
        try:
            return simplejson.load(dsa_urlopen(url))
        except (ValueError, IndexError):
            log('error', 'Could not load data from Yandex.',
                exc_info=True, extra=dict(data=params))
            return None
Exemplo n.º 8
0
def mailru_api(data):
    """ Calls Mail.ru REST API method
        http://api.mail.ru/docs/guides/restapi/
    """
    data.update({'app_id': settings.MAILRU_OAUTH2_CLIENT_KEY, 'secure': '1'})
    data['sig'] = mailru_sig(data)

    params = urlencode(data)
    request = Request(MAILRU_API_URL, params)
    try:
        return simplejson.loads(dsa_urlopen(request).read())
    except (TypeError, KeyError, IOError, ValueError, IndexError):
        log('error', 'Could not load data from Mail.ru.',
            exc_info=True, extra=dict(data=params))
        return None
Exemplo n.º 9
0
def mailru_api(data):
    """ Calls Mail.ru REST API method
        http://api.mail.ru/docs/guides/restapi/
    """
    data.update({'app_id': settings.MAILRU_OAUTH2_CLIENT_KEY, 'secure': '1'})
    data['sig'] = mailru_sig(data)

    params = urlencode(data)
    request = Request(MAILRU_API_URL, params)
    try:
        return simplejson.loads(dsa_urlopen(request).read())
    except (TypeError, KeyError, IOError, ValueError, IndexError):
        log('error',
            'Could not load data from Mail.ru.',
            exc_info=True,
            extra=dict(data=params))
        return None
Exemplo n.º 10
0
    def user_data(self, access_token, *args, **kwargs):
        """Loads user data from service"""
        data = None
        params = backend_setting(self, self.EXTRA_PARAMS_VAR_NAME, {})
        params['access_token'] = access_token
        url = FACEBOOK_ME + urlencode(params)

        try:
            data = simplejson.load(dsa_urlopen(url))
        except ValueError:
            extra = {'access_token': sanitize_log_data(access_token)}
            log('error',
                'Could not load user data from Facebook.',
                exc_info=True,
                extra=extra)
        except HTTPError:
            extra = {'access_token': sanitize_log_data(access_token)}
            log('error',
                'Error validating access token.',
                exc_info=True,
                extra=extra)
            raise AuthTokenError(self)
        else:
            log('debug',
                'Found user data for token %s',
                sanitize_log_data(access_token),
                extra={'data': data})
        return data
Exemplo n.º 11
0
def vkontakte_api(method, data):
    """Calls VKontakte OpenAPI method
        http://vkontakte.ru/apiclub,
        http://vkontakte.ru/pages.php?o=-1&p=%C2%FB%EF%EE%EB%ED%E5%ED%E8%E5%20
                                             %E7%E0%EF%F0%EE%F1%EE%E2%20%EA%20
                                             API
    """

    # We need to perform server-side call if no access_token
    if not 'access_token' in data:
        if not 'v' in data:
            data['v'] = VKONTAKTE_API_VERSION

        if not 'api_id' in data:
            data['api_id'] = _api_get_val_fun('id', 'VKONTAKTE_APP_ID')

        data['method'] = method
        data['format'] = 'json'

        url = VKONTAKTE_SERVER_API_URL
        secret = _api_get_val_fun('key', 'VKONTAKTE_APP_SECRET')

        param_list = sorted(list(item + '=' + data[item] for item in data))
        data['sig'] = md5(''.join(param_list) + secret).hexdigest()
    else:
        url = VKONTAKTE_API_URL + method

    params = urlencode(data)
    url += '?' + params
    try:
        return simplejson.load(dsa_urlopen(url))
    except (TypeError, KeyError, IOError, ValueError, IndexError):
        log('error',
            'Could not load data from VKontakte.',
            exc_info=True,
            extra=dict(data=data))
        return None
Exemplo n.º 12
0
        def wrapper(request, backend, *args, **kwargs):
            if redirect_name:
                redirect = reverse(redirect_name, args=(backend,))
            else:
                redirect = request.path
            backend = get_backend(backend, request, redirect)

            if not backend:
                return HttpResponseServerError('Incorrect authentication ' +
                                               'service')

            RAISE_EXCEPTIONS = backend_setting(backend,
                                               'SOCIAL_AUTH_RAISE_EXCEPTIONS',
                                               setting('DEBUG'))
            try:
                return func(request, backend, *args, **kwargs)
            except Exception, e:  # some error ocurred
                if RAISE_EXCEPTIONS:
                    raise
                log('error', unicode(e), exc_info=True, extra={
                    'request': request
                })

                url = None
                mod, func_name = PROCESS_EXCEPTIONS.rsplit('.', 1)
                try:
                    process = getattr(import_module(mod), func_name,
                                      lambda *args: None)
                except ImportError:
                    pass
                else:
                    url = process(request, backend, e)

                if not url:
                    url = backend_setting(backend, 'SOCIAL_AUTH_BACKEND_ERROR_URL',
                                        LOGIN_ERROR_URL)
                return HttpResponseRedirect(url)
Exemplo n.º 13
0
    def user_data(self, access_token, *args, **kwargs):
        """Loads user data from service"""
        data = None
        params = backend_setting(self, self.EXTRA_PARAMS_VAR_NAME, {})
        params["access_token"] = access_token
        url = FACEBOOK_ME + urlencode(params)

        try:
            data = simplejson.load(dsa_urlopen(url))
        except ValueError:
            extra = {"access_token": sanitize_log_data(access_token)}
            log("error", "Could not load user data from Facebook.", exc_info=True, extra=extra)
        except HTTPError:
            extra = {"access_token": sanitize_log_data(access_token)}
            log("error", "Error validating access token.", exc_info=True, extra=extra)
            raise AuthTokenError(self)
        else:
            log("debug", "Found user data for token %s", sanitize_log_data(access_token), extra={"data": data})
        return data