示例#1
0
    def auth_complete(self, *args, **kwargs):
        """Completes login process, must return user instance"""
        access_token = None
        if self.data.get('error'):
            error = self.data.get('error_description') or self.data['error']
            raise AuthFailed(self, error)

        client_id, client_secret = self.get_key_and_secret()
        try:
            shop_url = self.request.GET.get('shop')
            self.shopifyAPI.Session.setup(
                api_key=setting('SHOPIFY_APP_API_KEY'),
                secret=setting('SHOPIFY_SHARED_SECRET'))
            shopify_session = self.shopifyAPI.Session(shop_url,
                                                      self.request.REQUEST)
            access_token = shopify_session.token
        except self.shopifyAPI.ValidationException as e:
            raise AuthCanceled(self)
        except HTTPError as e:
            if e.code == 400:
                raise AuthCanceled(self)
            else:
                raise

        if not access_token:
            raise AuthFailed(self, 'Authentication Failed')
        return self.do_auth(access_token, shop_url, shopify_session.url, *args,
                            **kwargs)
示例#2
0
    def auth_complete(self, *args, **kwargs):
        """Completes login process, must return user instance"""

        if self.data.get('error'):
            error = self.data.get('error_description') or self.data['error']
            raise AuthFailed(self, error)

        token = kwargs.get('request').POST.get('jwt', {})

        if not token:
            raise AuthFailed(self, 'Authentication Failed')
        return self.do_auth(token, *args, **kwargs)
示例#3
0
def create_user(backend, details, response, uid, username, user=None,
                *args, **kwargs):
    """Create user. Depends on get_username pipeline."""
    if user:
        return {'user': user}
    if not username:
        return None

    # Avoid hitting field max length
    email = details.get('email')
    original_email = None

    if not email:
        message = _("""your social account needs to have a verified email address in order to proceed.""")
        raise AuthFailed(backend, message)

    if email and UserSocialAuth.email_max_length() < len(email):
        original_email = email
        email = ''

    return {
        'user': UserSocialAuth.create_user(username=username, email=email,
                                           sync_emailaddress=False),
        'original_email': original_email,
        'is_new': True
    }
示例#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)
示例#5
0
 def auth_complete(self, *args, **kwargs):
     """Complete auth process"""
     logger.debug('auth_complete ARGS=%s, KWARGS=%s' % (args, kwargs))
     response = self.consumer().complete(dict(self.data.items()),
                                         self.build_absolute_uri())
     logger.debug('response and status %s / %s' % (response, response.status))
     if not response:
         logger.debug('will throw AuthException')
         raise AuthException(self, 'OpenID relying party endpoint')
     elif response.status == SUCCESS:
         kwargs.update({
             'auth': self,
             'response': response,
             self.AUTH_BACKEND.name: True
         })
         return authenticate(*args, **kwargs)
     elif response.status == FAILURE:
         logger.debug('will throw AuthFailed(%s)' % response.message)
         raise AuthFailed(self, response.message)
     elif response.status == CANCEL:
         logger.debug('will throw AuthCanceled')
         raise AuthCanceled(self)
     else:
         logger.debug('will throw AuthUnknownError(%s)' % response.status)
         raise AuthUnknownError(self, response.status)
示例#6
0
 def process_error(self, data):
     if self.data.get('error'):
         error = self.data.get('error_description') or self.data['error']
         if self.data['error'] == 'access_denied':
             raise AuthCanceled(self, error)
         else:
             raise AuthFailed(self, error)
示例#7
0
    def user_data(self, access_token, *args, **kwargs):
        """Loads user data from service"""
        req = Request(GITHUB_USER_DATA_URL,
                      headers={"Authorization": "token %s" % access_token})

        try:
            data = json.load(dsa_urlopen(req))
        except ValueError:
            data = None

        # if we have a github organization defined, test that the current users
        # is a member of that organization.
        if data and self.GITHUB_ORGANIZATION:
            req = Request(
                GITHUB_ORGANIZATION_MEMBER_OF_URL.format(
                    org=self.GITHUB_ORGANIZATION, username=data.get("login")),
                headers={"Authorization": "token %s" % access_token},
            )

            try:
                response = dsa_urlopen(req)
            except HTTPError:
                data = None
            else:
                # if the user is a member of the organization, response code
                # will be 204, see http://bit.ly/ZS6vFl
                if response.code != 204:
                    raise AuthFailed("User doesn't belong to the "
                                     "organization")
        return data
示例#8
0
    def user_data(self, access_token, *args, **kwargs):
        """Loads user data from service"""
        url = GITHUB_USER_DATA_URL + '?' + urlencode({
            'access_token': access_token
        })

        try:
            data = simplejson.load(dsa_urlopen(url))
        except ValueError:
            data = None

        # if we have a github organization defined, test that the current users
        # is a member of that organization.
        if data and self.GITHUB_ORGANIZATION:
            member_url = GITHUB_ORGANIZATION_MEMBER_OF_URL.format(
                org=self.GITHUB_ORGANIZATION,
                username=data.get('login')
            ) + '?' + urlencode({
                'access_token': access_token
            })

            try:
                response = dsa_urlopen(member_url)
            except HTTPError:
                data = None
            else:
                # if the user is a member of the organization, response code
                # will be 204, see http://bit.ly/ZS6vFl
                if response.code != 204:
                    raise AuthFailed('User doesn\'t belong to the '
                                     'organization')
        return data
