Ejemplo n.º 1
0
    def auth_complete(self, *args, **kwargs):
        """Completes loging process, must return user instance"""
        access_token = None
        expires = None

        if 'code' in self.data:
            state = self.validate_state()
            url = ACCESS_TOKEN + urlencode({
                'client_id': backend_setting(self, self.SETTINGS_KEY_NAME),
                'redirect_uri': self.get_redirect_uri(state),
                'client_secret': backend_setting(
                    self,
                    self.SETTINGS_SECRET_NAME
                ),
                'code': self.data['code']
            })
            try:
                payload = dsa_urlopen(url)
            except HTTPError:
                raise AuthFailed(self, 'There was an error authenticating '
                                       'the app')

            response = payload.read()
            #parsed_response = cgi.parse_qs(response)
            parsed_response = json.loads(response)

            # print('***********************************************')
            # print(url)
            # print(response)
            # print(parsed_response)
            # print(parsed_response['access_token'])
            # print(parsed_response['expires_in'])
            # print('***********************************************')


            access_token = parsed_response['access_token']
            if 'expires' in parsed_response:
                expires = parsed_response['expires']

        if 'signed_request' in self.data:
            response = load_signed_request(
                self.data.get('signed_request'),
                backend_setting(self, self.SETTINGS_SECRET_NAME)
            )

            if response is not None:
                access_token = response.get('access_token') or\
                               response.get('oauth_token') or\
                               self.data.get('access_token')

                if 'expires' in response:
                    expires = response['expires']

        if access_token:
            return self.do_auth(access_token, expires=expires, *args, **kwargs)
        else:
            if self.data.get('error') == 'access_denied':
                raise AuthCanceled(self)
            else:
                raise AuthException(self)
Ejemplo n.º 2
0
 def response(self):
     if not hasattr(self, '_response'):
         access_token = None
         expires = None
 
         if 'code' in self.data:
             state = self.validate_state()
             url = ACCESS_TOKEN + urlencode({
                 'client_id': backend_setting(self, self.SETTINGS_KEY_NAME),
                 'redirect_uri': self.get_redirect_uri(state),
                 'client_secret': backend_setting(self,
                                                  self.SETTINGS_SECRET_NAME),
                 'code': self.data['code']
             })
             try:
                 self._response = cgi.parse_qs(dsa_urlopen(url).read())
             except HTTPError:
                 raise AuthFailed(self, 'There was an error authenticating '
                                        'the app')
     
         if 'signed_request' in self.data:
             self._response = load_signed_request(self.data.get('signed_request'),
                                            backend_setting(
                                                self,
                                                self.SETTINGS_SECRET_NAME))
     return self._response
Ejemplo n.º 3
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
Ejemplo n.º 4
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)
Ejemplo n.º 5
0
    def auth_complete(self, request, user, *args, **kwargs):
        form = OdnoklassnikiIframeForm(auth=self, data=request.GET)
        if not form.is_valid():
            raise AuthFailed('Cannot authorize: malformed parameters')
        else:
            response = form.get_response()
            extra_user_data = backend_setting(self, 'ODNOKLASSNIKI_APP_EXTRA_USER_DATA_LIST', ())
            base_fields = ('uid', 'first_name', 'last_name', 'name')
            fields = base_fields + extra_user_data
            data = {
                'method': 'users.getInfo',
                'uids': '{0}'.format(response['logged_user_id']),
                'fields': ','.join(fields),
            }
            client_key, client_secret, public_key = self.get_settings()
            details = odnoklassniki_api(data, response['api_server'], public_key, client_secret, 'iframe_nosession')
            if len(details) == 1 and 'uid' in details[0]:
                details = details[0]
                auth_data_fields = backend_setting(self, 'ODNOKLASSNIKI_APP_EXTRA_AUTH_DATA_LIST',
                                             ('api_server', 'apiconnection', 'session_key', 'session_secret_key', 'authorized'))

                for field in auth_data_fields:
                    details[field] = response[field]
                details['extra_data_list'] = fields + auth_data_fields
                kwargs.update({
                    'auth': self,
                    'response': details,
                    self.AUTH_BACKEND.name: True
                })
            else:
                raise AuthFailed('Cannot get user details: API error')
        return authenticate(*args, **kwargs)
Ejemplo n.º 6
0
def associate_complete(request, backend, *args, **kwargs):
    """Authentication complete process"""
    # pop redirect value before the session is trashed on login()
    redirect_value = request.session.get(REDIRECT_FIELD_NAME, '')
    user = auth_complete(request, backend, request.user, *args, **kwargs)

    backend_name = backend.AUTH_BACKEND.name

    messages.add_message(
        request, messages.SUCCESS,
        'You have linked your account with {}.'.format(
            settings.AUTH_PROVIDER_LABELS.get(backend_name, backend_name),
        )
    )

    if not user:
        url = backend_setting(backend, 'LOGIN_ERROR_URL', LOGIN_ERROR_URL)
    elif isinstance(user, HttpResponse):
        return user
    else:
        url = (
            redirect_value or
            backend_setting(backend, 'SOCIAL_AUTH_NEW_ASSOCIATION_REDIRECT_URL') or
            DEFAULT_REDIRECT
        )
    return HttpResponseRedirect(url)
Ejemplo n.º 7
0
def complete_process(request, backend, *args, **kwargs):
    """Authentication complete process"""
    # pop redirect value before the session is trashed on login()
    redirect_value = request.session.get(REDIRECT_FIELD_NAME, '')
    user = auth_complete(request, backend, *args, **kwargs)

    if isinstance(user, HttpResponse):
        return user

    if not user and request.user.is_authenticated():
        return HttpResponseRedirect(redirect_value)

    if user:
        if getattr(user, 'is_active', True):
            # catch is_new flag before login() might reset the instance
            is_new = getattr(user, 'is_new', False)
            login(request, user)
            # user.social_user is the used UserSocialAuth instance defined
            # in authenticate process
            social_user = user.social_user
            if redirect_value:
                request.session[REDIRECT_FIELD_NAME] = redirect_value or \
                                                       DEFAULT_REDIRECT

            if setting('SOCIAL_AUTH_SESSION_EXPIRATION', True):
                # Set session expiration date if present and not disabled by
                # setting. Use last social-auth instance for current provider,
                # users can associate several accounts with a same provider.
                if social_user.expiration_delta():
                    try:
                        request.session.set_expiry(social_user.expiration_delta())
                    except OverflowError:
                        # Handle django time zone overflow, set default expiry.
                        request.session.set_expiry(None)

            # store last login backend name in session
            key = setting('SOCIAL_AUTH_LAST_LOGIN',
                          'social_auth_last_login_backend')
            request.session[key] = social_user.provider

            # Remove possible redirect URL from session, if this is a new
            # account, send him to the new-users-page if defined.
            new_user_redirect = backend_setting(backend,
                                           'SOCIAL_AUTH_NEW_USER_REDIRECT_URL')
            if new_user_redirect and is_new:
                url = new_user_redirect
            else:
                url = redirect_value or \
                      backend_setting(backend,
                                      'SOCIAL_AUTH_LOGIN_REDIRECT_URL') or \
                      DEFAULT_REDIRECT
        else:
            url = backend_setting(backend, 'SOCIAL_AUTH_INACTIVE_USER_URL',
                                  LOGIN_ERROR_URL)
    else:
        msg = setting('LOGIN_ERROR_MESSAGE', None)
        if msg:
            messages.error(request, msg)
        url = backend_setting(backend, 'LOGIN_ERROR_URL', LOGIN_ERROR_URL)
    return HttpResponseRedirect(url)
Ejemplo n.º 8
0
def complete_process(request, backend, *args, **kwargs):
    """Authentication complete process"""
    # pop redirect value before the session is trashed on login()
    redirect_value = request.session.get(REDIRECT_FIELD_NAME, "")
    user = auth_complete(request, backend, *args, **kwargs)
    inv_code = request.session.get("code", "")
    inv_type = request.session.get("inv_type", "")

    if isinstance(user, HttpResponse):
        return user

    if not user and request.user.is_authenticated():
        return HttpResponseRedirect(redirect_value)

    if user:
        if getattr(user, "is_active", True):
            login(request, user)
            request.session["code"] = inv_code
            request.session["inv_type"] = inv_type
            from invite_friends.helpers import accept_invite

            accept_invite(request, user)
            # user.social_user is the used UserSocialAuth instance defined
            # in authenticate process
            social_user = user.social_user

            if setting("SOCIAL_AUTH_SESSION_EXPIRATION", True):
                # Set session expiration date if present and not disabled by
                # setting. Use last social-auth instance for current provider,
                # users can associate several accounts with a same provider.
                if social_user.expiration_delta():
                    request.session.set_expiry(social_user.expiration_delta())

            # store last login backend name in session
            key = setting("SOCIAL_AUTH_LAST_LOGIN", "social_auth_last_login_backend")
            request.session[key] = social_user.provider

            # Remove possible redirect URL from session, if this is a new
            # account, send him to the new-users-page if defined.
            new_user_redirect = backend_setting(backend, "SOCIAL_AUTH_NEW_USER_REDIRECT_URL")
            if new_user_redirect and getattr(user, "is_new", False):
                url = new_user_redirect
            else:
                url = redirect_value or backend_setting(backend, "SOCIAL_AUTH_LOGIN_REDIRECT_URL") or DEFAULT_REDIRECT
        else:
            url = backend_setting(backend, "SOCIAL_AUTH_INACTIVE_USER_URL", LOGIN_ERROR_URL)
    else:
        msg = setting("LOGIN_ERROR_MESSAGE", None)
        if msg:
            messages.error(request, msg)
        url = backend_setting(backend, "LOGIN_ERROR_URL", LOGIN_ERROR_URL)
    return HttpResponseRedirect(url)
Ejemplo n.º 9
0
def associate_complete(request, backend, *args, **kwargs):
    """Authentication complete process"""
    # pop redirect value before the session is trashed on login()
    redirect_value = request.session.get(REDIRECT_FIELD_NAME, "")
    user = auth_complete(request, backend, request.user, *args, **kwargs)

    if not user:
        url = backend_setting(backend, "LOGIN_ERROR_URL", LOGIN_ERROR_URL)
    elif isinstance(user, HttpResponse):
        return user
    else:
        url = backend_setting(backend, "SOCIAL_AUTH_NEW_ASSOCIATION_REDIRECT_URL") or redirect_value or DEFAULT_REDIRECT
    return HttpResponseRedirect(url)
Ejemplo n.º 10
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)
Ejemplo n.º 11
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
Ejemplo n.º 12
0
def disconnect(request, backend, association_id=None):
    """Disconnects given backend from current logged in user."""
    backend.disconnect(request.user, association_id)
    url = request.REQUEST.get(REDIRECT_FIELD_NAME, '') or \
          backend_setting(backend, 'SOCIAL_AUTH_DISCONNECT_REDIRECT_URL') or \
          DEFAULT_REDIRECT
    return HttpResponseRedirect(url)
Ejemplo n.º 13
0
def complete(request, backend, *args, **kwargs):
    """Authentication complete process"""
    # pop redirect value before the session is trashed on login()
    redirect_value = request.session.get(REDIRECT_FIELD_NAME, "")

    backend_name = backend.AUTH_BACKEND.name

    try:
        user = auth_complete(request, backend, request.user, *args, **kwargs)
    except AuthException as exc:
        messages.add_message(request, messages.ERROR, six.text_type(exc))
        user = None
    else:
        messages.add_message(
            request,
            messages.SUCCESS,
            "You have linked your account with {}.".format(
                settings.AUTH_PROVIDER_LABELS.get(backend_name, backend_name)
            ),
        )

    if not user:
        url = redirect_value or ASSOCIATE_ERROR_URL or DEFAULT_REDIRECT
    elif isinstance(user, HttpResponse):
        return user
    else:
        url = redirect_value or backend_setting(backend, "SOCIAL_AUTH_NEW_ASSOCIATION_REDIRECT_URL") or DEFAULT_REDIRECT
    return HttpResponseRedirect(url)
Ejemplo n.º 14
0
    def auth_complete(self, *args, **kwargs):
        if not self.application_auth():
            return HttpResponse(self.auth_html())

        access_token = None
        expires = None

        if 'signed_request' in self.data:
            response = load_signed_request(
                self.data.get('signed_request'),
                backend_setting(self, self.SETTINGS_SECRET_NAME)
            )

            if response is not None:
                access_token = response.get('access_token') or\
                               response.get('oauth_token') or\
                               self.data.get('access_token')

                if 'expires' in response:
                    expires = response['expires']

        if access_token:
            return self.do_auth(access_token, expires=expires, *args, **kwargs)
        else:
            if self.data.get('error') == 'access_denied':
                raise AuthCanceled(self)
            else:
                raise AuthException(self)
