Пример #1
0
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))
Пример #2
0
    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')
Пример #3
0
    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')
Пример #4
0
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
Пример #5
0
    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
Пример #6
0
    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
Пример #7
0
    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
Пример #8
0
    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']))
Пример #9
0
    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")
Пример #10
0
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
Пример #11
0
    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")
Пример #12
0
def yellowant_oauth_redirect(request):
    """Receive the oauth2 code from YA to generate a new user integration
    
    This method calls utilizes the YA Python SDK to create a new user integration on YA.
    This method only provides the code for creating a new user integration on YA. Beyond that, you might need to 
    authenticate the user on the actual application (whose APIs this application will be calling) and store a relation
    between these user auth details and the YA user integration.
    """
    # oauth2 code from YA, passed as GET params in the url
    print('inside yellowant_oauth_redirect')
    code = request.GET.get("code")
    print(code)

    print("Hello\n\n")

    # the unique string to identify the user for which we will create an integration
    state = request.GET.get("state")
    print("statis is")
    print(state)
    # fetch user with the help of state
    yellowant_redirect_state = YellowAntRedirectState.objects.get(state=state)
    user = yellowant_redirect_state.user
    print("user is")
    print(user)

    # initialize the YA SDK client with your application credentials
    ya_client = YellowAnt(app_key=settings.YA_CLIENT_ID, app_secret=settings.YA_CLIENT_SECRET, access_token=None,
        redirect_uri=settings.YA_REDIRECT_URL)


    # get the access token for a user integration from YA against the code
    print ("here")
    access_token_dict = ya_client.get_access_token(code)
    print(str(access_token_dict)+" Accesstoken")
    print("Inside \n\n")
    access_token = access_token_dict["access_token"]

    # reinitialize the YA SDK client with the user integration access token
    ya_client = YellowAnt(access_token=access_token)

    # get YA user details
    ya_user = ya_client.get_user_profile()

    # create a new user integration for your application
    user_integration = ya_client.create_user_integration()

    # save the YA user integration details in your database
    ut=UserIntegration.objects.create(user=user, yellowant_user_id=ya_user["id"],
        yellowant_team_subdomain=ya_user["team"]["domain_name"],
        yellowant_integration_id=user_integration["user_application"],
        yellowant_integration_invoke_name=user_integration["user_invoke_name"],
        yellowant_integration_token=access_token)

    Xero_Credentials.objects.create(user_integration=ut,XERO_OAUTH_SECRET='0',XERO_OAUTH_TOKEN='0',XERO_EXPIRE='0',XERO_AUTH_EXPIRE='0' ,XERO_UPDATE_LOGIN_FLAG=False)
    
    # A new YA user integration has been created and the details have been successfully saved in your application's 
    # database. However, we have only created an integration on YA. As a developer, you need to begin an authentication 
    # process for the actual application, whose API this application is connecting to. Once, the authentication process 
    # for the actual application is completed with the user, you need to create a db entry which relates the YA user
    # integration, we just created, with the actual application authentication details of the user. This application
    # will then be able to identify the actual application accounts corresponding to each YA user integration.
    # return HttpResponseRedirect("to the actual application authentication URL")

    print(str(user_integration["user_application"])+"  integration ID")


    global integ_id
    global saved_state
    global token
    integ_id= UserIntegration.objects.get(yellowant_integration_id=user_integration["user_application"])


    #-------------------------------------------------------------------------------------------------
    credentials=PublicCredentials('BGJJ6JSSEAGIRWQ9SYKA1T3O7Y6IPF','2JRHWN0QQ1K0AHVDZVUPKCVIQKUUNB','http://127.0.0.1:8000/return/')
    print(credentials.url)
    webbrowser.open(credentials.url)
    time.sleep(15)
    #time.sleep(60) for the user
    credentials.verify(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=integ_id.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()

    new_credentials=PublicCredentials(**saved_state)
    xero=Xero(new_credentials)
    print("successful authentication")


    return HttpResponseRedirect("/")
Пример #13
0
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:
    userids[user['EmailAddress']] = user['UserID']

# Get receipts and add them to Xero
if args.input_file == '-':
    in_fh = sys.stdin
else:
Пример #14
0
    def do_GET(self):
        """
        Handle GET request
        """
        config = configparser.ConfigParser()
        config.read('config.ini')

        consumer_key = config['APP']['XERO_CONSUMER_KEY']
        consumer_secret = config['APP']['XERO_CONSUMER_SECRET']
        callback_url = config['APP']['CALLBACK_URL']
        accounts_and_vendors_files_path = config['APP'][
            'ACCOUNTS_AND_VENDORS_FILES_PATH']
        vendors_file_name = config['APP']['VENDORS_FILE_NAME']
        accounts_file_name = config['APP']['ACCOUNTS_FILE_NAME']

        if consumer_key is None or consumer_secret is None:
            raise KeyError(
                'Please define both XERO_CONSUMER_KEY and XERO_CONSUMER_SECRET variables in config.ini file'
            )

        if callback_url is None:
            raise KeyError('Please define callback_url in config.ini file')

        if accounts_and_vendors_files_path is None or vendors_file_name is None or vendors_file_name is None:
            raise KeyError(
                'Please define Account and Vendors file names and paths in config.ini file'
            )

        print("Serving path: {}".format(self.path))
        path = urlparse(self.path)

        if path.path == '/do-auth':
            credentials = PublicCredentials(consumer_key,
                                            consumer_secret,
                                            callback_uri=callback_url)

            # Save generated credentials details to persistent storage
            for key, value in credentials.state.items():
                OAUTH_PERSISTENT_SERVER_STORAGE.update({key: value})

            # Redirect to Xero at url provided by credentials generation
            self.redirect_response(credentials.url)
            return

        elif path.path == '/oauth':
            params = dict(parse_qsl(path.query))
            if 'oauth_token' not in params or 'oauth_verifier' not in params or 'org' not in params:
                self.send_error(500, message='Missing parameters required.')
                return

            stored_values = OAUTH_PERSISTENT_SERVER_STORAGE
            credentials = PublicCredentials(**stored_values)

            try:
                credentials.verify(params['oauth_verifier'])

                # Resave our verified credentials
                for key, value in credentials.state.items():
                    OAUTH_PERSISTENT_SERVER_STORAGE.update({key: value})

            except XeroException as e:
                self.send_error(500,
                                message='{}: {}'.format(
                                    e.__class__, e.message))
                return

            # Once verified, api can be invoked with xero = Xero(credentials)
            self.redirect_response('/verified')
            return

        elif path.path == '/verified':
            stored_values = OAUTH_PERSISTENT_SERVER_STORAGE
            credentials = PublicCredentials(**stored_values)

            try:
                xero = Xero(credentials)

            except XeroException as e:
                self.send_error(500,
                                message='{}: {}'.format(
                                    e.__class__, e.message))
                return

            page_body = ''

            vendors = xero.contacts.filter(IsSupplier=True)
            accounts = xero.accounts.all()

            if vendors:
                vendors_file = accounts_and_vendors_files_path + '/' + vendors_file_name
                with open(vendors_file, 'w') as fileVendors:
                    json.dump(vendors,
                              fileVendors,
                              indent=4,
                              sort_keys=True,
                              default=str)
                page_body += ('Check vendors list in ' +
                              accounts_and_vendors_files_path + '/' +
                              vendors_file_name + '<br>')
            else:
                page_body += 'No vendors.\n'

            if accounts:
                accounts_file = accounts_and_vendors_files_path + '/' + accounts_file_name
                with open(accounts_file, 'w') as fileAccounts:
                    json.dump(accounts,
                              fileAccounts,
                              indent=4,
                              sort_keys=True,
                              default=str)
                    page_body += ('Check account list in ' +
                                  accounts_and_vendors_files_path + '/' +
                                  accounts_file_name)
            else:
                page_body += 'No accounts.\n'

            self.page_response(title='Downloading vendor and account files',
                               body=page_body)
            return

        SimpleHTTPRequestHandler.do_GET(self)
Пример #15
0
    def do_GET(self):
        """
        Handle GET request
        """
        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:
            raise KeyError(
                'Please define both XERO_CONSUMER_KEY and XERO_CONSUMER_SECRET environment variables'
            )

        print("Serving path: {}".format(self.path))
        path = urlparse(self.path)

        if path.path == '/do-auth':
            credentials = PublicCredentials(
                consumer_key,
                consumer_secret,
                callback_uri='http://localhost:8000/oauth')

            # Save generated credentials details to persistent storage
            for key, value in credentials.state.items():
                OAUTH_PERSISTENT_SERVER_STORAGE.update({key: value})

            # Redirect to Xero at url provided by credentials generation
            self.redirect_response(credentials.url)
            return

        elif path.path == '/oauth':
            params = dict(parse_qsl(path.query))
            if 'oauth_token' not in params or 'oauth_verifier' not in params or 'org' not in params:
                self.send_error(500, message='Missing parameters required.')
                return

            stored_values = OAUTH_PERSISTENT_SERVER_STORAGE
            credentials = PublicCredentials(**stored_values)

            try:
                credentials.verify(params['oauth_verifier'])

                # Resave our verified credentials
                for key, value in credentials.state.items():
                    OAUTH_PERSISTENT_SERVER_STORAGE.update({key: value})

            except XeroException as e:
                self.send_error(500,
                                message='{}: {}'.format(
                                    e.__class__, e.message))
                return

            # Once verified, api can be invoked with xero = Xero(credentials)
            self.redirect_response('/verified')
            return

        elif path.path == '/verified':
            stored_values = OAUTH_PERSISTENT_SERVER_STORAGE
            credentials = PublicCredentials(**stored_values)

            try:
                xero = Xero(credentials)

            except XeroException as e:
                self.send_error(500,
                                message='{}: {}'.format(
                                    e.__class__, e.message))
                return

            page_body = 'Your contacts:<br><br>'

            contacts = xero.contacts.all()

            if contacts:
                page_body += '<br>'.join(
                    [str(contact) for contact in contacts])
            else:
                page_body += 'No contacts'
            self.page_response(title='Xero Contacts', body=page_body)
            return

        SimpleHTTPRequestHandler.do_GET(self)
Пример #16
0
    "-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:
    userids[user["EmailAddress"]] = user["UserID"]

# Get receipts and add them to Xero
if args.input_file == "-":
    in_fh = sys.stdin
else:
Пример #17
0
try:
    secret = os.environ['XERO_CONSUMER_SECRET']
except KeyError:
    print("Environment variable XERO_CONSUMER_SECRET not defined")
    raise

# Typically this will be loaded from a database
saved_state = None

if saved_state is not None:
    credentials = PublicCredentials(**saved_state)
else:
    credentials = PublicCredentials(key, secret)
    print(credentials.url)
    code = input("Enter the verification code: ")
    credentials.verify(code)
    saved_state = credentials.state
    print(saved_state)

xero = Xero(credentials)

contacts = xero.contacts.all()
print(contacts)

purchased_items = xero.items.filter(IsPurchased=True)
sold_items = xero.items.filter(IsSold=False)

print("Purchased Items: ")
for i in purchased_items:
    print(i['IsPurchased'])