def _load_v1(self): credentials = self.input["credentials"] # Determine what type of credentials we have if "username" in credentials and "password" in credentials: # User + password, optional Security Token self.result = simple_salesforce.Salesforce( username=credentials["username"], password=credentials["password"], security_token=credentials.get("security-token", ""), organizationId=credentials.get("organization-id", ""), sandbox=credentials.get("sandbox", False), version=constants.API_VERSION, ) logging.getLogger("amaxa").debug( "Authenticating to Salesforce with user name and password") elif "username" in credentials and "consumer-key" and "jwt-key" in credentials: # JWT authentication with key provided inline. try: self.result = jwt_auth.jwt_login( credentials["consumer-key"], credentials["username"], credentials["jwt-key"], credentials.get("sandbox", False), ) logging.getLogger("amaxa").debug( "Authenticating to Salesforce with inline JWT key") except simple_salesforce.exceptions.SalesforceAuthenticationFailed as ex: self.errors.append( "Failed to authenticate with JWT: {}".format(ex.message)) elif "username" in credentials and "jwt-file" in credentials: # JWT authentication with external keyfile. try: with open(credentials["jwt-file"], "r") as jwt_file: self.result = jwt_auth.jwt_login( credentials["consumer-key"], credentials["username"], jwt_file.read(), credentials.get("sandbox", False), ) logging.getLogger("amaxa").debug( "Authenticating to Salesforce with external JWT key") except simple_salesforce.exceptions.SalesforceAuthenticationFailed as ex: self.errors.append( "Failed to authenticate with JWT: {}".format(ex.message)) elif "access-token" in credentials and "instance-url" in credentials: self.result = simple_salesforce.Salesforce( instance_url=credentials["instance-url"], session_id=credentials["access-token"], version=constants.API_VERSION, ) logging.getLogger("amaxa").debug( "Authenticating to Salesforce with access token") else: self.errors.append("A set of valid credentials was not provided.") if self.result is not None: self.result = api.Connection(self.result)
def load_credentials(incoming, load): (credentials, errors) = validate_credential_schema(incoming) if credentials is None: return (None, errors) connection = None credentials = credentials['credentials'] # Determine what type of credentials we have if 'username' in credentials and 'password' in credentials: # User + password, optional Security Token connection = simple_salesforce.Salesforce( username=credentials['username'], password=credentials['password'], security_token=credentials.get('security-token', ''), organizationId=credentials.get('organization-id', ''), sandbox=credentials.get('sandbox', False)) logging.getLogger('amaxa').debug( 'Authenticating to Salesforce with user name and password') elif 'username' in credentials and 'consumer-key' and 'jwt-key' in credentials: # JWT authentication with key provided inline. try: connection = jwt_auth.jwt_login(credentials['consumer-key'], credentials['username'], credentials['jwt-key'], credentials.get('sandbox', False)) logging.getLogger('amaxa').debug( 'Authenticating to Salesforce with inline JWT key') except simple_salesforce.exceptions.SalesforceAuthenticationFailed as e: return (None, ['Failed to authenticate with JWT: {}'.format(e.message)]) elif 'username' in credentials and 'jwt-file' in credentials: # JWT authentication with external keyfile. try: with open(credentials['jwt-file'], 'r') as jwt_file: connection = jwt_auth.jwt_login( credentials['consumer-key'], credentials['username'], jwt_file.read(), credentials.get('sandbox', False)) logging.getLogger('amaxa').debug( 'Authenticating to Salesforce with external JWT key') except simple_salesforce.exceptions.SalesforceAuthenticationFailed as e: return (None, ['Failed to authenticate with JWT: {}'.format(e.message)]) elif 'access-token' in credentials and 'instance-url' in credentials: connection = simple_salesforce.Salesforce( instance_url=credentials['instance-url'], session_id=credentials['access-token']) logging.getLogger('amaxa').debug( 'Authenticating to Salesforce with access token') else: return (None, ['A set of valid credentials was not provided.']) if not load: context = amaxa.ExtractOperation(connection) else: context = amaxa.LoadOperation(connection) return (context, [])
def login(production=True): username, password, token = query_environment() return simple_salesforce.Salesforce(username=username, password=password, security_token=token, client_id='My App', sandbox=not production)
def jwt_login(consumer_id, username, private_key, sandbox=False): endpoint = ("https://test.salesforce.com" if sandbox is True else "https://login.salesforce.com") jwt_payload = jwt.encode( { "exp": datetime.datetime.utcnow() + datetime.timedelta(seconds=30), "iss": consumer_id, "aud": endpoint, "sub": username, }, private_key, algorithm="RS256", ) result = requests.post( endpoint + "/services/oauth2/token", data={ "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer", "assertion": jwt_payload, }, ) body = result.json() if result.status_code != 200: raise SalesforceAuthenticationFailed(body["error"], body["error_description"]) return simple_salesforce.Salesforce( instance_url=body["instance_url"], session_id=body["access_token"], version="46.0", )
def jwt_login(consumer_id, username, private_key, sandbox=False): endpoint = 'https://test.salesforce.com' if sandbox is True else 'https://login.salesforce.com' jwt_payload = jwt.encode( { 'exp': datetime.datetime.utcnow() + datetime.timedelta(seconds=30), 'iss': consumer_id, 'aud': endpoint, 'sub': username }, private_key, algorithm='RS256') result = requests.post(endpoint + '/services/oauth2/token', data={ 'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer', 'assertion': jwt_payload }) body = result.json() if result.status_code != 200: raise SalesforceAuthenticationFailed(body['error'], body['error_description']) return simple_salesforce.Salesforce(instance_url=body['instance_url'], session_id=body['access_token'])
def get_simple_salesforce_connection(project_config, org_config, api_version=None): # Retry on long-running metadeploy jobs retries = Retry(total=5, status_forcelist=(502, 503, 504), backoff_factor=0.3) adapter = HTTPAdapter(max_retries=retries) sf = simple_salesforce.Salesforce( instance_url=org_config.instance_url, session_id=org_config.access_token, version=api_version or project_config.project__package__api_version, ) try: app = project_config.keychain.get_service("connectedapp") client_name = app.client_id except (ServiceNotValid, ServiceNotConfigured): client_name = "CumulusCI/{}".format(__version__) sf.headers.setdefault(CALL_OPTS_HEADER_KEY, "client={}".format(client_name)) sf.session.mount("http://", adapter) sf.session.mount("https://", adapter) return sf
def login_to_salesforce_using_username_password(username, password, security_token, sandbox): sf = simple_salesforce.Salesforce(username=username, password=password, security_token=security_token, sandbox=sandbox) return sf.session_id, sf.sf_instance
def __init__(self): self.api = simple_salesforce.Salesforce( username=os.getenv("SF_USERNAME"), password=os.getenv("SF_PASSWORD"), security_token=os.getenv("SF_TOKEN"), organizationId=os.getenv("SF_ORG_ID"), )
def __init__(self, sf_obj=None): if sf_obj is None: # Import here to avoid simple_salesforce dependency at ezr import import simple_salesforce self.sf = simple_salesforce.Salesforce(username=self.USERNAME, password=self.PASSWORD, security_token=self.TOKEN) else: self.sf = sf_obj
def create(self): client = simple_salesforce.Salesforce( username=self.username, password=self.password, security_token=self.security_token, sandbox=self.sandbox, version=self.api_version, ) return client
def __init__(self, _email, _password, _security_token, _sandbox): self.sf = simple_salesforce.Salesforce(username=_email, password=_password, security_token=_security_token, sandbox=_sandbox) self.sf.headers['Sforce-Auto-Assign'] = 'FALSE' self.current_lead_ids = [] self.current_account_ids = [] self.current_opportunity_ids = []
def initialize(self, bot_handler: Any) -> None: self.config_info = bot_handler.get_config_info('salesforce') try: self.sf = simple_salesforce.Salesforce( username=self.config_info['username'], password=self.config_info['password'], security_token=self.config_info['security_token']) except simple_salesforce.exceptions.SalesforceAuthenticationFailed as err: bot_handler.quit('Failed to log in to Salesforce. {} {}'.format( err.code, err.message))
def __init__(self): super().__init__() # Import here to avoid simple_salesforce dependency at ezr import import simple_salesforce self.session = requests.Session() self.sf_obj = simple_salesforce.Salesforce(username=self.USERNAME, password=self.PASSWORD, security_token=self.TOKEN, session=self.session)
def initialize(self, bot_handler: BotHandler) -> None: self.config_info = bot_handler.get_config_info("salesforce") try: self.sf = simple_salesforce.Salesforce( username=self.config_info["username"], password=self.config_info["password"], security_token=self.config_info["security_token"], ) except simple_salesforce.exceptions.SalesforceAuthenticationFailed as err: bot_handler.quit( f"Failed to log in to Salesforce. {err.code} {err.message}")
def case_details(case_num): if case_num.isdigit() != True: raise ValueError sf=simple_salesforce.Salesforce(**cred()) case_id = sf.query("SELECT Id from Case where CaseNumber = '{}'".format(int(case_num)))['records'][0]['Id'] res = sf.Case.get(case_id) table = { 'headers': [0,1], 'rows': res.items(), } page = { 'title': 'Case sobjects - {}'.format(case_num), 'header': 'Case {}({})'.format(case_num, case_id), } return render_template('base_table.html.j2', page=page, table=table)
def users(self): usernames = [] sf = simple_salesforce.Salesforce(username=self._config['username'], password=self._config['password'], security_token=self._config['token']) result = sf.query(self.query) if len(result): for record in result['records']: names = record['Username_s__c'] collection = [x.strip() for x in names.split(',')] for c in collection: usernames.append((record['Name'], c)) usernames.sort() return usernames
def __init__(self, data): self.sfdc_username = data[0][0] self.sfdc_pwd = data[0][1] self.sfdc_security_token = data[0][2] self.sfdc_instance_url = data[0][3] self.sfdc_is_sandbox = data[0][4] try: self.sf = simple_salesforce.Salesforce( instance_url=self.sfdc_instance_url, username=self.sfdc_username, password=self.sfdc_pwd, security_token=self.sfdc_security_token, sandbox=self.sfdc_is_sandbox) except Exception as e: print "failed"
def create(self): session = requests.Session() retry_adapter = requests.adapters.HTTPAdapter( max_retries=Retry(connect=CONNECT_RETRIES, read=READ_RETRIES, redirect=REDIRECT_RETRIES)) session.mount('http://', retry_adapter) session.mount('https://', retry_adapter) client = simple_salesforce.Salesforce( username=self.username, password=self.password, security_token=self.security_token, sandbox=self.sandbox, version=self.api_version, session=session) return client
def loginToSalesForce(isProduction): sandbox = not isProduction u = os.getenv('SalesForceUserName') p = os.getenv('SalesForcePassWord') t = os.getenv('SalesForceToken') if u == None: print('set the SalesForceUserName environment variable') sys.exit(1) if p == None: print('set the SalesForcePassWord environment variable') sys.exit(1) if t == None: print('set the SalesForceToken environment variable') sys.exit(1) salesforce = simple_salesforce.Salesforce( username = u, password = p, security_token = t, sandbox = sandbox) return(salesforce)
def get_simple_salesforce_connection(project_config, org_config, api_version=None): sf = simple_salesforce.Salesforce( instance_url=org_config.instance_url, session_id=org_config.access_token, version=api_version or project_config.project__package__api_version, ) try: app = project_config.keychain.get_service("connectedapp") client_name = app.client_id except (ServiceNotValid, ServiceNotConfigured): client_name = "CumulusCI/{}".format(__version__) sf.headers.setdefault(CALL_OPTS_HEADER_KEY, "client={}".format(client_name)) return sf
def new_open(): sf=simple_salesforce.Salesforce(**cred()) fields = ['isMosAlert__c', 'Milestone_violated__c', 'First_Reply__c', 'CaseNumber', 'Severity_Level__c', 'Status', 'Subject', 'URL_for_support__c'] quer = sf_queries.case_new_open(fields) res = sf.query(quer)['records'] table = { 'headers': fields, 'rows': res, } page = { 'title': 'New and Open Cases', 'header': 'New and Open Cases', } return render_template('base_table.html.j2', page=page, table=table)
def get_salesforce_connection(*, scratch_org, originating_user_id, base_url=""): org_name = "dev" org_config = refresh_access_token( org_name=org_name, config=scratch_org.config, scratch_org=scratch_org, originating_user_id=originating_user_id, ) conn = simple_salesforce.Salesforce( instance_url=org_config.instance_url, session_id=org_config.access_token, version=MetechoUniversalConfig().project__package__api_version, ) conn.headers.setdefault( "Sforce-Call-Options", "client={}".format(settings.SFDX_CLIENT_ID) ) conn.base_url += base_url return conn
def __init__(self): self.api = simple_salesforce.Salesforce( username=os.environ['SF_USERNAME'], password=os.environ['SF_PASSWORD'], security_token=os.environ['SF_TOKEN'], organizationId=os.environ['SF_ORG_ID'])
colnames) email_colname = find_matching(r"email", colnames, "email") company_colname = find_matching(r"company([\s_]*name)?", colnames, "company") salesforce_id_colname = find_matching( r"((salesforce|sfdc)[\s_]*)?(contact[\s_*])?id", colnames, "salesforce_id") title_colname = find_matching(r"title", colnames, "title") anymailfinder_status_colname = find_matching(r"anymailfinder[\s_]*status", colnames, "anymailfinder_status") hunterio_status_colname = find_matching(r"hunterio[\s_]*status", colnames, "hunterio_status") instance_url, session_id = salesforcecookies.get_instance_url_and_session() sf = simple_salesforce.Salesforce(instance_url=instance_url, session_id=session_id) # checks viable_data = [] for item in data: for key in colnames: item[key] = str(item.get(key, "")).strip() # if salesforce ID but no email, pull email from salesforce # this can happen if e.g. you pick a duplicate manually print("Populating email addresses from SFDC IDs...") working_set = [ item for item in data if item[salesforce_id_colname] and not item[email_colname] ] result = find_salesforce_emails_for_ids(
def sf(self): if self._sf is None: import simple_salesforce self._sf = simple_salesforce.Salesforce(username=self._config['username'], password=self._config['password'], security_token=self._config['token']) return self._sf
def _load_v2(self): credentials = self.input["credentials"] # Determine what type of credentials we have sandbox = credentials["sandbox"] if "username" in credentials: # User + password, optional Security Token credentials = credentials["username"] self.result = simple_salesforce.Salesforce( username=credentials["username"], password=credentials["password"], security_token=credentials.get("security-token", ""), organizationId=credentials.get("organization-id", ""), domain="test" if sandbox else "login", version=self.api_version, ) logging.getLogger("amaxa").debug( "Authenticating to Salesforce with user name and password") elif "jwt" in credentials: credentials = credentials["jwt"] if "keyfile" in credentials: # JWT authentication with external keyfile with open(credentials["keyfile"], "r", encoding="utf-8") as jwt_file: key = jwt_file.read() logging.getLogger("amaxa").debug( "Authenticating to Salesforce with external JWT key") else: # JWT authentication with key provided inline. key = credentials["key"] try: self.result = jwt_auth.jwt_login( credentials["consumer-key"], credentials["username"], key, self.api_version, sandbox, ) except simple_salesforce.exceptions.SalesforceAuthenticationFailed as ex: self.errors.append( "Failed to authenticate with JWT: {}".format(ex.message)) elif "token" in credentials: credentials = credentials["token"] self.result = simple_salesforce.Salesforce( instance_url=credentials["instance-url"], session_id=credentials["access-token"], version=self.api_version, ) logging.getLogger("amaxa").debug( "Authenticating to Salesforce with access token") elif "sfdx" in credentials: sfdx_username = credentials["sfdx"] result = subprocess.run( ["sfdx", "force:org:display", "--json", "-u", sfdx_username], encoding="utf-8", capture_output=True, ) try: org_info = json.loads(result.stdout) if org_info["status"] == 0: self.result = simple_salesforce.Salesforce( instance_url=org_info["result"]["instanceUrl"], session_id=org_info["result"]["accessToken"], version=self.api_version, ) else: self.errors.append( f"SFDX failed to provide credentials with return code {org_info['status']}: {org_info['message']}." ) except Exception as e: self.errors.append( f"SFDX failed to provide credentials with return code {result.returncode}. Exception: {e}" ) if self.result is not None: self.result = api.Connection(self.result, self.api_version)
import argparse import simple_salesforce a = argparse.ArgumentParser() a.add_argument('-u', '--username', dest='user') a.add_argument('-p', '--password', dest='password') a.add_argument('-t', '--security-token', dest='token') a.add_argument('-a', '--access-token', dest='access_token') a.add_argument('-i', '--instance-url', dest='instance_url') a.add_argument('-s', '--sandbox', dest='sandbox', action="store_true") args = a.parse_args() connection = None if args.access_token is not None and args.instance_url is not None: connection = simple_salesforce.Salesforce(instance_url=args.instance_url, session_id=args.access_token) elif args.user is not None and args.password is not None and args.token is not None: connection = simple_salesforce.Salesforce(username=args.user, password=args.password, security_token=args.token, sandbox=args.sandbox) assert connection is not None results = connection.query('SELECT Id FROM Account') assert results is not None
def __init__(self, **creds): self.api = simple_salesforce.Salesforce(**creds)