Ejemplo n.º 15
0
 def get_redirect_uri(self, request, exception):
     if self.backend is not None:
         return (
             backend_setting(self.backend, 'SOCIAL_AUTH_BACKEND_ERROR_URL')
             or settings.LOGIN_ERROR_URL
         )
     return settings.LOGIN_ERROR_URL
Ejemplo n.º 16
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 = 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
Ejemplo n.º 17
0
    def auth_html(self):
        app_id = backend_setting(self, self.SETTINGS_KEY_NAME)
        ctx = {
            "FACEBOOK_APP_ID": app_id,
            "FACEBOOK_EXTENDED_PERMISSIONS": ",".join(backend_setting(self, self.SCOPE_VAR_NAME)),
            "FACEBOOK_COMPLETE_URI": self.redirect_uri,
            "FACEBOOK_APP_NAMESPACE": APP_NAMESPACE or app_id,
        }

        try:
            fb_template = loader.get_template(LOCAL_HTML)
        except TemplateDoesNotExist:
            fb_template = loader.get_template_from_string(REDIRECT_HTML)
        context = RequestContext(self.request, ctx)

        return fb_template.render(context)
Ejemplo n.º 18
0
 def application_auth(self):
     required_params = ("user_id", "oauth_token")
     data = load_signed_request(self.data.get("signed_request"), backend_setting(self, self.SETTINGS_SECRET_NAME))
     for param in required_params:
         if not param in data:
             return False
     return True
Ejemplo n.º 19
0
    def auth_complete(self, *args, **kwargs):
        if not self.application_auth() and "error" not in self.data:
            return HttpResponse(self.auth_html())

        access_token = None
        expires = None

        if "signed_request" in self.data:
            response = load_signed_request(
                self.data.get("signed_request"), backend_setting(self, self.SETTINGS_SECRET_NAME)
            )

            if response is not None:
                access_token = (
                    response.get("access_token") or response.get("oauth_token") or self.data.get("access_token")
                )

                if "expires" in response:
                    expires = response["expires"]

        if access_token:
            return self.do_auth(access_token, expires=expires, *args, **kwargs)
        else:
            if self.data.get("error") == "access_denied":
                raise AuthCanceled(self)
            else:
                raise AuthException(self)
Ejemplo n.º 20
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
                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)
Ejemplo n.º 21
0
    def auth_complete(self, *args, **kwargs):
        """Completes loging process, must return user instance"""
        access_token = None
        expires = None

        if "code" in self.data:
            state = self.validate_state()
            url = ACCESS_TOKEN + urlencode(
                {
                    "client_id": backend_setting(self, self.SETTINGS_KEY_NAME),
                    "redirect_uri": self.get_redirect_uri(state),
                    "client_secret": backend_setting(self, self.SETTINGS_SECRET_NAME),
                    "code": self.data["code"],
                }
            )
            try:
                payload = dsa_urlopen(url)
            except HTTPError:
                raise AuthFailed(self, "There was an error authenticating " "the app")

            response = payload.read()
            parsed_response = cgi.parse_qs(response)

            access_token = parsed_response["access_token"][0]
            if "expires" in parsed_response:
                expires = parsed_response["expires"][0]

        if "signed_request" in self.data:
            response = load_signed_request(
                self.data.get("signed_request"), backend_setting(self, self.SETTINGS_SECRET_NAME)
            )

            if response is not None:
                access_token = (
                    response.get("access_token") or response.get("oauth_token") or self.data.get("access_token")
                )

                if "expires" in response:
                    expires = response["expires"]

        if access_token:
            return self.do_auth(access_token, expires=expires, *args, **kwargs)
        else:
            if self.data.get("error") == "access_denied":
                raise AuthCanceled(self)
            else:
                raise AuthException(self)
 def get_auth_sig(self):
     secret_key = backend_setting(self.auth, 'ODNOKLASSNIKI_APP_SECRET')
     hash_source = '{0:d}{1:s}{2:s}'.format(
             self.cleaned_data['logged_user_id'],
             self.cleaned_data['session_key'],
             secret_key
     )
     return md5(hash_source).hexdigest()
Ejemplo n.º 23
0
 def signed_request(self):
     if self._signed_request is None:
         response = load_signed_request(
             self.data.get('signed_request', ''),
             backend_setting(self, self.SETTINGS_SECRET_NAME)
         )
         self._signed_request = response
     return self._signed_request
Ejemplo n.º 24
0
 def user_data(self, access_token, *args, **kwargs):
     """Loads user data from service"""
     params = {
         'access_token': access_token,
         'api_secret': backend_setting(self, self.SETTINGS_SECRET_NAME),
     }
     url = DISQUS_CHECK_AUTH + '?' + urlencode(params)
     try:
         return simplejson.load(dsa_urlopen(url))
     except ValueError:
         return None
Ejemplo n.º 25
0
def disconnect(request, backend, association_id=None):

	if request.user.is_authenticated():
		if request.user.password == "!" or not email_re.search(request.user.username):
			request.session['last_page_idecorate'] = '/edit_profile/'
			request.session['fb_auth_error'] = "Ensure that you have updated your email and set password before disconnecting to your %s account." % str(backend.AUTH_BACKEND.name).capitalize()
		else:
			backend.disconnect(request.user, association_id)
	else:
		backend.disconnect(request.user, association_id)
	url = request.REQUEST.get(REDIRECT_FIELD_NAME, '') or backend_setting(backend, 'SOCIAL_AUTH_DISCONNECT_REDIRECT_URL') or DEFAULT_REDIRECT
	return HttpResponseRedirect(url)
Ejemplo n.º 26
0
 def user_data(self, access_token, *args, **kwargs):
     """Loads user data from service"""
     token = access_token.key
     params = {
         'token': token,
         'key': backend_setting(self, self.SETTINGS_KEY_NAME)
     }
     url = TRELLO_USER_DETAILS_URL + '?' + urlencode(params)
     try:
         return json.load(dsa_urlopen(url))
     except ValueError:
         return None
Ejemplo n.º 27
0
def complete_process(request, backend, *args, **kwargs):
    """Authentication complete process"""
    user = auth_complete(request, backend, *args, **kwargs)
    redirect_value = request.session.get(REDIRECT_FIELD_NAME, '')

    if not user and request.user.is_authenticated():
        return HttpResponseRedirect(redirect_value)

    if user and getattr(user, 'is_active', True):
        login(request, user)
        # user.social_user is the used UserSocialAuth instance defined
        # in authenticate process
        social_user = user.social_user
        if redirect_value:
            request.session[REDIRECT_FIELD_NAME] = redirect_value or\
                                                   DEFAULT_REDIRECT
        if SESSION_EXPIRATION :
            # Set session expiration date if present and not disabled by
            # setting. Use last social-auth instance for current provider,
            # users can associate several accounts with a same provider.
            if social_user.expiration_delta():
                request.session.set_expiry(social_user.expiration_delta())

        # store last login backend name in session
        request.session[SOCIAL_AUTH_LAST_LOGIN] = social_user.provider

        # Remove possible redirect URL from session, if this is a new account,
        # send him to the new-users-page if defined.
        new_user_redirect = backend_setting(backend,
            'SOCIAL_AUTH_NEW_USER_REDIRECT_URL')
        if new_user_redirect and getattr(user, 'is_new', False):
            url = new_user_redirect
        else:
            url = redirect_value or\
                  backend_setting(backend,
                      'SOCIAL_AUTH_LOGIN_REDIRECT_URL') or\
                  DEFAULT_REDIRECT
    else:
        url = backend_setting(backend, 'LOGIN_ERROR_URL', LOGIN_ERROR_URL)
    return HttpResponseRedirect(url)
Ejemplo n.º 28
0
    def auth_complete(self, *args, **kwargs):
        """Completes loging process, must return user instance"""
        access_token = None
        expires = None
        if 'code' in self.data:
            state = self.validate_state()
            data = urlencode({
                'client_id': backend_setting(self, self.SETTINGS_KEY_NAME),
                'redirect_uri': self.get_redirect_uri(state),
                'client_secret': backend_setting(self,
                                                 self.SETTINGS_SECRET_NAME),
                'code': self.data['code']
            })
            try:
                response = cgi.parse_qs(dsa_urlopen(STACKEXCHANGE_ACCESS_TOKEN_URL, data).read())
            except HTTPError, e:
                raise AuthFailed(self, 'There was an error authenticating '
                                       'the app')

            access_token = response['access_token'][0]
            if 'expires' in response:
                expires = response['expires'][0]
