def verify_credentials(request): """ **verify_credentials(request)** Verify the pyxero credentials with Xero. **Parameters:** ***request***: Django request object. **Returns**: Nothing """ # Recreate the credential objects from the saved credentials temp_credentials = request.session.get('temp_credentials', None) credentials = PublicCredentials(**temp_credentials) infolog.info("Pre-Verify Credentials: {0}".format(credentials.state)) # Verify the credentials using the passed in 'oauth_verifier' parameter credentials.verify(request.GET.get('oauth_verifier', None)) # Important we save the verified credentials for future use if credentials.state.get('verified', False) == True: tmp = credentials.state tmp['oauth_authorization_expires_at'] = str( tmp.get('oauth_authorization_expires_at')) tmp['oauth_expires_at'] = str(tmp.get('oauth_expires_at')) request.session['credentials'] = tmp infolog.info("Credentials Now Verified {0}".format(credentials.state)) else: infolog.info("Failed to Verify Credentials {0}".format( credentials.state))
def test_verify(self, r_post): "Unverfied credentials can be verified" r_post.return_value = Mock(status_code=200, text='oauth_token=verified_token&oauth_token_secret=verified_token_secret') credentials = PublicCredentials( consumer_key='key', consumer_secret='secret', oauth_token='token', oauth_token_secret='token_secret', ) credentials.verify('verifier') # A HTTP request was made self.assertTrue(r_post.called) state = credentials.state # Expiry times should be calculated self.assertIsNotNone(state.pop("oauth_authorization_expires_at")) self.assertIsNotNone(state.pop("oauth_expires_at")) self.assertEqual(state, { 'consumer_key': 'key', 'consumer_secret': 'secret', 'oauth_token': 'verified_token', 'oauth_token_secret': 'verified_token_secret', 'verified': True }) try: credentials.oauth except XeroNotVerified: self.fail('Credentials should have been verified')
def test_verify(self, r_post): "Unverfied credentials can be verified" r_post.return_value = Mock( status_code=200, text= 'oauth_token=verified_token&oauth_token_secret=verified_token_secret' ) credentials = PublicCredentials( consumer_key='key', consumer_secret='secret', oauth_token='token', oauth_token_secret='token_secret', ) credentials.verify('verifier') # A HTTP request was made self.assertTrue(r_post.called) self.assertEqual( credentials.state, { 'consumer_key': 'key', 'consumer_secret': 'secret', 'oauth_token': 'verified_token', 'oauth_token_secret': 'verified_token_secret', 'verified': True }) try: credentials.oauth except XeroNotVerified: self.fail('Credentials should have been verified')
def reauthenticate(args, user_integration): xcr = Xero_Credentials.objects.get(user_integration_id=user_integration.id) print("user integration-" + str(xcr.user_integration_id)) credentials = PublicCredentials('BGJJ6JSSEAGIRWQ9SYKA1T3O7Y6IPF', '2JRHWN0QQ1K0AHVDZVUPKCVIQKUUNB', 'http://127.0.0.1:8000/return/') print(credentials.url) webbrowser.open(credentials.url) time.sleep(30) # time.sleep(60) for the user credentials.verify(views.token) xero = Xero(credentials) saved_state = credentials.state print(str(saved_state) + "saved_state") s1 = saved_state['oauth_expires_at'] s2 = saved_state['oauth_authorization_expires_at'] print("\n\n") print(s1) print(s2) s1 = s1.strftime('%Y%m%d%H%M%S%f') s2 = s2.strftime('%Y%m%d%H%M%S%f') # new_date=datetime.datetime.strptime(s1,'%Y%m%d%H%M%S%f') # print(new_date) t1 = saved_state['oauth_token'] t2 = saved_state['oauth_token_secret'] obj = Xero_Credentials.objects.get(user_integration_id=user_integration.id) obj.XERO_OAUTH_TOKEN = t1 obj.XERO_OAUTH_SECRET = t2 obj.XERO_EXPIRE = s1 obj.XERO_AUTH_EXPIRE = s2 obj.XERO_UPDATE_LOGIN_FLAG = True print(str(obj.XERO_AUTH_EXPIRE) + " helloooo") obj.save() # global flag # global saved_state # credentials = PublicCredentials(consumer_key, consumer_secret) m = MessageClass() m.message_text = "Your account has been authenticated" # if flag == 0: # code=args['7-Digit-Code'] # print(code) # print(credentials.url) # credentials.verify(input("enter")) # saved_state = credentials.state # new_credentials=PublicCredentials(**saved_state) # xero=Xero_Credentials(new_credentials) # flag = 1 # print("Your account has been authenticated") # attachment=MessageAttachmentsClass() # field=AttachmentFieldsClass() # field.title="Your account is now authenticated" # attachment.attach_field(field) # m.attach(attachment) return m
def complete_flow(self, verification_code, user): """ Complete Authorization flow Note that you must already have a Django user, since Xero won't tell you anything about the logged-on user. :param verification_code: code to verify the original request :param user: User instance :returns XeroUser instance """ # rebuild our connection state_dict = json.loads(self.state, object_hook=_datetime_parser_hook) creds = PublicCredentials(**state_dict) creds.verify(verification_code) xero_user = XeroUser.from_state(creds, user) return xero_user
def get_xero_credentials(request, callback=settings.XERO_CALLBACK_URI): """ **get_xero_credentials(request, callback=settings.XERO_CALLBACK_URI)** Receives Xero credentials to be used for the initial login and authorisation_url. Saves a temporary copy of the pyxero credentials that are used following the callback from Xero. **Parameters:** ***request***: Django request object. ***callback***: Callback URI to be used by Xero. **Returns:** Pyxero credentials object. """ # Reset session state request.session['temp_credentials'] = None # Login to Xero to generate credentials to access the authorization URL credentials = PublicCredentials(settings.XERO_CLIENT_KEY, settings.XERO_CLIENT_SECRET, callback) # Save initial request credentials pre-URL call as these are needed post the call too save_temp_credentials(request, credentials) infolog.info("Getting Credentials {0}".format(credentials.state)) return credentials
def client(self): """ Get a ready-made xero.Xero object :return: xero.Xero instance """ return Xero(credentials=PublicCredentials(**self.token), user_agent=get_xero_consumer_key())
def test_validated_constructor(self, r_post): "A validated set of credentials can be reconstructed" credentials = PublicCredentials( consumer_key='key', consumer_secret='secret', oauth_token='validated_token', oauth_token_secret='validated_token_secret', verified=True) self.assertEqual( credentials.state, { 'consumer_key': 'key', 'consumer_secret': 'secret', 'oauth_token': 'validated_token', 'oauth_token_secret': 'validated_token_secret', 'verified': True }) try: credentials.oauth except XeroNotVerified: self.fail('Credentials should have been verified') # No HTTP requests were made self.assertFalse(r_post.called)
def test_verify_failure(self, r_post): "If verification credentials are bad, an error is raised" r_post.return_value = Mock(status_code=401, text='oauth_problem=bad_verifier&oauth_problem_advice=The consumer was denied access to this resource.') credentials = PublicCredentials( consumer_key='key', consumer_secret='secret', oauth_token='token', oauth_token_secret='token_secret', ) with self.assertRaises(XeroUnauthorized): credentials.verify('badverifier') with self.assertRaises(XeroNotVerified): credentials.oauth
def test_initial_constructor(self, r_post): "Initial construction causes a requst to get a request token" r_post.return_value = Mock( status_code=200, text="oauth_token=token&oauth_token_secret=token_secret") credentials = PublicCredentials(consumer_key="key", consumer_secret="secret", scope="payroll.endpoint") # A HTTP request was made self.assertTrue(r_post.called) state = credentials.state # Expiry times should be calculated self.assertIsNotNone(state.pop("oauth_authorization_expires_at")) self.assertIsNotNone(state.pop("oauth_expires_at")) self.assertEqual( state, { "consumer_key": "key", "consumer_secret": "secret", "oauth_token": "token", "oauth_token_secret": "token_secret", "verified": False, "scope": "payroll.endpoint", }, )
def refresh_xero_auth_token(pk): secret_keys = Utils.get_access_keys(pk) consumer_key = secret_keys.client_id consumer_secret = secret_keys.client_secret credentials = PublicCredentials(consumer_key, consumer_secret) return
def test_initial_constructor(self, r_post): "Initial construction causes a requst to get a request token" r_post.return_value = Mock( status_code=200, text='oauth_token=token&oauth_token_secret=token_secret') credentials = PublicCredentials(consumer_key='key', consumer_secret='secret', scope='payroll.endpoint') # A HTTP request was made self.assertTrue(r_post.called) state = credentials.state # Expiry times should be calculated self.assertIsNotNone(state.pop("oauth_authorization_expires_at")) self.assertIsNotNone(state.pop("oauth_expires_at")) self.assertEqual( state, { 'consumer_key': 'key', 'consumer_secret': 'secret', 'oauth_token': 'token', 'oauth_token_secret': 'token_secret', 'verified': False, 'scope': 'payroll.endpoint' })
def connect(self, request, company): """ Connects a company to Xero company must be included in the querystring /?company=<id> """ try: secret_keys = Utils.get_access_keys(company) consumer_key = secret_keys.client_id consumer_secret = secret_keys.client_secret global credentials call_back_uri = settings.XERO_CALL_BACK_URI + "/" + company # call_back_url = 'http://localhost/oauth' if AccountingConfiguration.PRIVATE == secret_keys.type: credentials = PrivateCredentials(consumer_key=consumer_key,rsa_key=consumer_secret) OAUTH_PERSISTENT_SERVER_STORAGE.update({'consumer_key':credentials.consumer_key}) OAUTH_PERSISTENT_SERVER_STORAGE.update({'rsa_key':credentials.rsa_key}) url = call_back_uri else: credentials = PublicCredentials(consumer_key, consumer_secret, callback_uri=call_back_uri) # Save generated credentials details to persistent storage for key, value in credentials.state.items(): OAUTH_PERSISTENT_SERVER_STORAGE.update({key: value}) LoginInfo.objects.create(company_id=company, status=LoginInfo.IN_PROGRESS, created=timezone.now()) url = credentials.url except Exception as e: auth_cancel_url = settings.QBO_AUTH_CANCEL_URL Utils.send_company_misconfig(company,e) return redirect(auth_cancel_url + '/error') return Utils.redirect_response(url)
def test_validated_constructor(self, r_post): "A validated set of credentials can be reconstructed" credentials = PublicCredentials( consumer_key="key", consumer_secret="secret", oauth_token="validated_token", oauth_token_secret="validated_token_secret", verified=True, ) self.assertEqual( credentials.state, { "consumer_key": "key", "consumer_secret": "secret", "oauth_token": "validated_token", "oauth_token_secret": "validated_token_secret", "verified": True, }, ) try: credentials.oauth except XeroNotVerified: self.fail("Credentials should have been verified") # No HTTP requests were made self.assertFalse(r_post.called)
def get(self): data = OauthXero.parser.parse_args() session_data = SessionHistory.get_latest(data['oauth_token']) credentials = PublicCredentials(**session_data.json()) try: credentials.verify(data['oauth_verifier']) s = SessionHistory(**credentials.state) s.save_to_db() session_data.delete_from_db() except XeroException as e: return {'message': '{}: {}'.format(e.__class__, e.message)}, 500 return redirect('/verified?oauth_token={}'.format( credentials.state['oauth_token']))
def test_bad_credentials(self, r_post): "Initial construction with bad credentials raises an exception" r_post.return_value = Mock(status_code=401, text='oauth_problem=consumer_key_unknown&oauth_problem_advice=Consumer%20key%20was%20not%20recognised') with self.assertRaises(XeroUnauthorized): PublicCredentials( consumer_key='unknown', consumer_secret='unknown' )
def test_url(self, r_post): "The request token URL can be obtained" r_post.return_value = Mock(status_code=200, text='oauth_token=token&oauth_token_secret=token_secret') credentials = PublicCredentials( consumer_key='key', consumer_secret='secret' ) self.assertEquals(credentials.url, 'https://api.xero.com/oauth/Authorize?oauth_token=token')
def get_xero_public_credentials(stored_values): return PublicCredentials(consumer_key=stored_values['consumer_key'], consumer_secret=stored_values['consumer_secret'], callback_uri=stored_values['callback_uri'], verified=stored_values['verified'], oauth_token=stored_values['oauth_token'], oauth_token_secret=stored_values['oauth_token_secret'], oauth_expires_at=stored_values['oauth_expires_at'], oauth_authorization_expires_at=stored_values[ 'oauth_authorization_expires_at'], )
def test_url_with_scope(self, r_post): "The request token URL includes the scope parameter" r_post.return_value = Mock( status_code=200, text='oauth_token=token&oauth_token_secret=token_secret') credentials = PublicCredentials(consumer_key='key', consumer_secret='secret', scope="payroll.endpoint") self.assertIn('scope=payroll.endpoint', credentials.url)
def test_verify(self, r_post): "Unverfied credentials can be verified" r_post.return_value = Mock( status_code=200, text= "oauth_token=verified_token&oauth_token_secret=verified_token_secret", ) credentials = PublicCredentials( consumer_key="key", consumer_secret="secret", oauth_token="token", oauth_token_secret="token_secret", ) credentials.verify("verifier") # A HTTP request was made self.assertTrue(r_post.called) state = credentials.state # Expiry times should be calculated self.assertIsNotNone(state.pop("oauth_authorization_expires_at")) self.assertIsNotNone(state.pop("oauth_expires_at")) self.assertEqual( state, { "consumer_key": "key", "consumer_secret": "secret", "oauth_token": "verified_token", "oauth_token_secret": "verified_token_secret", "verified": True, }, ) try: credentials.oauth except XeroNotVerified: self.fail("Credentials should have been verified")
def start_flow(cls, acceptance_url, next_page=None): """ Start authorization flow """ # instantiating credentials automatically starts the flow creds = PublicCredentials(get_xero_consumer_key(), get_xero_consumer_secret(), acceptance_url) # save state for later af_state = cls(state=json.dumps(creds.state, cls=DjangoJSONEncoder), oauth_token=creds.oauth_token, next_page=next_page) af_state.auth_url = creds.url af_state.save() return af_state
def test_verify(self, r_post): "Unverfied credentials can be verified" r_post.return_value = Mock( status_code=200, text="oauth_token=verified_token&oauth_token_secret=verified_token_secret" ) credentials = PublicCredentials( consumer_key="key", consumer_secret="secret", oauth_token="token", oauth_token_secret="token_secret" ) credentials.verify("verifier") # A HTTP request was made self.assertTrue(r_post.called) state = credentials.state # Expiry times should be calculated self.assertIsNotNone(state.pop("oauth_authorization_expires_at")) self.assertIsNotNone(state.pop("oauth_expires_at")) self.assertEqual( state, { "consumer_key": "key", "consumer_secret": "secret", "oauth_token": "verified_token", "oauth_token_secret": "verified_token_secret", "verified": True, }, ) try: credentials.oauth except XeroNotVerified: self.fail("Credentials should have been verified")
def test_configurable_url(self, r_post): "Test configurable API url" r_post.return_value = Mock( status_code=200, text="oauth_token=token&oauth_token_secret=token_secret") url = "https//api-tls.xero.com" credentials = PublicCredentials(consumer_key="key", consumer_secret="secret", api_url=url) self.assertEqual( credentials.url, "{url}/oauth/Authorize?oauth_token=token".format(url=url))
def test_unvalidated_constructor(self, r_post): "Credentials with an unverified request token can be constructed" credentials = PublicCredentials( consumer_key='key', consumer_secret='secret', oauth_token='token', oauth_token_secret='token_secret', ) self.assertEqual(credentials.state, { 'consumer_key': 'key', 'consumer_secret': 'secret', 'oauth_token': 'token', 'oauth_token_secret': 'token_secret', 'verified': False }) # No HTTP requests were made self.assertFalse(r_post.called)
def test_initial_constructor(self, r_post): "Initial construction causes a requst to get a request token" r_post.return_value = Mock(status_code=200, text='oauth_token=token&oauth_token_secret=token_secret') credentials = PublicCredentials( consumer_key='key', consumer_secret='secret' ) # A HTTP request was made self.assertTrue(r_post.called) self.assertEqual(credentials.state, { 'consumer_key': 'key', 'consumer_secret': 'secret', 'oauth_token': 'token', 'oauth_token_secret': 'token_secret', 'verified': False })
def __init__(self, app_type, consumer_key, *args, consumer_secret=None, rsa_key=None, **kwargs): """Create a session using the provided Xero app (key, secret). Args: consumer_key (str): Consumer key for HMAC-SHA1 based three-legged OAuth 1.0a. consumer_secret (str): Consumer key for HMAC-SHA1 based three-legged OAuth 1.0a. rsa_key: file handle to the rsa_key for RSA-SHA1 based two-legged OAuth 1.0a *arg: non-keyworded arguemnts passed to the parent BaseAPI initializer. **kwargs: keyworded arguemnts passed to the parent BaseAPI initializer. """ self.session = None self.app_type = app_type if app_type == "public": if consumer_secret is None: raise TypeError( "Xero API applications of type Public require a consumer secret code." ) else: self.session_credentials = PublicCredentials( consumer_key, consumer_secret) elif app_type == "private": if rsa_key is None: raise TypeError( "Xero API applications of type Private require an RSA key." ) else: self.session_credentials = PrivateCredentials( consumer_key, rsa_key) elif app_type == "partner": raise TypeError( "Xero API applications of type Partner are not yet supported.") else: raise TypeError("Unexpected Xero API application type: " + app_type) super().__init__(*args, **kwargs)
def test_unvalidated_constructor(self, r_post): "Credentials with an unverified request token can be constructed" credentials = PublicCredentials( consumer_key="key", consumer_secret="secret", oauth_token="token", oauth_token_secret="token_secret", ) self.assertEqual( credentials.state, { "consumer_key": "key", "consumer_secret": "secret", "oauth_token": "token", "oauth_token_secret": "token_secret", "verified": False, }, ) # No HTTP requests were made self.assertFalse(r_post.called)
def get(self): data = Verified.parser.parse_args() session_data = SessionHistory.get_latest(data['oauth_token']) credentials = PublicCredentials(**session_data.json()) try: xero = Xero(credentials) except XeroException as e: return {'message': '{}: {}'.format(e.__class__, e.response)}, 500 # using consumer key as a placeholder since there is no logged in user # here this can be the customer's record for which the data is being pulled xero_integration = XeroIntegration.get_by_ckey( credentials.state['consumer_key']) contacts = xero.contacts.filter(since=xero_integration.updated_on_utc) accounts = xero.accounts.filter(since=xero_integration.updated_on_utc) updated = False message = '' try: if contacts: Contact.sync_with_xero(contacts, xero_integration) updated = True message += 'Contacts Synced' if accounts: Account.sync_with_xero(accounts, xero_integration) updated = True message += ' Accounts Synced' except SQLAlchemyError as e: return {'message': e._message}, 500 finally: if updated: xero_integration.update_date() else: message = 'Nothing was synced' return {'message': message}, 200
def get(self): consumer_key = os.environ.get('XERO_CONSUMER_KEY') consumer_secret = os.environ.get('XERO_CONSUMER_SECRET') if consumer_key is None or consumer_secret is None: return { 'message': 'XERO_CONSUMER_KEY \ and XERO_CONSUMER_SECRET are required' }, 400 credentials = PublicCredentials( consumer_key, consumer_secret, callback_uri=os.environ.get('XERO_CALLBACK_URI')) s = SessionHistory(**credentials.state) try: s.save_to_db() except SQLAlchemyError as e: return {'message': e._message}, 500 return redirect(credentials.url)
def test_expired(self): "Expired credentials are correctly detected" now = datetime(2014, 1, 1, 12, 0, 0) soon = now + timedelta(minutes=30) credentials = PublicCredentials( consumer_key='key', consumer_secret='secret', oauth_token='token', oauth_token_secret='token_secret', ) # At this point, oauth_expires_at isn't set with self.assertRaises(XeroException): credentials.expired(now) # Not yet expired credentials.oauth_expires_at = soon self.assertFalse(credentials.expired(now=now)) # Expired self.assertTrue(credentials.expired(now=soon))
def get_xero(request): """ **get_xero(request)** Retrieves the Xero connection object to allow access to Xero API. **Parameters:** ***request***: Django request object. **Returns**: Xero connection object that allows api access. """ try: saved_credentials = request.session.get('credentials', None) credentials = PublicCredentials(**saved_credentials) infolog.info("session credentials: {0}".format(credentials.state)) return Xero(credentials) except: errorlog.error( "Failed to retrieve the connection object. Perhaps user not logged in." ) raise Http404("Failed to connect to Xero. Ensure you are signed in.")
def test_expired(self): "Expired credentials are correctly detected" now = datetime(2014, 1, 1, 12, 0, 0) soon = now + timedelta(minutes=30) credentials = PublicCredentials( consumer_key="key", consumer_secret="secret", oauth_token="token", oauth_token_secret="token_secret" ) # At this point, oauth_expires_at isn't set with self.assertRaises(XeroException): credentials.expired(now) # Not yet expired credentials.oauth_expires_at = soon self.assertFalse(credentials.expired(now=now)) # Expired self.assertTrue(credentials.expired(now=soon))
def main(): privateKey = os.getenv("XERO_PRIVATE_KEY") privateConsumerKey = os.getenv("XERO_PRIVATE_CONSUMER_KEY") if privateKey is None or privateConsumerKey is None: raise KeyError( 'Please define both XERO_CONSUMER_KEY and XERO_CONSUMER_SECRET environment variables' ) credentials = PublicCredentials(privateKey, privateConsumerKey) print("please go here and authorize", credentials.url) verifier = input('paste verifier here:') credentials.verify(verifier) data = {"assetName": "Other Computer Test", "assetNumber": "FA-00211"} credentials.expired() print(xero_asset_put(credentials.oauth, data)) print(xero_asset_get(credentials.oauth, {"status": "DRAFT"})) return 0
from xero import Xero from xero.auth import PublicCredentials argp = argparse.ArgumentParser(description=__doc__) argp.add_argument("-i", "--input-file", dest="input_file", default="-", help="input file name") argp.add_argument( "-c", "--credentials-file", dest="credentials_file", default="credentials.pickle", help="credentials file name" ) args = argp.parse_args() # Connect to Xero if os.path.isfile(args.credentials_file): # Use cached credentials with open(args.credentials_file, "r") as credentials_fh: credentials_state = pickle.loads(credentials_fh.read()) credentials = PublicCredentials(**credentials_state) else: credentials = PublicCredentials(xero_config["consumer_key"], xero_config["consumer_secret"]) print credentials.url webbrowser.open(credentials.url) verifier = raw_input("Enter auth code: ") credentials.verify(verifier) with open(args.credentials_file, "w") as credentials_fh: pickle.dump(credentials.state, credentials_fh) xero = Xero(credentials) # Get userids matching user email userids = {} users = xero.users.all() # print users for user in users: