def pipeline(self, pipeline, *args, **kwargs):
        """Pipeline"""
        out = kwargs.copy()

        for name in pipeline:
            mod_name, func_name = name.rsplit(".", 1)
            try:
                mod = import_module(mod_name)
            except ImportError:
                log("exception", "Error importing pipeline %s", name)
            else:
                func = getattr(mod, func_name, None)

                if callable(func):
                    try:
                        result = func(*args, **out) or {}
                    except StopPipeline:
                        # Clean partial pipeline on stop
                        if "request" in kwargs:
                            clean_partial_pipeline(kwargs["request"])
                        break

                    if isinstance(result, dict):
                        out.update(result)
                    else:
                        return result
        return out
Exemple #2
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 or service API settings not available!"
                )

            try:
                return func(request, backend, *args, **kwargs)
            except Exception, e:  # some error ocurred
                if RAISE_EXCEPTIONS:
                    raise
                backend_name = backend.AUTH_BACKEND.name

                log("error", unicode(e), exc_info=True, extra=dict(request=request))

                if "django.contrib.messages" in setting("INSTALLED_APPS"):
                    from django.contrib.messages.api import error

                    error(request, unicode(e), extra_tags=backend_name)
                else:
                    log("warn", "Messages framework not in place, some " + "errors have not been shown to the user.")

                url = backend_setting(backend, "SOCIAL_AUTH_BACKEND_ERROR_URL", LOGIN_ERROR_URL)
                return HttpResponseRedirect(url)
Exemple #3
0
def vk_api(method, data, is_app=False):
    """Calls VK OpenAPI method
        https://vk.com/apiclub,
        https://vk.com/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%20API
    """

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

        if not 'api_id' in data:
            data['api_id'] = setting('VKAPP_APP_ID' if is_app else 'VK_APP_ID')

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

        url = VK_SERVER_API_URL
        secret = setting('VKAPP_API_SECRET' if is_app else 'VK_API_SECRET')

        param_list = sorted(list(item + '=' + data[item] for item in data))
        data['sig'] = md5(''.join(param_list) + secret).hexdigest()
    else:
        url = VK_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 vk.com',
            exc_info=True,
            extra=dict(data=data))
        return None
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
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
Exemple #6
0
    def tumblr_audio(self, request, id, p):
        """
        Post an audio blogpost to the connected Tumblr blog
        
        :Decorators: ``rest_login_required, must_be_owner``
        :Rest Types: ``GET, POST``
        :URL: ``^(?P<id>[0-9]+)/tumblr/audio(?:/$|.(html|json)$)``
        """
        material_dict = p.get_material_wrapper()

        # Check if this project is connected to a Tumblt blog
        if not material_dict['tumblr']:
            return self.show(request, id, errors='You have to connect a Tumblr Blog in order to complete this action. Click on "Manage Material" to link your blog to this project.')

        if request.method == 'POST':
            form = Tumblr_AudioForm(request.POST, request.FILES)
            if form.is_valid():
                new_source  = form.cleaned_data['source']
                try:
                    p.material.tumblr_add_audio(request.user, new_source)
                except UploadException, e:
                    log('error', unicode(e), exc_info=True, extra={'request': request})
                    return self.show(request, id, errors="Something went wrong. Please, retry")
                except ClearanceException:
                    return self.show(request, id, errors="You can't modify a blog you don't own.")
                except Exception, e:
                    log('error', unicode(e), exc_info=True, extra={'request': request})
                    return self.show(request, id, errors="Something went wrong. Please, retry")
Exemple #7
0
    def pipeline(self, pipeline, *args, **kwargs):
        """Pipeline"""
        out = kwargs.copy()

        for name in pipeline:
            mod_name, func_name = name.rsplit('.', 1)
            try:
                mod = import_module(mod_name)
            except ImportError:
                log('exception', 'Error importing pipeline %s', name)
            else:
                func = getattr(mod, func_name, None)

                if callable(func):
                    try:
                        result = func(*args, **out) or {}
                    except StopPipeline:
                        # Clean partial pipeline on stop
                        if 'request' in kwargs:
                            clean_partial_pipeline(kwargs['request'])
                        break

                    if isinstance(result, dict):
                        out.update(result)
                    else:
                        return result
        return out
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
Exemple #9
0
    def flickr_add(self, request, id, p):
        """
        Post a new photo to the connected Flickr photoset
        
        :Decorators: ``rest_login_required, must_be_owner``
        :Rest Types: ``GET, POST``
        :URL: ``^(?P<id>[0-9]+)/flickr/add(?:/$|.(html|json)$)``
        """
        material_dict = p.get_material_wrapper()

        # Check if this project is connected to a Flickr Photoset
        if not material_dict['flickr']:
            return self.show(request, id, errors='You have to connect a Flickr Photoset in order to complete this action. Click on "Manage Material" to link one of your Photosets to this project.')

        if request.method == 'POST':
            form = FlickrForm(request.POST, request.FILES)
            if form.is_valid():
                new_title       = form.cleaned_data['title']
                new_description = form.cleaned_data['description']
                new_photo       = form.cleaned_data['image']
                
                # Upload photo to flickr
                try:
                    p.material.flickr_add_photo(request.user, new_title, new_description, new_photo)
                except UploadException, e:
                    log('error', unicode(e), exc_info=True, extra={'request': request})
                    return self.show(request, id, errors="Something went wrong. Please, retry")
                except ClearanceException:
                    return self.show(request, id, errors="Photoset not found. Are you sure you are the owner of the linked photoset?")
                except Exception, e:
                    log('error', unicode(e), exc_info=True, extra={'request': request})
                    return self.show(request, id, errors="Something went wrong. Please, retry")