Ejemplo n.º 29
0
def associate_complete(request, backend, *args, **kwargs):
    """Authentication complete process"""
    # pop redirect value before the session is trashed on login()
    redirect_value = request.session.pop(REDIRECT_FIELD_NAME, '') or \
                     request.REQUEST.get(REDIRECT_FIELD_NAME, '')

    user = auth_complete(request, backend, request.user, *args, **kwargs)

    if not user:
        url = backend_setting(backend, 'LOGIN_ERROR_URL', LOGIN_ERROR_URL)
    elif isinstance(user, HttpResponse):
        return user
    else:
        url = redirect_value or \
              backend_setting(backend,
                              'SOCIAL_AUTH_NEW_ASSOCIATION_REDIRECT_URL') or \
              DEFAULT_REDIRECT

    keys_query_string = foreward_query_string(backend, request)
    if '?' in url:
        url = url + '&' + keys_query_string
    else:
        url = url + '?' + keys_query_string
    return HttpResponseRedirect(url)
Ejemplo n.º 30
0
def disconnect(request, backend, association_id=None):
    """Disconnects given backend from current logged in user."""
    backend.disconnect(request.user, association_id)
    data = request.REQUEST
    if REDIRECT_FIELD_NAME in data:
        redirect = data[REDIRECT_FIELD_NAME]
        # NOTE: Django's `is_safe_url` is much better at catching bad
        # redirections to different domains than social_auth's
        # `sanitize_redirect` call.
        if not is_safe_url(redirect, host=request.get_host()):
            redirect = DEFAULT_REDIRECT
    else:
        redirect = backend_setting(backend, 'SOCIAL_AUTH_DISCONNECT_REDIRECT_URL')
        if not redirect:
            redirect = DEFAULT_REDIRECT
    return HttpResponseRedirect(redirect)
Ejemplo n.º 31
0
 def enabled(cls):
     """Return backend enabled status by checking basic settings"""
     return backend_setting(cls, cls.SETTINGS_KEY_NAME) and\
            backend_setting(cls, cls.SETTINGS_SECRET_NAME)
 def get_redirect_uri(self, request, exception):
     if self.backend is not None:
         return backend_setting(self.backend,
                                'SOCIAL_AUTH_BACKEND_ERROR_URL') or \
                                settings.LOGIN_ERROR_URL
     return settings.LOGIN_ERROR_URL
 def raise_exception(self, request, exception):
     backend = self.backend
     return backend and backend_setting(backend, 'SOCIAL_AUTH_RAISE_EXCEPTIONS')
Ejemplo n.º 34
0
    def auth_complete(self, *args, **kwargs):
        """Completes loging process, must return user instance"""
        access_token = None
        expires = None

        if 'code' in self.data:
            state = self.validate_state()
            url = ACCESS_TOKEN + urlencode({
                'client_id':
                backend_setting(self, self.SETTINGS_KEY_NAME),
                'redirect_uri':
                self.get_redirect_uri(state),
                'client_secret':
                backend_setting(self, self.SETTINGS_SECRET_NAME),
                'code':
                self.data['code']
            })
            try:
                http_response = requests.get(url)
                if http_response.status_code == 200:
                    response = cgi.parse_qs(http_response.text)
                else:
                    raise AuthFailed(self, u'There was an error authenticating ' \
                                           'the app (status={0}, body={1})'\
                                           .format(http_response.status_code,
                                                   http_response.text)
                                           )
            except requests.RequestException:
                raise AuthFailed(self, 'There was an error authenticating ' \
                                       'the app')

            access_token = response['access_token'][0]
            if 'expires' in response:
                expires = response['expires'][0]

        if 'signed_request' in self.data:
            response = load_signed_request(
                self.data.get('signed_request'),
                backend_setting(self, self.SETTINGS_SECRET_NAME))

            if response is not None:
                access_token = response.get('access_token') or \
                               response.get('oauth_token') or \
                               self.data.get('access_token')

                if 'expires' in response:
                    expires = response['expires']

        if access_token:
            data = self.user_data(access_token)

            if not isinstance(data, dict):
                # From time to time Facebook responds back a JSON with just
                # False as value, the reason is still unknown, but since the
                # data is needed (it contains the user ID used to identify the
                # account on further logins), this app cannot allow it to
                # continue with the auth process.
                raise AuthUnknownError(self, 'An error ocurred while ' \
                                             'retrieving users Facebook ' \
                                             'data')

            data['access_token'] = access_token
            # expires will not be part of response if offline access
            # premission was requested
            if expires:
                data['expires'] = expires

            kwargs.update({
                'auth': self,
                'response': data,
                self.AUTH_BACKEND.name: True
            })

            return authenticate(*args, **kwargs)
        else:
            if self.data.get('error') == 'access_denied':
                raise AuthCanceled(self)
            else:
                raise AuthException(self)
