def make_session(self):
     """Authenticate and get the name of assigned SFDC data server"""
     with connect_lock:
         if self._sf_session is None:
             sf_session = requests.Session()
             # TODO configurable class Salesforce***Auth
             sf_session.auth = SalesforcePasswordAuth(db_alias=self.alias,
                                                      settings_dict=self.settings_dict)
             sf_instance_url = sf_session.auth.instance_url
             sf_requests_adapter = HTTPAdapter(max_retries=get_max_retries())
             sf_session.mount(sf_instance_url, sf_requests_adapter)
             # Additional headers work, but the same are added automatically by "requests' package.
             # sf_session.header = {'accept-encoding': 'gzip, deflate', 'connection': 'keep-alive'} # TODO
             self._sf_session = sf_session
Example #2
0
 def make_session(self):
     """Authenticate and get the name of assigned SFDC data server"""
     with connect_lock:
         if self._sf_session is None:
             sf_session = requests.Session()
             # TODO configurable class Salesforce***Auth
             sf_session.auth = SalesforcePasswordAuth(db_alias=self.alias,
                                                      settings_dict=self.settings_dict)
             sf_instance_url = sf_session.auth.instance_url
             sf_requests_adapter = HTTPAdapter(max_retries=get_max_retries())
             sf_session.mount(sf_instance_url, sf_requests_adapter)
             # Additional headers work, but the same are added automatically by "requests' package.
             # sf_session.header = {'accept-encoding': 'gzip, deflate', 'connection': 'keep-alive'} # TODO
             self._sf_session = sf_session
Example #3
0
 def make_session(self) -> None:
     """Authenticate and get the name of assigned SFDC data server"""
     with connect_lock:
         if self._sf_session is None:
             auth_data = self.sf_auth.authenticate_and_cache()
             sf_instance_url = auth_data.get('instance_url')
             sf_session = SfSession()
             sf_session.auth = self.sf_auth
             if sf_instance_url and sf_instance_url not in sf_session.adapters:
                 # a repeated mount to the same prefix would cause a warning about unclosed SSL socket
                 sf_requests_adapter = HTTPAdapter(
                     max_retries=get_max_retries())
                 sf_session.mount(sf_instance_url, sf_requests_adapter)
             # Additional headers work, but the same are added automatically by "requests' package.
             # sf_session.header = {'accept-encoding': 'gzip, deflate', 'connection': 'keep-alive'}
             self._sf_session = sf_session
    def authenticate(self):
        """
        Authenticate to the Salesforce API with the provided credentials (password).
        """
        settings_dict = self.settings_dict
        url = ''.join([settings_dict['HOST'], '/services/oauth2/token'])

        log.info("attempting authentication to %s", settings_dict['HOST'])
        self._session.mount(settings_dict['HOST'],
                            HTTPAdapter(max_retries=get_max_retries()))
        auth_params = {
            'grant_type': 'password',
            'client_id': settings_dict['CONSUMER_KEY'],
            'client_secret': settings_dict['CONSUMER_SECRET'],
            'username': settings_dict['USER'],
            'password': settings_dict['PASSWORD'],
        }
        response = self._session.post(url, data=auth_params)
        if response.status_code == 200:
            # prefer str in Python 2 due to other API
            response_data = {
                str(k): str(v)
                for k, v in response.json().items()
            }
            # Verify signature (not important for this auth mechanism)
            calc_signature = (base64.b64encode(
                hmac.new(key=settings_dict['CONSUMER_SECRET'].encode('ascii'),
                         msg=(response_data['id'] +
                              response_data['issued_at']).encode('ascii'),
                         digestmod=hashlib.sha256).digest())).decode('ascii')
            if calc_signature == response_data['signature']:
                log.info("successfully authenticated %s",
                         settings_dict['USER'])
            else:
                raise IntegrityError('Invalid auth signature received')
        else:
            raise SalesforceAuthError("oauth failed: %s: %s" %
                                      (settings_dict['USER'], response.text))
        return response_data
Example #5
0
    def authenticate(self) -> Dict[str, str]:
        """
        Authenticate to the Salesforce API with the provided credentials (password).
        """
        settings_dict = self.settings_dict
        url = ''.join([settings_dict['HOST'], '/services/oauth2/token'])

        log.info("authentication to %s as %s", settings_dict['HOST'],
                 settings_dict['USER'])
        if settings_dict['HOST'] not in self._session.adapters:
            # a repeated mount to the same prefix would cause a warning about unclosed SSL socket
            self._session.mount(settings_dict['HOST'],
                                HTTPAdapter(max_retries=get_max_retries()))
        auth_params = {
            'grant_type': 'password',
            'client_id': settings_dict['CONSUMER_KEY'],
            'client_secret': settings_dict['CONSUMER_SECRET'],
            'username': settings_dict['USER'],
            'password': settings_dict['PASSWORD'],
        }
        time_statistics.update_callback(url, self.ping_connection)
        response = self._session.post(url, data=auth_params)
        return self.checked_auth_response(response)
Example #6
0
    def authenticate(self):
        """
        Authenticate to the Salesforce API with the provided credentials (password).
        """
        settings_dict = self.settings_dict
        url = ''.join([settings_dict['HOST'], '/services/oauth2/token'])

        log.info("attempting authentication to %s", settings_dict['HOST'])
        self._session.mount(settings_dict['HOST'], HTTPAdapter(max_retries=get_max_retries()))
        auth_params = {
            'grant_type':    'password',
            'client_id':     settings_dict['CONSUMER_KEY'],
            'client_secret': settings_dict['CONSUMER_SECRET'],
            'username':      settings_dict['USER'],
            'password':      settings_dict['PASSWORD'],
        }
        response = self._session.post(url, data=auth_params)
        if response.status_code == 200:
            # prefer str in Python 2 due to other API
            response_data = {str(k): str(v) for k, v in response.json().items()}
            # Verify signature (not important for this auth mechanism)
            calc_signature = (
                base64.b64encode(
                    hmac.new(
                        key=settings_dict['CONSUMER_SECRET'].encode('ascii'),
                        msg=(response_data['id'] + response_data['issued_at']).encode('ascii'),
                        digestmod=hashlib.sha256
                    ).digest()
                )
            ).decode('ascii')
            if calc_signature == response_data['signature']:
                log.info("successfully authenticated %s", settings_dict['USER'])
            else:
                raise IntegrityError('Invalid auth signature received')
        else:
            raise SalesforceAuthError("oauth failed: %s: %s" % (settings_dict['USER'], response.text))
        return response_data