#NEWLINE# def authenticate( self ) : #NEWLINE# #INDENT# "\n        Authenticate to the Salesforce API with the provided credentials.\n\n            Params:\n                db_alias:  The database alias e.g. the default SF alias 'salesforce'.\n                settings_dict: It is only important for the first connection.\n                        Should be taken from django.conf.DATABASES['salesforce'],\n                        because it is not known in connection.settings_dict initially.\n                _session: only for tests\n\n        This function can be called multiple times, but will only make\n        an external request once per the lifetime of the auth token. Subsequent\n        calls to authenticate() will return the original oauth response.\n\n        This function is thread-safe.\n        " #NEWLINE# db_alias = self . db_alias #NEWLINE# if ( not ( db_alias in connections ) ) : #NEWLINE# #INDENT# raise KeyError ( 'authenticate function signature has been changed. The db_alias parameter more important than settings_dict' ) #NEWLINE# #UNINDENT# with oauth_lock : #NEWLINE# #INDENT# if ( not ( db_alias in oauth_data ) ) : #NEWLINE# #INDENT# settings_dict = self . settings_dict #NEWLINE# if ( settings_dict [ 'USER' ] == 'dynamic auth' ) : #NEWLINE# #INDENT# oauth_data [ db_alias ] = { #NEWLINE# #INDENT# 'instance_url' : settings_dict [ 'HOST' ] , #NEWLINE# #UNINDENT# } #NEWLINE# #UNINDENT# else : #NEWLINE# #INDENT# url = '' . join ( [ settings_dict [ 'HOST' ] , '/services/oauth2/token' ] ) #NEWLINE# log . info ( ( 'attempting authentication to %s' % settings_dict [ 'HOST' ] ) ) #NEWLINE# self . _session . mount ( settings_dict [ 'HOST' ] , SslHttpAdapter ( max_retries = MAX_RETRIES ) ) #NEWLINE# response = self . _session . post ( url , data = dict ( grant_type = 'password' , client_id = settings_dict [ 'CONSUMER_KEY' ] , client_secret = settings_dict [ 'CONSUMER_SECRET' ] , username = settings_dict [ 'USER' ] , password = settings_dict [ 'PASSWORD' ] ) ) #NEWLINE# if ( response . status_code == 200 ) : #NEWLINE# #INDENT# response_data = response . json ( ) #NEWLINE# 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' ) #NEWLINE# if ( calc_signature == response_data [ 'signature' ] ) : #NEWLINE# #INDENT# log . info ( ( 'successfully authenticated %s' % settings_dict [ 'USER' ] ) ) #NEWLINE# oauth_data [ response_data ] = response_data #NEWLINE# #UNINDENT# else : #NEWLINE# #INDENT# raise RuntimeError ( 'Invalid auth signature received' ) #NEWLINE# #UNINDENT# #UNINDENT# else : #NEWLINE# #INDENT# raise LookupError ( ( 'oauth failed: %s: %s' % ( settings_dict [ 'USER' ] , response . text ) ) ) #NEWLINE# #UNINDENT# #UNINDENT# #UNINDENT# return oauth_data [ db_alias ]