Ejemplo n.º 35
0
 def get_scope(self):
     return backend_setting(self, 'ODNOKLASSNIKI_OAUTH2_EXTRA_SCOPE', [])
Ejemplo n.º 36
0
 def get_settings(self):
     client_key = backend_setting(self, self.SETTINGS_KEY_NAME)
     client_secret = backend_setting(self, self.SETTINGS_SECRET_NAME)
     public_key = backend_setting(self, self.SETTINGS_PUBLIC_NAME)
     return client_key, client_secret, public_key
Ejemplo n.º 37
0
 def get_auth_sig(self):
     secret_key = backend_setting(self.auth, 'ODNOKLASSNIKI_APP_SECRET')
     hash_source = '{0:d}{1:s}{2:s}'.format(
         self.cleaned_data['logged_user_id'],
         self.cleaned_data['session_key'], secret_key)
     return md5(hash_source).hexdigest()
Ejemplo n.º 38
0
def complete_process(request, backend, *args, **kwargs):
    """Authentication complete process"""
    # pop redirect value before the session is trashed on login()
    redirect_value = request.session.get(REDIRECT_FIELD_NAME, '')
    user = auth_complete(request, backend, *args, **kwargs)

    if isinstance(user, HttpResponse):
        return user

    if not user and request.user.is_authenticated():
        return HttpResponseRedirect(redirect_value)

    if user:
        if getattr(user, 'is_active', True):
            # catch is_new flag before login() might reset the instance
            is_new = getattr(user, 'is_new', False)
            login(request, user)
            # user.social_user is the used UserSocialAuth instance defined
            # in authenticate process
            social_user = user.social_user
            if redirect_value:
                request.session[REDIRECT_FIELD_NAME] = redirect_value or \
                                                       DEFAULT_REDIRECT

            if setting('SOCIAL_AUTH_SESSION_EXPIRATION', True):
                # Set session expiration date if present and not disabled by
                # setting. Use last social-auth instance for current provider,
                # users can associate several accounts with a same provider.
                if social_user.expiration_delta():
                    try:
                        request.session.set_expiry(
                            social_user.expiration_delta())
                    except OverflowError:
                        # Handle django time zone overflow, set default expiry.
                        request.session.set_expiry(None)

            # store last login backend name in session
            key = setting('SOCIAL_AUTH_LAST_LOGIN',
                          'social_auth_last_login_backend')
            request.session[key] = social_user.provider

            # Remove possible redirect URL from session, if this is a new
            # account, send him to the new-users-page if defined.
            new_user_redirect = backend_setting(
                backend, 'SOCIAL_AUTH_NEW_USER_REDIRECT_URL')
            if new_user_redirect and is_new:
                url = new_user_redirect
            else:
                url = redirect_value or \
                      backend_setting(backend,
                                      'SOCIAL_AUTH_LOGIN_REDIRECT_URL') or \
                      DEFAULT_REDIRECT
        else:
            url = backend_setting(backend, 'SOCIAL_AUTH_INACTIVE_USER_URL',
                                  LOGIN_ERROR_URL)
    else:
        msg = setting('LOGIN_ERROR_MESSAGE', None)
        if msg:
            messages.error(request, msg)
        url = backend_setting(backend, 'LOGIN_ERROR_URL', LOGIN_ERROR_URL)
    return HttpResponseRedirect(url)