示例#9
0
    def auth_complete(self, *args, **kwargs):
        """Performs check of authentication in VK, returns User if
        succeeded"""
        app_cookie = 'vk_app_' + self.APP_ID

        if not 'id' in self.request.GET or \
           not app_cookie in self.request.COOKIES:
            raise AuthCanceled(self)

        cookie_dict = dict(
            item.split('=')
            for item in self.request.COOKIES[app_cookie].split('&'))
        check_str = ''.join(item + '=' + cookie_dict[item]
                            for item in ['expire', 'mid', 'secret', 'sid'])

        hash = md5(check_str + setting('VK_API_SECRET')).hexdigest()

        if hash != cookie_dict['sig'] or int(cookie_dict['expire']) < time():
            raise AuthFailed('VK authentication failed: invalid hash')
        else:
            kwargs.update({
                'auth': self,
                'response': self.user_data(cookie_dict['mid']),
                self.AUTH_BACKEND.name: True
            })
            return authenticate(*args, **kwargs)
示例#10
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
示例#11
0
def check_credentials(details, user=None, *args, **kwargs):
    """Check that user is a lateral-thoughts member."""
    if user:
        return None

    email = details.get('email')

    if not email or not email.endswith(settings.AGORA_ORGANIZATION_DOMAIN):
        raise AuthFailed(
            kwargs['backend'], 'You must connect with your %s account.' %
            settings.AGORA_ORGANIZATION_NAME)
    return None
示例#12
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 = simplejson.loads(response)

            print 'parsed_response', parsed_response

            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)
示例#13
0
def check_credentials(details, user=None, *args, **kwargs):
    """Check that user is a lateral-thoughts member."""
    if user:
        return None

    email = details.get('email')

    if not email or not email.endswith("@lateral-thoughts.com"):
        raise AuthFailed(
            kwargs['backend'],
            'You must connect with your Lateral Thoughts account.')
    return None
def validate_whitelists(backend, email):
    """
    Validates allowed domains and emails against the following settings:
        GOOGLE_WHITE_LISTED_DOMAINS
        GOOGLE_WHITE_LISTED_EMAILS

    All domains and emails are allowed if setting is an empty list.
    """
    emails = setting('GOOGLE_WHITE_LISTED_EMAILS', [])
    domains = setting('GOOGLE_WHITE_LISTED_DOMAINS', [])
    if emails and email in emails:
        return  # you're good
    if domains and email.split('@', 1)[1] not in domains:
        raise AuthFailed(backend, 'Domain not allowed')
示例#15
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)
示例#16
0
 def auth_complete(self, *args, **kwargs):
     """Complete auth process"""
     response = self.consumer().complete(dict(self.data.items()),
                                         self.build_absolute_uri())
     if not response:
         raise AuthException(self, 'OpenID relying party endpoint')
     elif response.status == SUCCESS:
         kwargs.update({
             'auth': self,
             'response': response,
             self.AUTH_BACKEND.name: True
         })
         return authenticate(*args, **kwargs)
     elif response.status == FAILURE:
         raise AuthFailed(self, response.message)
     elif response.status == CANCEL:
         raise AuthCanceled(self)
     else:
         raise AuthUnknownError(self, response.status)
示例#17
0
 def process_error(self, data):
     if data.get('error'):
         error = self.data.get('error_description') or self.data['error']
         raise AuthFailed(self, error)
示例#18
0
 def process_error(self, data):
     error = data.get("error_description") or data.get("error")
     if error:
         raise AuthFailed(self, error)
示例#19
0
            self.shopifyAPI.Session.setup(
                api_key=setting('SHOPIFY_APP_API_KEY'),
                secret=setting('SHOPIFY_SHARED_SECRET'))
            shopify_session = self.shopifyAPI.Session(shop_url,
                                                      self.request.REQUEST)
            access_token = shopify_session.token
        except self.shopifyAPI.ValidationException, e:
            raise AuthCanceled(self)
        except HTTPError, e:
            if e.code == 400:
                raise AuthCanceled(self)
            else:
                raise

        if not access_token:
            raise AuthFailed(self, 'Authentication Failed')
        return self.do_auth(access_token, shop_url, shopify_session.url, *args,
                            **kwargs)

    def do_auth(self, access_token, shop_url, website, *args, **kwargs):
        kwargs.update({
            'auth': self,
            'response': {
                'shop': shop_url,
                'website': 'http://%s' % website,
                'access_token': access_token
            },
            self.AUTH_BACKEND.name: True
        })
        return authenticate(*args, **kwargs)
示例#20
0
 def _user_id(self, response):
     match = STEAM_ID.search(response.identity_url)
     if match is None:
         raise AuthFailed(self, 'Missing Steam Id')
     return match.group(1)