コード例 #1
0
def get_native_app_authorizer(client_id):
    tokens = None
    client = NativeClient(client_id=client_id, app_name=APP_NAME)
    try:
        # if we already have tokens, load and use them
        tokens = client.load_tokens(requested_scopes=SCOPES)
    except:
        pass

    if not tokens:
        tokens = client.login(requested_scopes=SCOPES, refresh_tokens=True)
        try:
            client.save_tokens(tokens)
        except:
            pass

    transfer_tokens = tokens['transfer.api.globus.org']

    auth_client = globus_sdk.NativeAppAuthClient(client_id=client_id)

    return globus_sdk.RefreshTokenAuthorizer(
        transfer_tokens['refresh_token'],
        auth_client,
        access_token=transfer_tokens['access_token'],
        expires_at=transfer_tokens['expires_at_seconds'])
コード例 #2
0
def spawn_tokens(client_id=CLIENT_ID, req_scopes=SCOPES, name=APP_NAME):
    """
    Checks if Globus tokens already exists and spawns them if they don't.
    Returns instance of 'NativeClient'.
    """

    tokens = os.getenv('GLOBUS_DATA')
    # try to load tokens from local file (native app config)
    client = NativeClient(client_id=client_id, app_name=name)

    # try:
    #     tokens = client.load_tokens(requested_scopes=req_scopes)
    # except:
    #     pass

    if not tokens:
        # if no tokens, need to start Native App authentication process to get tokens
        tokens = client.login(requested_scopes=req_scopes, refresh_tokens=True)

        try:
            # save the tokens
            client.save_tokens(tokens)

            # create environment variable
            os.environ['GLOBUS_DATA'] = json.dumps(tokens,
                                                   indent=4,
                                                   sort_keys=True)
        except:
            pass
コード例 #3
0
def main():
    tokens = None
    client = NativeClient(client_id=CLIENT_ID, app_name=APP_NAME)
    try:
        # if we already have tokens, load and use them
        tokens = client.load_tokens(requested_scope=SCOPES)
    except:
        pass

    if not tokens:
        # if we need to get tokens, start the Native App authentication process
        # need to specify that we want refresh tokens
        tokens = client.login(requested_scopes=SCOPES, refresh_tokens=True)
        try:
            client.save_tokens(tokens)
        except:
            pass

    transfer = setup_transfer_client(tokens['transfer.api.globus.org'])

    try:
        task_data = load_data_from_file(DATA_FILE)['task']
        task = transfer.get_task(task_data['task_id'])
        if task['status'] not in PREVIOUS_TASK_RUN_CASES:
            print('The last transfer status is {}, skipping run...'.format(
                task['status']))
            sys.exit(1)
    except KeyError:
        # Ignore if there is no previous task
        pass

    check_endpoint_path(transfer, SOURCE_ENDPOINT, SOURCE_PATH)
    if CREATE_DESTINATION_FOLDER:
        create_destination_directory(transfer, DESTINATION_ENDPOINT,
                                     DESTINATION_PATH)
    else:
        check_endpoint_path(transfer, DESTINATION_ENDPOINT, DESTINATION_PATH)

    tdata = TransferData(transfer,
                         SOURCE_ENDPOINT,
                         DESTINATION_ENDPOINT,
                         label=TRANSFER_LABEL,
                         sync_level="checksum")
    tdata.add_item(SOURCE_PATH, DESTINATION_PATH, recursive=True)

    task = transfer.submit_transfer(tdata)
    save_data_to_file(DATA_FILE, 'task', task.data)
    print('Transfer has been started from\n  {}:{}\nto\n  {}:{}'.format(
        SOURCE_ENDPOINT, SOURCE_PATH, DESTINATION_ENDPOINT, DESTINATION_PATH))
    url_string = 'https://globus.org/app/transfer?' + \
        six.moves.urllib.parse.urlencode({
            'origin_id': SOURCE_ENDPOINT,
            'origin_path': SOURCE_PATH,
            'destination_id': DESTINATION_ENDPOINT,
            'destination_path': DESTINATION_PATH
        })
    print('Visit the link below to see the changes:\n{}'.format(url_string))
コード例 #4
0
def test_json_token_storage(mock_tokens, mock_revoke, monkeypatch):
    cli = NativeClient(client_id=str(uuid.uuid4()),
                       token_storage=JSONTokenStorage())
    # Mock actual call to open(). Catch the data 'written' and use it in the
    # load function. This is a cheap and easy (and hacky) way to test that the
    # stuff we get read was the same as the stuff written in.
    monkeypatch.setattr(os.path, 'exists', lambda x: True)
    mo = mock_open()
    with patch(BUILTIN_OPEN, mo):
        cli.save_tokens(mock_tokens)
        written = ''.join([c[1][0] for c in mo().write.mock_calls])
    with patch(BUILTIN_OPEN, mock_open(read_data=written)):
        tokens = cli.load_tokens()
        assert tokens == MOCK_TOKEN_SET
        mock_remove = Mock()
        with patch('os.remove', mock_remove):
            cli.logout()
            assert mock_remove.called
コード例 #5
0
        # Alternatively, with no local server, we simply wait for a code. The
        # more likely case there is the user enters garbage which results in an
        # invalid grant.
        no_local_server=True,
    )
    print('Login Successful')
except LocalServerError as lse:
    # There was some problem with the local server, likely the user clicked
    # "Decline" on the consents page
    print('Login Unsuccessful: {}'.format(str(lse)))
except globus_sdk.exc.AuthAPIError as aapie:
    # Something went wrong with getting the auth code
    print('Login Unsuccessful: {}'.format(aapie))
"""
Token Expiration
"""

# Let's start off by manually expiring some tokens
client.save_tokens({
    'auth.globus.org': {
        'scope': 'openid profile',
        'access_token': '<fake_access_token>',
        'expires_at_seconds': 0,
        'resource_server': 'auth.globus.org',
    }
})
try:
    client.load_tokens(requested_scopes=['openid', 'profile'])
except TokensExpired as te:
    print('Load Failure, tokens expired for: {}'.format(te))
コード例 #6
0
import json
from fair_research_login import NativeClient

CLIENT_ID = 'e54de045-d346-42ef-9fbc-5d466f4a00c6'
APP_NAME = 'My App'
SCOPES = 'openid email profile urn:globus:auth:scope:transfer.api.globus.org:all urn:globus:auth:scope:search.api.globus.org:all'
CONFIG_FILE = 'tokens-data.json'

tokens = None
# try to load tokens from local file (native app config)
client = NativeClient(client_id=CLIENT_ID, app_name=APP_NAME)
try:
    tokens = client.load_tokens(requested_scopes=SCOPES)
except:
    pass

if not tokens:
    # if no tokens, need to start Native App authentication process to get tokens
    tokens = client.login(requested_scopes=SCOPES, refresh_tokens=False)

    try:
        # save the tokens
        client.save_tokens(tokens)

        # create environment variable
        os.environ['GLOBUS_DATA'] = json.dumps(tokens,
                                               indent=4,
                                               sort_keys=True)
    except:
        pass