Skip to content

Instantly share code, notes, and snippets.

@boudhayan-dev
Last active July 2, 2020 22:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save boudhayan-dev/623038c4efafe39a9de9aa34e775130a to your computer and use it in GitHub Desktop.
Save boudhayan-dev/623038c4efafe39a9de9aa34e775130a to your computer and use it in GitHub Desktop.
Contains modification for OData services that require authentication.
  1. Set DESTINATION in Line 21, to the name of your destination.
  2. getCred() will return Username and password of the destination (base64).
  3. getProxy() contains new set of headers to facilitate auth.
from flask import Flask, request, jsonify
import requests
import json
import base64
import os
from cfenv import AppEnv
app = Flask(__name__)
port = int(os.getenv("PORT"))
env = AppEnv()
UAA_SERVICE = env.get_service(name='uaa_service')
DESTINATION_SERVICE = env.get_service(name='destination_service')
CONNECTIVITY_SERVICE = env.get_service(name='connectivity_service')
#destination
CONNECTIVITY_PROXY = CONNECTIVITY_SERVICE.credentials["onpremise_proxy_host"] + ":" + CONNECTIVITY_SERVICE.credentials["onpremise_proxy_port"]
# Name of the Destination configured
DESTINATION = 'BP_API'
CONNECTIVITY_SECRET = CONNECTIVITY_SERVICE.credentials["clientid"] + \
':' + CONNECTIVITY_SERVICE.credentials["clientsecret"]
DESTINATION_SECRET = DESTINATION_SERVICE.credentials["clientid"] + \
':' + DESTINATION_SERVICE.credentials["clientsecret"]
CONNECTIVITY_CREDENTIALS = base64.b64encode(
CONNECTIVITY_SECRET.encode()).decode('ascii')
DESTINATION_CREDENTIALS = base64.b64encode(
DESTINATION_SECRET.encode()).decode('ascii')
def getAccessToken(credentials, serviceName):
#Getting access token for Connectivity service.
headers = {'Authorization': 'Basic ' + credentials,
'content-type': 'application/x-www-form-urlencoded'}
form = [('client_id', serviceName.credentials["clientid"]),
('grant_type', 'client_credentials')]
r = requests.post(
UAA_SERVICE.credentials["url"] + '/oauth/token', data=form, headers=headers)
token = r.json()['access_token']
return token
# Helper function to receive the destination config
def _getDestinationConfig(token):
headers = {'Authorization': 'Bearer ' + token}
r = requests.get(DESTINATION_SERVICE.credentials["uri"] +
'/destination-configuration/v1/destinations/' + DESTINATION, headers=headers)
destination = r.json()
return destination
# Helper that Returns the URL of the destination.
def _getDestinationURL(token):
destination = _getDestinationConfig(token)
return destination["destinationConfiguration"]["URL"]
# Helper function to parse User:Password from the Destinatin config
def _getDestinationCred(token):
destination = _getDestinationConfig(token)
return destination["destinationConfiguration"]["User"]+":"+destination["destinationConfiguration"]["Password"]
def getURL():
# Fetch URL of the Destination
destination_token = getAccessToken(
DESTINATION_CREDENTIALS, DESTINATION_SERVICE)
url = _getDestinationURL(destination_token)
return url
# This function return the credentials set in Destination tab for the OData service.
def getCred():
destination_token = getAccessToken(
DESTINATION_CREDENTIALS, DESTINATION_SERVICE)
cred = _getDestinationCred(destination_token)
# print('Destiantion credentials - '+ cred)
cred = base64.b64encode(
cred.encode()).decode('ascii')
return cred
def getProxy():
data = {}
connectivity_token = getAccessToken(
CONNECTIVITY_CREDENTIALS, CONNECTIVITY_SERVICE)
# Get credentials of the Destination API
# This is the cred used for authentication with the backend OData
api_cred = getCred()
# print('Encoded Destiantion credentials - ' + api_cred)
# Setting proxies and header for the Destination that needs to be called.
# Proxy-Authorization is auth for the proxy server
# Authorization is the auth for the actual backend Odata service
# Accep : application/json -> to receive the response in JSON format.
headers = {
'Proxy-Authorization': 'Bearer ' + connectivity_token,
'Authorization': 'Basic '+ api_cred,
'Accept' : 'application/json'
}
# connection['headers'] = str(headers)
# proxy
proxies = {
"http": CONNECTIVITY_PROXY
}
# connection['proxies'] = str(proxies)
data['headers'] = headers
data['proxies'] = proxies
return data
def makeRequest(request,endpoint):
# # Get the data passed from Recast
# recast_data = request.get_json()
# Get destiantion URL
url = getURL()
#Get proxy parameters
connection = getProxy()
# Call the on-prem process_query service.
r = requests.get(url+endpoint,
proxies=connection['proxies'], headers=connection['headers'], verify=False, timeout=10)
# print(r.text)
return json.loads(r.text)
# Routes
@app.route('/process_query', methods=['POST', 'GET'])
def process_query():
responseText = makeRequest(request, "/A_BusinessPartner('00011234566')")
return jsonify(responseText)
@app.route('/')
def authenticate():
return "App is running fine !"
if __name__ == '__main__':
app.run(host='0.0.0.0', port=port)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment