| 1 |
#!/usr/bin/env python |
| 2 |
|
| 3 |
import argparse |
| 4 |
import os |
| 5 |
import sys |
| 6 |
|
| 7 |
import globus_sdk |
| 8 |
from globus_sdk.token_storage import SimpleJSONFileAdapter |
| 9 |
|
| 10 |
MY_FILE_ADAPTER = SimpleJSONFileAdapter(os.path.expanduser("~/.sdk-manage-flow.json")) |
| 11 |
|
| 12 |
# tutorial client ID |
| 13 |
# we recommend replacing this with your own client for any production use-cases |
| 14 |
CLIENT_ID = "61338d24-54d5-408f-a10d-66c06b59f6d2" |
| 15 |
|
| 16 |
NATIVE_CLIENT = globus_sdk.NativeAppAuthClient(CLIENT_ID) |
| 17 |
|
| 18 |
|
| 19 |
def do_login_flow(scope): |
| 20 |
NATIVE_CLIENT.oauth2_start_flow(requested_scopes=scope, refresh_tokens=True) |
| 21 |
authorize_url = NATIVE_CLIENT.oauth2_get_authorize_url() |
| 22 |
print(f"Please go to this URL and login:\n\n{authorize_url}\n") |
| 23 |
auth_code = input("Please enter the code here: ").strip() |
| 24 |
tokens = NATIVE_CLIENT.oauth2_exchange_code_for_tokens(auth_code) |
| 25 |
return tokens |
| 26 |
|
| 27 |
|
| 28 |
def get_authorizer(flow_id): |
| 29 |
scopes = globus_sdk.SpecificFlowClient(flow_id).scopes |
| 30 |
|
| 31 |
# try to load the tokens from the file, possibly returning None |
| 32 |
if MY_FILE_ADAPTER.file_exists(): |
| 33 |
tokens = MY_FILE_ADAPTER.get_token_data(flow_id) |
| 34 |
else: |
| 35 |
tokens = None |
| 36 |
|
| 37 |
if tokens is None: |
| 38 |
# do a login flow, getting back initial tokens |
| 39 |
response = do_login_flow(scopes.user) |
| 40 |
# now store the tokens and pull out the correct token |
| 41 |
MY_FILE_ADAPTER.store(response) |
| 42 |
tokens = response.by_resource_server[flow_id] |
| 43 |
|
| 44 |
return globus_sdk.RefreshTokenAuthorizer( |
| 45 |
tokens["refresh_token"], |
| 46 |
NATIVE_CLIENT, |
| 47 |
access_token=tokens["access_token"], |
| 48 |
expires_at=tokens["expires_at_seconds"], |
| 49 |
on_refresh=MY_FILE_ADAPTER.on_refresh, |
| 50 |
) |
| 51 |
|
| 52 |
|
| 53 |
def get_flow_client(flow_id): |
| 54 |
authorizer = get_authorizer(flow_id) |
| 55 |
return globus_sdk.SpecificFlowClient(flow_id, authorizer=authorizer) |
| 56 |
|
| 57 |
|
| 58 |
def run_flow(args): |
| 59 |
flow_client = get_flow_client(args.FLOW_ID) |
| 60 |
print(flow_client.run_flow({})) |
| 61 |
|
| 62 |
|
| 63 |
def main(): |
| 64 |
parser = argparse.ArgumentParser() |
| 65 |
parser.add_argument("FLOW_ID", help="Flow ID to run") |
| 66 |
args = parser.parse_args() |
| 67 |
|
| 68 |
try: |
| 69 |
run_flow(args) |
| 70 |
except globus_sdk.FlowsAPIError as e: |
| 71 |
print(f"API Error: {e.code} {e.message}") |
| 72 |
print(e.text) |
| 73 |
sys.exit(1) |
| 74 |
|
| 75 |
|
| 76 |
if __name__ == "__main__": |
| 77 |
main() |