def post_send(): short_prescription_id = get_prescription_id_from_cookie() send_request = load_send_request(short_prescription_id) send_request_xml = make_eps_api_convert_message_request( get_access_token(), send_request) send_prescription_response = make_eps_api_process_message_request( get_access_token(), send_request) return { "prescription_id": short_prescription_id, "success": send_prescription_response.status_code == 200, "request_xml": send_request_xml.text, "request": json.dumps(send_request), "response": json.dumps(send_prescription_response.json()), }
def post_dispense(): if (config.ENVIRONMENT == "prod"): return app.make_response("Bad Request", 400) dispense_request = flask.request.json response = make_eps_api_process_message_request(get_access_token(), dispense_request) dispense_request_xml = make_eps_api_convert_message_request( get_access_token(), dispense_request) return { "body": json.dumps(response.json()), "success": response.status_code == 200, "request_xml": dispense_request_xml.text, "request": json.dumps(dispense_request), "response": json.dumps(response.json()), }
def get_send(): auth_method = get_auth_method_from_cookie() signature_response_json = make_sign_api_signature_download_request( auth_method, get_access_token(), flask.request.args.get("token")) short_prescription_id = get_prescription_id_from_cookie() prepare_response = load_prepare_response(short_prescription_id) payload = prepare_response["digest"] signature = signature_response_json["signature"] certifcate = signature_response_json["certificate"] payload_decoded = (base64.b64decode(payload).decode("utf-8").replace( '<SignedInfo xmlns="http://www.w3.org/2000/09/xmldsig#">', "<SignedInfo>")) xml_dsig = ( f'<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">{payload_decoded}' f"<SignatureValue>{signature}</SignatureValue>" f"<KeyInfo><X509Data><X509Certificate>{certifcate}</X509Certificate></X509Data></KeyInfo>" f"</Signature>") xml_dsig_encoded = base64.b64encode(xml_dsig.encode()).decode() prepare_request = load_prepare_request(short_prescription_id) provenance = create_provenance(prepare_response["timestamp"], xml_dsig_encoded) prepare_request["entry"].append(provenance) send_request = prepare_request add_send_request(short_prescription_id, send_request) return render_client("send", sign_response={"signature": xml_dsig_encoded})
def post_sign(): sign_request = flask.request.json skip_signature_page = sign_request["skipSignaturePage"] short_prescription_id = get_prescription_id_from_cookie() prepare_request = load_prepare_request(short_prescription_id) prepare_response = make_eps_api_prepare_request(get_access_token(), prepare_request) auth_method = get_auth_method_from_cookie() sign_response = make_sign_api_signature_upload_request( auth_method, get_access_token(), prepare_response["digest"], prepare_response["algorithm"]) print("Response from Signing Service signature upload request...") print(json.dumps(sign_response)) response = app.make_response({"redirectUri": sign_response["redirectUri"]}) set_skip_signature_page_cookie(response, str(skip_signature_page)) add_prepare_response(short_prescription_id, prepare_response) return response
def refresh_handler(request): logger.Logger().log(f'Get refresh from {request.hostname}:{request.port}') req_handler = request_handler.RequestHandler( request, base_request_checker.BaseRequestChecker(request)) jwt_access_token = auth.get_access_token(req_handler.get_login()) res = {'access-token': jwt_access_token} logger.Logger().log(f'Response {res} to {request.hostname}:{request.port}') return req_handler.response(**res)
def post_cancel(): cancel_request = flask.request.json short_prescription_id = get_prescription_id(cancel_request) cancel_request_xml = make_eps_api_convert_message_request( get_access_token(), cancel_request) cancel_response = make_eps_api_process_message_request( get_access_token(), cancel_request) response = app.make_response({ "prescription_id": short_prescription_id, "success": cancel_response.status_code == 200, "request": json.dumps(cancel_request), "request_xml": cancel_request_xml.text, "response": json.dumps(cancel_response.json()), }) return response
def login_as_producer(): code_auth = request.args.get('code') token = get_access_token(code_auth) user_id = get_user_id(token) api_token = get_MGMT_API_ACCESS_TOKEN() payload = verify_decode_jwt(token) if 'permissions' not in payload: abort(400) permissions = payload.get('permissions') if len(permissions) == 0: url3 = f'https://{AUTH0_DOMAIN}/api/v2/users/{user_id}/roles' headers = { 'content-type': 'application/json', 'authorization': 'Bearer ' + api_token, 'cache-control': 'no-cache' } data = '{ "roles": [ " rol_t2ets4eZtnaqf6Xo " ] }' data = data.encode('ascii') req3 = uri.Request(url3, data, headers) try: uri.urlopen(req3) except uri.URLError as e: print('URL Error: ', e.reason) except uri.HTTPError as e: print('HTTP Error code: ', e.code) else: session['role'] = 'producer' return redirect(url_for('home')) if 'delete:movie' in permissions: session['role'] = 'producer' elif 'delete:movie' not in permissions and 'delete:actor' \ in permissions: session['role'] = 'director' elif 'delete:actor' not in permissions: session['role'] = 'Casting Assistant' return redirect(url_for('home'))
def init(): db.connect() global tinder if not config.misc.get("isMockingEnabled", False): token = auth.get_access_token(config.facebook_auth["email"], config.facebook_auth["password"]) print token tinder = api.TinderAPI(token, auth.get_facebook_id(token), socketio) else: tinder = mock_session.MockSession()
def _get_team_name(team_id): """Get the name of a certain team""" # Create URL to get team name url = '{}/teams/{}?access_token={}'.format(GITHUB_API_URL, team_id, get_access_token()) # Retrieve team name from result result = json.loads(fetch_url(url)) return result['name']
def main(): token = get_access_token() arguments = docopt.docopt(__doc__) list_id = arguments['--list-id'] if list_id: response = requests.get(f'http://a.wunderlist.com/api/v1/tasks', {'list_id': list_id}, headers={ 'X-Access-Token': token, 'X-Client-ID': client_id }) assert response.status_code == 200 json = response.json() json.sort(key=lambda item: item['created_at']) json.reverse() sorted_ids = [item['id'] for item in json] response = requests.get( f'http://a.wunderlist.com/api/v1/task_positions', {'list_id': list_id}, headers={ 'X-Access-Token': token, 'X-Client-ID': client_id }) assert response.status_code == 200 positions_json = response.json() if positions_json[0]['values'] == sorted_ids: print('Nothing changed.') else: response = requests.put( f'http://a.wunderlist.com/api/v1/task_positions/{positions_json[0]["id"]}', json={ 'revision': positions_json[0]['revision'], 'values': [item['id'] for item in json] }, headers={ 'X-Access-Token': token, 'X-Client-ID': client_id }) assert response.status_code == 200 print('Done!') else: response = requests.get('http://a.wunderlist.com/api/v1/lists', headers={ 'X-Access-Token': token, 'X-Client-ID': client_id }) assert response.status_code == 200 json = response.json() for item in json: print(f"{item['title']}: {item['id']}")
def get_all_org_members(): """Get all members belonging to org""" url = '{}/orgs/{}/members?access_token={}'.format(GITHUB_API_URL, os.environ.get('ORG'), get_access_token()) all_members = json.loads(fetch_url(url)) response = _append_to_response(all_members) return response
def access_token_timer(): global at_timer global access_token at_timer = threading.Timer(6000, access_token_timer) at_timer.start() is_success, result = auth.get_access_token(config.CorpID, config.Secret) if is_success == True: access_token = result.get('access_token') expires_in = result.get('expires_in') #print access_token #debug only else: sleep(300)
def get_team_members(team_id): """Get the members of a given team""" # Get members belonging to the selected team url = '{}/teams/{}/members?access_token={}'.format( GITHUB_API_URL, team_id, get_access_token()) team_members = json.loads(fetch_url(url)) response = _append_to_response(team_members) return response
def authenticate(self, auth_code, client_id, secret, redirect): """ Generate and save an access token using public and private keys, as well as the authorization code. Args: auth_code - The code query parameter returned from /oauth/authorize client_id - The public client ID for the app secret - The secret key for the app redirect - The app redirect url """ self.config['access_token'] = get_access_token(auth_code, self.config['apiroot'], client_id, secret, redirect)
def _remove_member_from_team(team_id, member): """Remove an org member from a team""" url = '{}/teams/{}/members/{}?access_token={}'.format( GITHUB_API_URL, team_id, member, get_access_token()) fetch_url(url, urlfetch.DELETE) # Create a log entry message = '{} was removed from {}'.format(member, _get_team_name(team_id)) create_log(message)
def _add_members_to_team(team_id, members): """Add members of org to a team""" for member in members: url = '{}/teams/{}/members/{}?access_token={}'.format( GITHUB_API_URL, team_id, member, get_access_token()) fetch_url(url, urlfetch.PUT) # Create a log entry message = '{} was added to {}'.format(members, _get_team_name(team_id)) create_log(message)
def _get_front_page_data(): """Retrieve list of private repos for the org""" # Set the url to retrieve all the private repos for an org url = 'https://api.github.com/orgs/{}/repos?access_token={}'.format( os.environ.get('ORG'), get_access_token()) # Fetch the list of private repos content = json.loads(fetch_url(url)) response = [] # Retrieve the repo names from the JSON response for value in content: response.append(value.get('name')) return response
def download(): zFile = io.BytesIO() with zipfile.ZipFile(zFile, 'w') as zip_file: short_prescription_ids = get_prescription_ids_from_cookie() for index, short_prescription_id in enumerate(short_prescription_ids): bundle = load_prepare_request(short_prescription_id) xml = make_eps_api_convert_message_request(get_access_token(), bundle).text zip_file.writestr(f"send_request_{index+1}.json", json.dumps(bundle, indent=2)) zip_file.writestr(f"send_request_{index+1}.xml", xml) zFile.seek(0) return flask.send_file(zFile, mimetype='application/zip', as_attachment=True, attachment_filename='messages.zip')
def add_team(team_id, repo): """Add team access to a repo""" # Build url for HTTP request url = '{}/teams/{}/repos/{}/{}?access_token={}'.format( GITHUB_API_URL, team_id, os.environ.get('ORG'), repo, get_access_token()) # Give repo access to team fetch_url(url, urlfetch.PUT) # Create a log entry message = '{} was added to the {} repo'.format(_get_team_name(team_id), repo) create_log(message)
def get_all_teams(): """Get all teams belonging to org""" # Create url url = '{}/orgs/{}/teams?access_token={}'.format(GITHUB_API_URL, os.environ.get('ORG'), get_access_token()) # Fetch results from Github content = json.loads(fetch_url(url)) # Create a dict to store results response = {} for value in content: response[value.get('name')] = (value.get('id'), value.get('permission')) return response
def remove_team(team_id, repo): """Remove team access from a repo""" # Build url for HTTP request url = '{}/teams/{}/repos/{}/{}?access_token={}'.format( GITHUB_API_URL, team_id, os.environ.get('ORG'), repo, get_access_token()) # Remove repo access from a team fetch_url(url, urlfetch.DELETE) # Create a log entry message = '{} was removed from the {} repo'.format(_get_team_name(team_id), repo) create_log(message)
def _create_private_repo(name, description, private=True): """Create a private repo""" url = '{}/orgs/{}/repos?access_token={}'.format(GITHUB_API_URL, os.environ.get('ORG'), get_access_token()) fields = { "name": name, "description": description, "private": True, } # Send request to Github's API fetch_url(url, urlfetch.POST, json.dumps(fields)) # Create a log entry message = '{} created the {} repo'.format(get_user_name(), name) create_log(message)
def generate_token(self): request_body = { "facebookId": "10152933244684657", "facebookToken": None, "installId": "B4D7C24A-A126-48FA-ACFF-C239FC7661B8" } request_body['facebookToken'] = str(get_access_token()) url = "https://prod-api.hingeaws.net/identity" identity_response = requests.post(url, data=json.dumps(request_body), headers=self.headers) identity_json = identity_response.json() auth_token = identity_json['token'] self.headers['Authorization'] = f'Bearer {auth_token}' return auth_token
def edit_team(team_name, team_id, edit_type): """Edit the access of a team""" url = '{}/teams/{}?access_token={}'.format(GITHUB_API_URL, team_id, get_access_token()) # Get the required info to perform the query fields = { "name": team_name, "id": team_id, "permission": edit_type, } fetch_url(url, urlfetch.PATCH, json.dumps(fields)) # Create a log entry message = '{} was given {} access'.format(team_name, edit_type) create_log(message)
import requests, base64, json import csv from requests.auth import HTTPBasicAuth import pandas as pd import numpy as np # from sklearn.cluster import KMeans from sklearn import preprocessing import pdb from sklearn.neighbors import NearestNeighbors import sys import auth MIN_COMMON_SONGS = 1 token = auth.get_access_token() def build_featurized_df(df): filtered_cols = ['duration_ms', 'time_signature', 'key', 'mode'] for column in df: if df[column].dtype == np.object: filtered_cols.append(column) df_filtered = df.drop(columns=filtered_cols) x = df_filtered.values x_scaled = preprocessing.scale(x) return pd.DataFrame(x_scaled, index = df_filtered.index, columns = df_filtered.columns) def find_song_index_from_title(song_title, df): song_index = -1 for i, row in df.iterrows(): if song_title == row['name']: return i if song_index == -1:
# encoding: utf-8 from config import CorpID, secret import auth import message import user import department import media def print_dict(result): for k, v in result.iteritems(): print '%s : %s' % (k, v) is_success, result = auth.get_access_token(CorpID, secret) access_token = result.get('access_token') # department # is_success, result = department.get_department_list(access_token) # print_dict(result) # message touser = '******' toparty = '1868210' # send_type = 'text' # content = {'content': 'dingding'} send_type = 'image' content = {'media_id': '@lADOAMnd1M0Bqc0CgA'} is_success, result = message.send(access_token, touser, toparty, send_type,
#!/usr/bin/env python # encoding: utf-8 from config import CorpID, secret import auth import message import user import department import media def print_dict(result): for k, v in result.iteritems(): print '%s : %s' % (k, v) is_success, result = auth.get_access_token(CorpID, secret) access_token = result.get('access_token') # department # is_success, result = department.get_department_list(access_token) # print_dict(result) # message touser = '******' toparty = '1868210' # send_type = 'text' # content = {'content': 'dingding'} send_type = 'image' content = {'media_id': '@lADOAMnd1M0Bqc0CgA'} is_success, result = message.send(access_token, touser, toparty, send_type, content)
def post_release(): if (config.ENVIRONMENT == "prod"): return app.make_response("Bad Request", 400) release = flask.request.json short_prescription_id = release.get("prescriptionId") ods_code = release["odsCode"] if short_prescription_id: release_request_body = { "resourceType": "Parameters", "id": str(uuid.uuid4()), "parameter": [{ "name": "owner", "valueIdentifier": { "system": "https://fhir.nhs.uk/Id/ods-organization-code", "value": ods_code } }, { "name": "group-identifier", "valueIdentifier": { "system": "https://fhir.nhs.uk/Id/prescription-order-number", "value": short_prescription_id } }, { "name": "status", "valueCode": "accepted" }] } else: release_request_body = { "resourceType": "Parameters", "id": str(uuid.uuid4()), "parameter": [ { "name": "owner", "valueIdentifier": { "system": "https://fhir.nhs.uk/Id/ods-organization-code", "value": ods_code }, }, { "name": "status", "valueCode": "accepted" }, ], } response = make_eps_api_release_request( get_access_token(), release_request_body, ) release_request_xml = make_eps_api_convert_message_request( get_access_token(), release_request_body) return { "body": json.dumps(response.json()), "success": response.status_code == 200, "request_xml": release_request_xml.text, "request": json.dumps(release_request_body), "response": json.dumps(response.json()), }
# LIST ALL TRANSPORTS result = gq_client.execute(query=list_transports_query, operation_name='listTransports') print("LIST RESULT:") print(result) # GET ONE TRANSPORT get_variables = {"getInput": newly_created_transport_id} result = gq_client.execute(query=get_transport_query, operation_name='getTransport', variables=get_variables) print("GET RESULT:") print(result) # DELETE TRANSPORT delete_variables = {"deleteInput": {"id": newly_created_transport_id}} result = gq_client.execute(query=delete_transport_mutation, operation_name='deleteTransport', variables=delete_variables) print("DELETE RESULT:") print(result) if __name__ == "__main__": access_token = get_access_token() gq_client = GraphqlClient(endpoint=APPSYNC_ENDPOINT_DEV, headers={'authorization': access_token}) execute_test_scenario()