Example #1
0
def getToken(code):
    uid = current_user.get_id()
    api_client = enablebanking.ApiClient('Alior', connector_settings=polish_api_data)  # Create client instance.
    auth_api = enablebanking.AuthApi(api_client)
    token = auth_api.make_token(grant_type="authorization_code",  # grant type, MUST be set to "authorization_code"
                            code=code,
                            # The code received in the query string when redirected from authorization
                            redirect_uri=redirect_url)
    queries.updateToken(uid, token)
Example #2
0
def keyRedirect():
    # token = auth_api.make_token(grant_type="authorization_code",  # grant type, MUST be set to "authorization_code"
    #                                 code=parsed_query.get("code"),
    #                                 # The code received in the query string when redirected from authorization
    #                                 redirect_uri=REDIRECT_URL)
    code = request.args.get("code")
    # print(f"\nCode: {code}\n\n")

    api_client = enablebanking.ApiClient(
        "Alior",
        connector_settings=nordea_settings())  # Create client instance.

    auth_api = enablebanking.AuthApi(
        api_client)  # Create authentication interface.

    # auth_url = auth_api.get_auth(
    #     response_type="code",  # OAuth2 response type
    #     redirect_uri=REDIRECT_URL,  # redirect URI
    #     scope=["aisp"],  # API scopes
    #     state="okok").url # state to pass to redirect URL

    # redirected_url = util.read_redirected_url(auth_url, REDIRECT_URL)
    # parsed_query = util.parse_redirected_url(redirected_url)  # calling helper functions for CLI interaction
    # logging.info("Parsed query: %s", parsed_query)

    token = auth_api.make_token(
        grant_type=
        "authorization_code",  # grant type, MUST be set to "authorization_code"
        code=code,
        # The code received in the query string when redirected from authorization
        redirect_uri=REDIRECT_URL)
    # logging.info("Token: %s", token)

    aisp_api = enablebanking.AISPApi(
        api_client
    )  # api_client has already accessToken and refreshToken applied after call to makeToken()

    accounts = aisp_api.get_accounts()
    x = "Accounts info: %s" % accounts

    for account in accounts.accounts:
        transactions = aisp_api.get_account_transactions(
            account.account_id.iban,
            date_from=(datetime.datetime.now() -
                       datetime.timedelta(days=89)).strftime('%Y-%m-%d'),
            date_to=datetime.datetime.now().strftime('%Y-%m-%d'))
        x += "Transactions info: %s" % transactions

        balances = aisp_api.get_account_balances(account.account_id.iban)
        x += "Balances info: %s" % balances
    # TODO: how to save it somewhere else
    # do_magic.magic(x)
    return x
Example #3
0
def generateToken():
    api_client = enablebanking.ApiClient('Alior', connector_settings=polish_api_data)  # Create client instance.
    auth_api = enablebanking.AuthApi(api_client)  # Create authentication interface.
    auth_url = auth_api.get_auth(
        response_type='code',  # OAuth2 response type
        redirect_uri=redirect_url,  # redirect URI
        scope=['aisp'],  # API scopes
        state='okok', 
        access = enablebanking.Access(
            valid_until=(datetime.datetime.now() + datetime.timedelta(days=89)).strftime('%Y-%m-%d'),
            balances=enablebanking.BalancesAccess(),
            transactions=enablebanking.TransactionsAccess())).url # state to pass to redirect URL
    res = {'oauth_link': auth_url}
    return make_response(res, 200)
Example #4
0
def registerToken():
    api_client = enablebanking.ApiClient(
        "Alior", connector_settings=polish_api_data)  # Create client instance.
    auth_api = enablebanking.AuthApi(
        api_client)  # Create authentication interface.
    auth_url = auth_api.get_auth(
        response_type="code",  # OAuth2 response type
        redirect_uri=REDIRECT_URL,  # redirect URI
        scope=["aisp"],  # API scopes
        state="okok",
        access=enablebanking.Access(
            valid_until=(datetime.datetime.now() +
                         datetime.timedelta(days=89)).strftime('%Y-%m-%d'),
            balances=enablebanking.BalancesAccess(),
            transactions=enablebanking.TransactionsAccess())
    ).url  # state to pass to redirect URL

    print(auth_url)
Example #5
0
def main():
    api_client = enablebanking.ApiClient(
        "Alior",
        connector_settings=nordea_settings())  # Create client instance.
    auth_api = enablebanking.AuthApi(
        api_client)  # Create authentication interface.
    auth_url = auth_api.get_auth(
        response_type="code",  # OAuth2 response type
        redirect_uri=REDIRECT_URL,  # redirect URI
        scope=["aisp"],  # API scopes
        state="okok",
        access=enablebanking.Access(
            valid_until=(datetime.datetime.now() +
                         datetime.timedelta(days=89)).strftime('%Y-%m-%d'),
            balances=enablebanking.BalancesAccess(),
            transactions=enablebanking.TransactionsAccess())
    ).url  # state to pass to redirect URL

    redirected_url = util.read_redirected_url(auth_url, REDIRECT_URL)
    parsed_query = util.parse_redirected_url(
        redirected_url)  # calling helper functions for CLI interaction
    logging.info("Parsed query: %s", parsed_query)

    token = auth_api.make_token(
        grant_type=
        "authorization_code",  # grant type, MUST be set to "authorization_code"
        code=parsed_query.get("code"),
        # The code received in the query string when redirected from authorization
        redirect_uri=REDIRECT_URL)
    logging.info("Token: %s", token)

    aisp_api = enablebanking.AISPApi(
        api_client
    )  # api_client has already accessToken and refreshToken applied after call to makeToken()

    accounts = aisp_api.get_accounts()
    logging.info("Accounts info: %s", accounts)

    for account in accounts.accounts:
        transactions = aisp_api.get_account_transactions(account.resource_id)
        logging.info("Transactions info: %s", transactions)

        balances = aisp_api.get_account_balances(account.resource_id)
        logging.info("Balances info: %s", balances)
Example #6
0
 def getLoginURLandAPI(self, bank):
     assert bank in ["Alior", "KIR"], "Unknown bank!"
     settings = self.bank2config[bank]
     redirect = self.bank2redirect[bank]
     api_client = enablebanking.ApiClient(
         bank, connector_settings=settings(redirect))
     auth_api = enablebanking.AuthApi(api_client)
     access = enablebanking.Access(
         valid_until=(datetime.datetime.now() +
                      datetime.timedelta(days=89)).strftime('%Y-%m-%d'),
         balances=enablebanking.BalancesAccess(),
         transactions=enablebanking.TransactionsAccess())
     auth_url = auth_api.get_auth(
         response_type="code",  # OAuth2 response type
         redirect_uri=redirect,  # redirect URI
         scope=["aisp"],  # API scopes
         access=access,
         state="test").url  # state to pass to redirect URL
     return auth_url, redirect, (api_client, auth_api)
Example #7
0
def main():
    api_client = enablebanking.ApiClient(
        "Alior",
        connector_settings=alior_settings())  # Create client instance.
    pisp_api = enablebanking.PISPApi(api_client)

    payment_request_resource = enablebanking.PaymentRequestResource(
        payment_type_information=enablebanking.PaymentTypeInformation(
            service_level="SEPA",  # will be resolved to "pis:EEA"
            local_instrument="SEPA"
        ),  # set explicitly, can also be for example SWIFT or ELIXIR
        credit_transfer_transaction=[
            enablebanking.CreditTransferTransaction(
                instructed_amount=enablebanking.AmountType(amount="12.25",
                                                           currency="EUR"),
                beneficiary=enablebanking.Beneficiary(
                    creditor=enablebanking.PartyIdentification(
                        name="Creditor Name",
                        postal_address={
                            "country":
                            "RO",
                            "addressLine": [
                                "Creditor Name", "Creditor Address 1",
                                "Creditor Address 2"
                            ]
                        }),
                    creditor_account=enablebanking.AccountIdentification(
                        iban="RO56ALBP0RON421000045875"),
                ),
                remittance_information=["Some remittance information"],
            ),
        ],
        debtor=enablebanking.PartyIdentification(
            name="Debtor Name",
            postal_address={
                "country":
                "PL",
                "addressLine":
                ["Debtor Name", "Debtor Address 1", "Debtor Address 2"]
            }),
        debtor_account=enablebanking.AccountIdentification(
            iban="PL63249000050000400030900682"),
    )
    request_creation = pisp_api.make_payment_request(payment_request_resource)
    logging.info("Request creation: %s", request_creation)

    redirected_url = read_redirected_url(
        request_creation.links.consent_approval.href,
        REDIRECT_URL)  # calling helper functions for CLI interaction
    auth_api = enablebanking.AuthApi(
        api_client)  # Create authentication interface.
    parsed_query_params = auth_api.parse_redirect_url(redirected_url)
    logging.info("Query params: %s", parsed_query_params)

    payment_request_confirmation = pisp_api.make_payment_request_confirmation(
        request_creation.payment_request_resource_id,
        confirmation=enablebanking.PaymentRequestConfirmation(
            psu_authentication_factor=parsed_query_params.code,
            payment_request=payment_request_resource))
    logging.info("Payment request confirmation: %s",
                 payment_request_confirmation)
def main():
    api_meta = get_connector_meta(
        CONNECTOR_NAME,
        CONNECTOR_COUNTRY)  # get meta information for current connector

    api_client = enablebanking.ApiClient(
        CONNECTOR_NAME,
        connector_settings=CONNECTOR_SETTINGS)  # Create client instance.

    auth_api = enablebanking.AuthApi(
        api_client)  # Create authentication interface.

    client_info = enablebanking.ClientInfo()
    connector_psu_headers = api_meta.required_psu_headers
    if "psuIpAddress" in connector_psu_headers:
        client_info.psu_ip_address = "10.10.10.10"

    if "psuUserAgent" in connector_psu_headers:
        client_info.psu_user_agent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1.1 Safari/605.1.15"

    auth_api.set_client_info(client_info=client_info)

    access = enablebanking.Access(valid_until=(datetime.datetime.now() +
                                               datetime.timedelta(days=89)))
    get_auth_params: Dict[str, Any] = {"state": str(uuid.uuid4())}
    if api_meta.auth_info[0].info.access:
        get_auth_params["access"] = access
    if api_meta.auth_info[0].info.user_id_required:
        get_auth_params["user_id"] = "some_id"
    if api_meta.auth_info[0].info.password_required:
        get_auth_params["password"] = "******"
    auth_response = auth_api.get_auth(**get_auth_params)

    make_token_response = None
    if auth_response.url:
        # if url is returned, then we are doing redirect flow
        redirected_url = read_redirected_url(auth_response.url, REDIRECT_URL)
        query_params = auth_api.parse_redirect_url(redirected_url)
        logging.info("Parsed query: %s", query_params)
        make_token_response = auth_api.make_token(
            "authorization_code",  # grant type, MUST be set to "authorization_code"
            query_params.code,
            auth_env=auth_response.env,
        )
    else:
        # decoupled flow otherwise
        # Doing a retry to check periodically whether user has already authorized a consent
        sleep_time = 3
        for _ in range(3):
            try:
                make_token_response = auth_api.make_token(
                    "authorization_code",  # grant type, MUST be set to "authorization_code"
                    code="",
                    auth_env=auth_response.env,
                )
            except enablebanking.MakeTokenException as e:
                logging.debug(
                    f"Failed to get authorization code, sleeping for {sleep_time} seconds"
                )
                time.sleep(sleep_time)
            else:
                break

    logging.info("Token: %s", make_token_response)

    aisp_api = enablebanking.AISPApi(
        api_client
    )  # api_client has already accessToken and refreshToken applied after call to makeToken()

    if api_meta.modify_consents_info[0].info.before_accounts:
        # bank requires to create a consent explicitly before accessing list of accounts
        consent = aisp_api.modify_consents(access=access)
        logging.debug(f"Consent: {consent}")
        try:
            # If returned consent has a redirect url, we need to redirect a PSU there
            consent_url = consent.links.redirect.href
            redirect_url = read_redirected_url(consent_url, REDIRECT_URL)
            logging.debug(f"Redirect url: {redirect_url}")
        except AttributeError:
            pass

    accounts = aisp_api.get_accounts()
    logging.info("Accounts info: %s", accounts)

    if api_meta.modify_consents_info[0].info.accounts_required:
        # bank requires to create a consent with account ids specified
        account_ids = [
            enablebanking.AccountIdentification(iban=acc.account_id.iban)
            for acc in accounts.accounts
        ]
        access.accounts = account_ids
        consent = aisp_api.modify_consents(access=access)
        logging.debug(f"Consent: {consent}")
        try:
            # If returned consent has a redirect url, we need to redirect a PSU there
            consent_url = consent.links.redirect.href
            redirect_url = read_redirected_url(consent_url, REDIRECT_URL)
            logging.debug(f"Redirect url: {redirect_url}")
        except AttributeError:
            pass

    for account in accounts.accounts:
        transactions = aisp_api.get_account_transactions(account.resource_id)
        logging.info("Transactions info: %s", transactions)

        balances = aisp_api.get_account_balances(account.resource_id)
        logging.info("Balances info: %s", balances)