Exemple #10
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
Exemple #11
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')

            try:
                return func(request, backend, *args, **kwargs)
            except Exception, e:  # some error ocurred
                if setting('DEBUG'):
                    raise
                backend_name = backend.AUTH_BACKEND.name

                log('error', unicode(e), exc_info=True,
                    extra=dict(request=request))

                if 'django.contrib.messages' in setting('INSTALLED_APPS'):
                    from django.contrib.messages.api import error
                    error(request, unicode(e), extra_tags=backend_name)
                else:
                    log('warn', 'Messages framework not in place, some '+
                                'errors have not been shown to the user.')

                url = setting('SOCIAL_AUTH_BACKEND_ERROR_URL', LOGIN_ERROR_URL)
                return HttpResponseRedirect(url)
Exemple #12
0
def vk_api(method, data, is_app=False):
    """Calls VK OpenAPI method
        https://vk.com/apiclub,
        https://vk.com/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%20API
    """

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

        if not 'api_id' in data:
            data['api_id'] = setting('VKAPP_APP_ID' if is_app else 'VK_APP_ID')

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

        url = VK_SERVER_API_URL
        secret = setting('VKAPP_API_SECRET' if is_app else 'VK_API_SECRET')

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

    params = urlencode(data)
    url += '?' + params
    try:
        return json.load(dsa_urlopen(url))
    except (TypeError, KeyError, IOError, ValueError, IndexError):
        log('error', 'Could not load data from vk.com',
            exc_info=True, extra=dict(data=data))
        return None
Exemple #13
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')

            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})

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

                url = backend_setting(backend, 'SOCIAL_AUTH_BACKEND_ERROR_URL',
                                      LOGIN_ERROR_URL)
                return HttpResponseRedirect(url)
    def pipeline(self, pipeline, *args, **kwargs):
        """Pipeline"""
        out = kwargs.copy()

        if 'pipeline_index' in kwargs:
            base_index = int(kwargs['pipeline_index'])
        else:
            base_index = 0

        for idx, name in enumerate(pipeline):
            out['pipeline_index'] = base_index + idx
            mod_name, func_name = name.rsplit('.', 1)
            try:
                mod = import_module(mod_name)
            except ImportError:
                log('exception', 'Error importing pipeline %s', name)
            else:
                func = getattr(mod, func_name, None)

                if callable(func):
                    try:
                        result = func(*args, **out) or {}
                    except StopPipeline:
                        # Clean partial pipeline on stop
                        if 'request' in kwargs:
                            clean_partial_pipeline(kwargs['request'])
                        break

                    if isinstance(result, dict):
                        out.update(result)
                    else:
                        return result
        return out
    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)
Exemple #16
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)
Exemple #17
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
                })

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

                url = backend_setting(backend, 'SOCIAL_AUTH_BACKEND_ERROR_URL',
                                      LOGIN_ERROR_URL)
                return HttpResponseRedirect(url)
    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
Exemple #19
0
def etvnet_api(data):
    """ Calls Mail.ru REST API method
        http://api.mail.ru/docs/guides/restapi/
    """
    request = Request(ETVNET_API_URL, urlencode(data))
    try:
        return simplejson.loads(dsa_urlopen(request).read())
    except (TypeError, KeyError, IOError, ValueError, IndexError):
        log('error', 'Could not load data from eTVnet.com.',
            exc_info=True, extra=dict(data=params))
        return None
    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(urlopen(url))
        except (ValueError, IndexError):
            log('error', 'Could not load data from Yandex.',
                exc_info=True, extra=dict(data=params))
            return None
    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 json.load(dsa_urlopen(url))
        except (ValueError, IndexError):
            log('error', 'Could not load data from Yandex.',
                exc_info=True, extra=dict(data=params))
            return None
Exemple #22
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
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(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
    def user_data(self, access_token):
        """Loads user data from service"""
        data = None
        url = FACEBOOK_ME + urlencode({'access_token': access_token})

        try:
            data = simplejson.load(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)
        else:
            log('debug', 'Found user data for token %s',
                sanitize_log_data(access_token),
                extra=dict(data=data))
        return data
Exemple #25
0
    def user_data(self, access_token):
        """Loads user data from service"""
        data = None
        url = FACEBOOK_ME + urlencode({'access_token': access_token})

        try:
            data = simplejson.load(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)
        else:
            log('debug', 'Found user data for token %s',
                sanitize_log_data(access_token),
                extra=dict(data=data))
        return data
    def authenticate(self, *args, **kwargs):
        """Authenticate user using social credentials

        Authentication is made if this is the correct backend, backend
        verification is made by kwargs inspection for current backend
        name presence.
        """

        try:
            # Validate backend and arguments. Require that the Social Auth
            # response be passed in as a keyword argument, to make sure we
            # don't match the username/password calling conventions of
            # authenticate.
            if not (self.name and kwargs.get(self.name) and "response" in kwargs):
                return None

            response = kwargs.get("response")
            pipeline = PIPELINE
            kwargs = kwargs.copy()
            kwargs["backend"] = self

            if "pipeline_index" in kwargs:
                pipeline = pipeline[kwargs["pipeline_index"] :]
            else:
                kwargs["details"] = self.get_user_details(response)
                kwargs["uid"] = self.get_user_id(kwargs["details"], response)
                kwargs["is_new"] = False

            out = self.pipeline(pipeline, *args, **kwargs)
            if not isinstance(out, dict):
                return out

            social_user = out.get("social_user")
            if social_user:
                # define user.social_user attribute to track current social
                # account
                user = social_user.user
                user.social_user = social_user
                user.is_new = out.get("is_new")
                return user
        except Exception as e:
            import traceback

            log("warn", "Uncaught exception in authenticate: %s" % e)
            log("warn", "Traceback: %s" % traceback.format_exc())
            raise
    def authenticate(self, *args, **kwargs):
        """Authenticate user using social credentials

        Authentication is made if this is the correct backend, backend
        verification is made by kwargs inspection for current backend
        name presence.
        """

        try:
            # Validate backend and arguments. Require that the Social Auth
            # response be passed in as a keyword argument, to make sure we
            # don't match the username/password calling conventions of
            # authenticate.
            if not (self.name and kwargs.get(self.name)
                    and 'response' in kwargs):
                return None

            response = kwargs.get('response')
            pipeline = PIPELINE
            kwargs = kwargs.copy()
            kwargs['backend'] = self

            if 'pipeline_index' in kwargs:
                pipeline = pipeline[kwargs['pipeline_index']:]
            else:
                kwargs['details'] = self.get_user_details(response)
                kwargs['uid'] = self.get_user_id(kwargs['details'], response)
                kwargs['is_new'] = False

            out = self.pipeline(pipeline, *args, **kwargs)
            if not isinstance(out, dict):
                return out

            social_user = out.get('social_user')
            if social_user:
                # define user.social_user attribute to track current social
                # account
                user = social_user.user
                user.social_user = social_user
                user.is_new = out.get('is_new')
                return user
        except Exception as e:
            import traceback
            log('warn', 'Uncaught exception in authenticate: %s' % e)
            log('warn', 'Traceback: %s' % traceback.format_exc())
            raise
def odnoklassniki_api(data):
    """ Calls Odnoklassniki REST API method
        http://dev.odnoklassniki.ru/wiki/display/ok/Odnoklassniki+Rest+API
    """
    data.update({
        'application_key': settings.ODNOKLASSNIKI_OAUTH2_APP_KEY,
        'format': 'JSON'
    })
    data['sig'] = odnoklassniki_sig(data)

    params = urlencode(data)
    request = Request(ODNOKLASSNIKI_API_URL + '?' + params)
    try:
        return simplejson.loads(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
Exemple #29
0
    def dec(func):
        @wraps(func)
        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')

            try:
                return func(request, backend, *args, **kwargs)
            except AuthFailed, e:
                backend_name = backend.AUTH_BACKEND.name
                if 'django.contrib.messages' in setting('INSTALLED_APPS'):
                    from django.contrib.messages.api import error
                    error(request, unicode(e), extra_tags=backend_name)
                else:
                    log('warn', 'Messages framework not in place, some '+
                                'errors have not been shown to the user.')
                url = setting('SOCIAL_AUTH_BACKEND_ERROR_URL', LOGIN_ERROR_URL)
                return HttpResponseRedirect(url)
            except Exception, e:  # some error ocurred
                if RAISE_EXCEPTIONS:
                    raise
                log('error', unicode(e), exc_info=True, extra={
                    'request': request
                })

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

                url = backend_setting(backend, 'SOCIAL_AUTH_BACKEND_ERROR_URL',
                                      LOGIN_ERROR_URL)
                return HttpResponseRedirect(url)
Exemple #30
0
def auth_complete(request, backend, user=None, *args, **kwargs):
    """Complete auth process. Return authenticated user or None."""
    if user and not user.is_authenticated():
        user = None

    name = setting('SOCIAL_AUTH_PARTIAL_PIPELINE_KEY', 'partial_pipeline')
    if request.session.get(name):
        data = request.session.pop(name)
        idx, args, kwargs = backend.from_session_dict(data, user=user,
                                                      request=request,
                                                      *args, **kwargs)
        return backend.continue_pipeline(pipeline_index=idx, *args, **kwargs)
    else:
        start = time.time()
        resp = backend.auth_complete(user=user, request=request, *args,
                                     **kwargs)
        duration = time.time() - start
        log('debug', "Time to auth for %s was %s sec" % (backend.AUTH_BACKEND.name, duration))
        return resp
Exemple #31
0
def odnoklassniki_api(data):
    """ Calls Odnoklassniki REST API method
        http://dev.odnoklassniki.ru/wiki/display/ok/Odnoklassniki+Rest+API
    """
    data.update({
        'application_key': settings.ODNOKLASSNIKI_OAUTH2_APP_KEY,
        'format': 'JSON'
    })
    data['sig'] = odnoklassniki_sig(data)

    params = urlencode(data)
    request = Request(ODNOKLASSNIKI_API_URL + '?' + params)
    try:
        return simplejson.loads(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
Exemple #32
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:
            response = requests.get(url)
            if response.status_code == 200:
                data = simplejson.loads(response.text)
            else:
                raise AuthTokenError()
        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 requests.RequestException:
            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
    def user_data(self, access_token, *args, **kwargs):
        """
        Grab user profile information from facebook.

        returns: dict or None
        """

        data = None
        params = backend_setting(self, self.EXTRA_PARAMS_VAR_NAME, {})
        params['access_token'] = access_token
        url = FACEBOOK_ME + urlencode(params)

        try:
            response = dsa_urlopen(url)
            data = json.load(response)
        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
    def user_data(self, access_token, *args, **kwargs):
        """Loads user data from service"""
        data = None
        params = setting('FACEBOOK_PROFILE_EXTRA_PARAMS', {})
        params['access_token'] = access_token
        url = FACEBOOK_ME + urlencode(params)

        try:
            data = simplejson.load(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
Exemple #35
0
    def user_data(self, access_token, *args, **kwargs):
        """
        Grab user profile information from facebook.

        returns: dict or None
        """

        data = None
        params = backend_setting(self, self.EXTRA_PARAMS_VAR_NAME, {})
        params['access_token'] = access_token
        url = FACEBOOK_ME + urlencode(params)

        try:
            response = dsa_urlopen(url)
            data = simplejson.load(response)
        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
Exemple #36
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})
            
        mandatory = backend_setting(self, self.MANDATORY_PERMISSIONS_VAR_NAME, [])
        for permission in mandatory:
            if not data.get(permission, False):
                raise AuthIncomplete(self, 'Missing mandatory permission %s' % permission)
            
        return data
    def pipeline(self, pipeline, *args, **kwargs):
        """Pipeline"""
        out = kwargs.copy()

        for name in pipeline:
            mod_name, func_name = name.rsplit('.', 1)
            try:
                mod = import_module(mod_name)
            except ImportError:
                log('exception', 'Error importing pipeline %s', name)
            else:
                func = getattr(mod, func_name, None)

                if callable(func):
                    try:
                        result = func(*args, **out) or {}
                    except StopPipeline:
                        break

                    if isinstance(result, dict):
                        out.update(result)
                    else:
                        return result
        return out
    def user_data(self, access_token, *args, **kwargs):
        """Loads user data from service"""
        data = None
        params = setting('FACEBOOK_PROFILE_EXTRA_PARAMS', {})
        params['access_token'] = access_token
        url = FACEBOOK_ME + urlencode(params)

        try:
            data = simplejson.load(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
Exemple #39
0
def _log_facebook_http_error(http_error):
    if 400 == http_error.code and 'javascript' == http_error.info().subtype:
        as_json = simplejson.load(http_error)
        pretty = simplejson.dumps(as_json, sort_keys=True, indent=4)
        log('error', 'Facebook HTTP bad request content: %s', pretty)