Esempio n. 1
0
 def say_hello(self):
     # Loads RefreshTokenAuthorizer if login(refresh_tokens=True), otherwise
     # will load an AccessTokenAuthorizer
     ac_authorizer = self.get_authorizers()['auth.globus.org']
     auth_cli = AuthClient(authorizer=ac_authorizer)
     user_info = auth_cli.oauth2_userinfo()
     print('Hello {}! How are you today?'.format(user_info['name']))
Esempio n. 2
0
 def login(self, *args, **kwargs):
     super().login(*args, **kwargs)
     if not config.get_user_info():
         ac_authorizer = self.get_authorizers()['auth.globus.org']
         auth_cli = AuthClient(authorizer=ac_authorizer)
         user_info = auth_cli.oauth2_userinfo()
         config.save_user_info(user_info.data)
Esempio n. 3
0
def identity_to_user(field: str, l: List[Dict[str,
                                              Any]]) -> List[Dict[str, Any]]:
    """
    Given a list of dict entries, this function will attempt to
    """
    # get_identities will fail if there's no data, so short circuit
    if len(l) == 0:
        return l

    # Only do the conversion if the user is already logged in
    authzs = get_authorizers_for_scopes(["openid"], no_login=True)
    authorizer = authzs.get("openid")
    if authorizer is None:
        return l

    # Collect IDs from the List data
    creators: Dict[str, None] = collections.OrderedDict()
    for item in l:
        urn_id = item.get(field, "")
        id = urn_id.split(":")[-1]
        creators[id] = None

    # Get id -> username mapping
    ac = AuthClient(authorizer=authorizer)
    resp = ac.get_identities(ids=creators.keys())
    id_to_user = {i["id"]: i["username"] for i in resp.data["identities"]}

    # Update items in list
    for item in l:
        urn_id = item.get(field, "")
        id = urn_id.split(":")[-1]
        if id in id_to_user:
            item[field] = id_to_user[id]
    return l
Esempio n. 4
0
def get_current_user(
    no_login: bool = False,
    token_store: Union[pathlib.Path, str] = DEFAULT_TOKEN_FILE
) -> Optional[Dict[str, Any]]:
    """
    When `no_login` is set, returns `None` if not logged in.
    """
    # We don't really care which scope from the AUTH_SCOPE list we use here since they
    # all share the same resource server (Auth itself) and therefore an authorizer for
    # any of them grants us access to the same resource server.
    authorizers = get_authorizers_for_scopes(AUTH_SCOPES,
                                             token_store=token_store,
                                             no_login=no_login)
    if not authorizers:
        return None
    auth_client = AuthClient(authorizer=authorizers.get("openid"))
    try:
        user_info = auth_client.oauth2_userinfo()
    except AuthAPIError as e:
        click.echo(
            ("Couldn't get user information from Auth service\n"
             "(If you rescinded your consents in the Auth service, do `session"
             " logout` and try again)\n"
             f"    Error details: {str(e)}"),
            err=True,
        )
        sys.exit(1)
    return user_info.data
 def say_hello(self):
     # Loads RefreshTokenAuthorizer if login(refresh_tokens=True), otherwise
     # will load an AccessTokenAuthorizer
     ac_authorizer = self.get_authorizers()['auth.globus.org']
     auth_cli = AuthClient(authorizer=ac_authorizer)
     user_info = auth_cli.oauth2_userinfo()
     username, domain = user_info['preferred_username'].split('@', 1)
     print('Hello {} (preferred) from {}! How are you today?'.format(
         username, domain))
     for identity in user_info['identity_set']:
         username, domain = identity['username'].split('@', 1)
         print('Hello {} from {}! How are you today?'.format(
             username, domain))
     print()
     print(user_info.text)
Esempio n. 6
0
def get_auth_client():
    """
    Retrieve an authorization client.
    """

    authorizer = get_refresh_authorizer()
    client = AuthClient(authorizer=authorizer, app_name=app_name)

    return client
Esempio n. 7
0
def get_test_access_tokens():
    """
    Uses hard-coded refresh tokens to get an Access Tokens for challengeuser1
    and challengeuser2
    """
    ac = AuthClient()

    form_data_1 = {"refresh_token": TEST_REFRESH_TOKEN_1,
                   "grant_type": 'refresh_token',
                   "client_id": CLIENT_ID}
    access_token_1 = ac.oauth2_token(form_data_1)["access_token"]

    form_data_2 = {"refresh_token": TEST_REFRESH_TOKEN_2,
                   "grant_type": 'refresh_token',
                   "client_id": CLIENT_ID}
    access_token_2 = ac.oauth2_token(form_data_2)["access_token"]

    return access_token_1, access_token_2
Esempio n. 8
0
def get_user_info(access_token):
    """
    Given an Access Token issued by the Globus Auth API introspects the token
    and returns a dict with user_id and username keys.
    Raises a ValueError if the token introspection fails
    """
    auth_client = AuthClient(authorizer=AccessTokenAuthorizer(access_token),
                             client_id=CLIENT_ID)

    try:
        userinfo_res = auth_client.oauth2_userinfo()
    except GlobusError as err:
        raise ValueError("Userinfo could not be gotten from token. "
                         "Failure on: {}".format(err))

    return {
        "user_id": userinfo_res.get("sub"),
        "username": userinfo_res.get("preferred_username")
    }
Esempio n. 9
0
def exchange_code_and_store_config(native_client, auth_code):
    """
    Finishes login flow after code is gotten from command line or local server.
    Exchanges code for tokens and gets user info from auth.
    Stores tokens and user info in config.
    """
    # do a token exchange with the given code
    tkn = native_client.oauth2_exchange_code_for_tokens(auth_code)
    tkn = tkn.by_resource_server

    # extract access tokens from final response
    transfer_at = (tkn['transfer.api.globus.org']['access_token'])
    transfer_at_expires = (
        tkn['transfer.api.globus.org']['expires_at_seconds'])
    transfer_rt = (tkn['transfer.api.globus.org']['refresh_token'])
    auth_at = (tkn['auth.globus.org']['access_token'])
    auth_at_expires = (tkn['auth.globus.org']['expires_at_seconds'])
    auth_rt = (tkn['auth.globus.org']['refresh_token'])

    # get the identity that the tokens were issued to
    auth_client = AuthClient(authorizer=AccessTokenAuthorizer(auth_at))
    res = auth_client.oauth2_userinfo()

    # revoke any existing tokens
    for token_opt in (TRANSFER_RT_OPTNAME, TRANSFER_AT_OPTNAME,
                      AUTH_RT_OPTNAME, AUTH_AT_OPTNAME):
        token = lookup_option(token_opt)
        if token:
            native_client.oauth2_revoke_token(token)

    # write new tokens to config
    write_option(TRANSFER_RT_OPTNAME, transfer_rt)
    write_option(TRANSFER_AT_OPTNAME, transfer_at)
    write_option(TRANSFER_AT_EXPIRES_OPTNAME, transfer_at_expires)
    write_option(AUTH_RT_OPTNAME, auth_rt)
    write_option(AUTH_AT_OPTNAME, auth_at)
    write_option(AUTH_AT_EXPIRES_OPTNAME, auth_at_expires)

    safeprint(_LOGIN_EPILOG.format(res["preferred_username"]))
Esempio n. 10
0
def get_auth_client():
    tokens = get_auth_tokens()
    authorizer = None

    # if there's a refresh token, use it to build the authorizer
    if tokens['refresh_token'] is not None:
        authorizer = RefreshTokenAuthorizer(tokens['refresh_token'],
                                            internal_auth_client(),
                                            tokens['access_token'],
                                            tokens['access_token_expires'],
                                            on_refresh=_update_access_tokens)

    client = AuthClient(authorizer=authorizer, app_name=version.app_name)
    return client
Esempio n. 11
0
def _base_principal_validator(
    principals: List[str], *,
    special_vals: AbstractSet[str] = frozenset()) -> List[str]:
    """
    This validator ensures the principal IDs are valid UUIDs prefixed with valid
    Globus ID beginnings. It will optionally determine if a provided principal
    exists in a set of "special" values.
    """
    auth_beginning = "urn:globus:auth:identity:"

    auth_client: Optional[AuthClient] = None

    valid_principals = []

    invalid_principals = []
    for p in principals:
        if special_vals and p in special_vals or re.match(
                _principal_urn_regex, p):
            valid_principals.append(p)
        else:
            # Try to do a lookup of the identity
            if auth_client is None:
                auth = get_authorizer_for_scope(
                    "urn:globus:auth:scope:auth.globus.org:view_identities")
                auth_client = AuthClient(authorizer=auth)
            auth_resp = auth_client.get_identities(usernames=p)
            identities = auth_resp.data.get("identities", [])
            if len(identities) == 0:
                invalid_principals.append(p)
            for identity in identities:
                valid_principals.append(auth_beginning + identity["id"])

    if invalid_principals:
        raise typer.BadParameter(
            f"Invalid principal value {'; '.join(invalid_principals)}")
    return valid_principals
Esempio n. 12
0
    def __init__(self):
        """Initiate an OAuth2() object.

        Initiate OAuth2 flow with Globus credentaials to obtain access tokens. 
        Refresh the tokens automatically so another login is not required.

        Examples
        --------
        Create an OAuth2 object:
            >>> from archeion.models import OAuth2
            >>> authorizer = OAuth2()

        """
        self.client = NativeAppAuthClient(CLIENT_ID)
        self.client.oauth2_start_flow(refresh_tokens=True)

        logger.info("Opening browser window for Globus Authentication")
        webbrowser.open_new(self.client.oauth2_get_authorize_url())

        get_input = getattr(__builtins__, "raw_input", input)
        auth_code = get_input(
            "Please enter the code you get after login here: "
        ).strip()
        logger.debug("User has input authentication code")
        token_response = self.client.oauth2_exchange_code_for_tokens(auth_code)

        self.access_token = token_response.by_resource_server["auth.globus.org"][
            "access_token"
        ]
        transfer_response = token_response.by_resource_server["transfer.api.globus.org"]
        self.transfer_token = transfer_response["access_token"]
        self.transfer_refresh_token = transfer_response["refresh_token"]
        self.transfer_expiry_seconds = transfer_response["expires_at_seconds"]

        authorizer = RefreshTokenAuthorizer(
            self.transfer_refresh_token,
            self.client,
            access_token=self.transfer_token,
            expires_at=self.transfer_expiry_seconds,
        )
        self.transfer_client = TransferClient(
            AccessTokenAuthorizer(self.transfer_token)
        )
        self.authorisation_client = AuthClient(authorizer=authorizer)
Esempio n. 13
0
    def __init__(self,
                 http_timeout=None,
                 funcx_home=os.path.join('~', '.funcx'),
                 force_login=False,
                 fx_authorizer=None,
                 funcx_service_address='https://api.funcx.org/v1',
                 **kwargs):
        """ Initialize the client

        Parameters
        ----------
        http_timeout: int
        Timeout for any call to service in seconds.
        Default is no timeout

        force_login: bool
        Whether to force a login to get new credentials.

        fx_authorizer:class:`GlobusAuthorizer <globus_sdk.authorizers.base.GlobusAuthorizer>`:
        A custom authorizer instance to communicate with funcX.
        Default: ``None``, will be created.

        funcx_service_address: str
        The address of the funcX web service to communicate with.
        Default: https://api.funcx.org/v1

        Keyword arguments are the same as for BaseClient.
        """
        self.func_table = {}
        self.ep_registration_path = 'register_endpoint_2'
        self.funcx_home = os.path.expanduser(funcx_home)

        if not os.path.exists(self.TOKEN_DIR):
            os.makedirs(self.TOKEN_DIR)

        tokens_filename = os.path.join(self.TOKEN_DIR, self.TOKEN_FILENAME)
        self.native_client = NativeClient(
            client_id=self.CLIENT_ID,
            app_name="FuncX SDK",
            token_storage=JSONTokenStorage(tokens_filename))

        # TODO: if fx_authorizer is given, we still need to get an authorizer for Search
        fx_scope = "https://auth.globus.org/scopes/facd7ccc-c5f4-42aa-916b-a0e270e2c2a9/all"
        search_scope = "urn:globus:auth:scope:search.api.globus.org:all"
        scopes = [fx_scope, search_scope, "openid"]

        search_authorizer = None

        if not fx_authorizer:
            self.native_client.login(
                requested_scopes=scopes,
                no_local_server=kwargs.get("no_local_server", True),
                no_browser=kwargs.get("no_browser", True),
                refresh_tokens=kwargs.get("refresh_tokens", True),
                force=force_login)

            all_authorizers = self.native_client.get_authorizers_by_scope(
                requested_scopes=scopes)
            fx_authorizer = all_authorizers[fx_scope]
            search_authorizer = all_authorizers[search_scope]
            openid_authorizer = all_authorizers["openid"]

        super(FuncXClient, self).__init__("funcX",
                                          environment='funcx',
                                          authorizer=fx_authorizer,
                                          http_timeout=http_timeout,
                                          base_url=funcx_service_address,
                                          **kwargs)
        self.fx_serializer = FuncXSerializer()

        authclient = AuthClient(authorizer=openid_authorizer)
        user_info = authclient.oauth2_userinfo()
        self.searcher = SearchHelper(authorizer=search_authorizer,
                                     owner_uuid=user_info['sub'])
        self.funcx_service_address = funcx_service_address
Esempio n. 14
0
import os

parser = argparse.ArgumentParser(description='kbase share creator')
parser.add_argument('--share-dir', dest='sharedDir',
                help='Directory to create a share on', required=True)
parser.add_argument('--share-name', dest='shareName', 
                help='globusid to share with', required=True)

args = parser.parse_args()
print(args.sharedDir)
print(args.shareName)

if not os.path.exists(args.sharedDir):
    os.makedirs(args.sharedDir)
    os.chmod(args.sharedDir, 0777)

tc = TransferClient() # uses transfer_token from the config file
auth = AuthClient()

identities = auth.get_identities(usernames="*****@*****.**" % args.shareName)
user_identity_id = identities['identities'][0]['id']
try:
   tc.add_endpoint_acl_rule(
       '3aca022a-5e5b-11e6-8309-22000b97daec',
       dict(principal=user_identity_id,
            principal_type='identity', path=args.sharedDir, permissions='rw'),
   )
except TransferAPIError as error:
   if error.code != 'Exists':
       raise
    def __init__(self):
        self.log = logging.getLogger(self.__class__.__name__)
        self.log.info("init - started")

        config = configparser.ConfigParser()
        config.read(str(CONFIG_PATH))

        # To set up a client_id, see https://auth.globus.org/v2/web/developers
        # Current client_id is in Project: MaterialsCommonsProject, App: MaterialsCommonsTest
        client_id = config['sdk']['id']

        auth_tokens = None
        transfer_tokens = None
        tokens = None
        try:
            # if we already have tokens, load and use them
            tokens = self._load_tokens_from_file(TOKEN_FILE_PATH)
        except IOError:
            pass

        if not tokens:
            # if we need to get tokens, start the Native App authentication process
            tokens = self.do_native_app_authentication(client_id, REDIRECT_URI,
                                                       SCOPES)

            try:
                self._save_tokens_to_file(TOKEN_FILE_PATH, tokens)
            except IOError:
                pass

        try:
            auth_tokens = tokens['auth.globus.org']
            transfer_tokens = tokens['transfer.api.globus.org']
        except KeyError as er:
            self.log.error(
                "KeyError on NativeApp tokens: {}\n delete {} and restart".
                format(er, TOKEN_FILE_PATH))

        def refresh_tokens(token_response):
            context = self
            context._update_tokens_file_on_refresh(token_response)

        auth_client = NativeAppAuthClient(client_id=client_id)
        authorizer = RefreshTokenAuthorizer(
            auth_tokens['refresh_token'],
            auth_client,
            access_token=auth_tokens['access_token'],
            expires_at=auth_tokens['expires_at_seconds'],
            on_refresh=refresh_tokens)

        auth_client = AuthClient(client_id=client_id, authorizer=authorizer)

        authorizer = RefreshTokenAuthorizer(
            transfer_tokens['refresh_token'],
            auth_client,
            access_token=transfer_tokens['access_token'],
            expires_at=transfer_tokens['expires_at_seconds'],
            on_refresh=refresh_tokens)

        transfer_client = TransferClient(authorizer=authorizer)

        self._auth_client = auth_client
        self._transfer_client = transfer_client
Esempio n. 16
0
    def __init__(
        self,
        http_timeout=None,
        funcx_home=_FUNCX_HOME,
        force_login=False,
        fx_authorizer=None,
        search_authorizer=None,
        openid_authorizer=None,
        funcx_service_address=None,
        check_endpoint_version=False,
        asynchronous=False,
        loop=None,
        results_ws_uri=None,
        use_offprocess_checker=True,
        environment=None,
        **kwargs,
    ):
        """
        Initialize the client

        Parameters
        ----------
        http_timeout: int
            Timeout for any call to service in seconds.
            Default is no timeout

        force_login: bool
            Whether to force a login to get new credentials.

        fx_authorizer:class:`GlobusAuthorizer \
            <globus_sdk.authorizers.base.GlobusAuthorizer>`:
            A custom authorizer instance to communicate with funcX.
            Default: ``None``, will be created.

        search_authorizer:class:`GlobusAuthorizer \
            <globus_sdk.authorizers.base.GlobusAuthorizer>`:
            A custom authorizer instance to communicate with Globus Search.
            Default: ``None``, will be created.

        openid_authorizer:class:`GlobusAuthorizer \
            <globus_sdk.authorizers.base.GlobusAuthorizer>`:
            A custom authorizer instance to communicate with OpenID.
            Default: ``None``, will be created.

        funcx_service_address: str
            For internal use only. The address of the web service.

        results_ws_uri: str
            For internal use only. The address of the websocket service.

        environment: str
            For internal use only. The name of the environment to use.

        asynchronous: bool
        Should the API use asynchronous interactions with the web service? Currently
        only impacts the run method
        Default: False

        loop: AbstractEventLoop
        If asynchronous mode is requested, then you can provide an optional event loop
        instance. If None, then we will access asyncio.get_event_loop()
        Default: None

        use_offprocess_checker: Bool,
            Use this option to disable the offprocess_checker in the FuncXSerializer
            used by the client.
            Default: True

        Keyword arguments are the same as for BaseClient.

        """
        # resolve URLs if not set
        if funcx_service_address is None:
            funcx_service_address = get_web_service_url(environment)
        if results_ws_uri is None:
            results_ws_uri = get_web_socket_url(environment)

        self.func_table = {}
        self.use_offprocess_checker = use_offprocess_checker
        self.funcx_home = os.path.expanduser(funcx_home)
        self.session_task_group_id = str(uuid.uuid4())

        if not os.path.exists(self.TOKEN_DIR):
            os.makedirs(self.TOKEN_DIR)

        tokens_filename = os.path.join(self.TOKEN_DIR, self.TOKEN_FILENAME)
        self.native_client = NativeClient(
            client_id=self.FUNCX_SDK_CLIENT_ID,
            app_name="FuncX SDK",
            token_storage=JSONTokenStorage(tokens_filename),
        )

        # TODO: if fx_authorizer is given, we still need to get an authorizer for Search
        search_scope = "urn:globus:auth:scope:search.api.globus.org:all"
        scopes = [self.FUNCX_SCOPE, search_scope, "openid"]

        if not fx_authorizer or not search_authorizer or not openid_authorizer:
            self.native_client.login(
                requested_scopes=scopes,
                no_local_server=kwargs.get("no_local_server", True),
                no_browser=kwargs.get("no_browser", True),
                refresh_tokens=kwargs.get("refresh_tokens", True),
                force=force_login,
            )

            all_authorizers = self.native_client.get_authorizers_by_scope(
                requested_scopes=scopes
            )
            fx_authorizer = all_authorizers[self.FUNCX_SCOPE]
            search_authorizer = all_authorizers[search_scope]
            openid_authorizer = all_authorizers["openid"]

        self.web_client = FuncxWebClient(
            base_url=funcx_service_address, authorizer=fx_authorizer
        )
        self.fx_serializer = FuncXSerializer(
            use_offprocess_checker=self.use_offprocess_checker
        )

        authclient = AuthClient(authorizer=openid_authorizer)
        user_info = authclient.oauth2_userinfo()
        self.searcher = SearchHelper(
            authorizer=search_authorizer, owner_uuid=user_info["sub"]
        )
        self.funcx_service_address = funcx_service_address
        self.check_endpoint_version = check_endpoint_version

        self.version_check()

        self.results_ws_uri = results_ws_uri
        self.asynchronous = asynchronous
        if asynchronous:
            self.loop = loop if loop else asyncio.get_event_loop()

            # Start up an asynchronous polling loop in the background
            self.ws_polling_task = WebSocketPollingTask(
                self,
                self.loop,
                init_task_group_id=self.session_task_group_id,
                results_ws_uri=self.results_ws_uri,
            )
        else:
            self.loop = None
Esempio n. 17
0
args = parser.parse_args()
print(args.sharedDir)
print(args.shareName)

if not os.path.exists(args.sharedDir):
    os.makedirs(args.sharedDir)
    os.chmod(args.sharedDir, 0777)

authToken = ''
transferToken = ''
endpointId = ''

tc = TransferClient(
    authorizer=transferToken)  # uses transfer_token from the config file
auth = AuthClient(authorizer=authToken)

identities = auth.get_identities(usernames="*****@*****.**" % args.shareName)
user_identity_id = identities['identities'][0]['id']
try:
    tc.add_endpoint_acl_rule(
        endpointId,
        dict(principal=user_identity_id,
             principal_type='identity',
             path=args.sharedDir,
             permissions='rw'),
    )
    with open('/var/log/globus_shares.log', 'w') as f:
        fwrite('Shared %s with %s' % (args.sharedDir, args.shareName))
except TransferAPIError as error:
    if error.code != 'Exists':
Esempio n. 18
0
"""
from globus_sdk import AuthClient
from fair_research_login import NativeClient

# Register a Native App for a client_id at https://developers.globus.org
client = NativeClient(client_id='7414f0b4-7d05-4bb6-bb00-076fa3f17cf5')

# Automatically saves tokens in ~/.globus-native-apps.cfg
tokens = client.login(
    # Request any scopes you want to use here.
    requested_scopes=['openid', 'profile'],
    # You can turn off the local server if it cannot be used for some reason
    no_local_server=False,
    # You can also turn off automatically opening the Auth URL
    no_browser=False,
    # refresh tokens are fully supported, but optional
    refresh_tokens=True,
)

# Authorizers automatically choose a refresh token authorizer if possible,
# and will automatically save new refreshed tokens when they expire.
ac_authorizer = client.get_authorizers()['auth.globus.org']

# Example client usage:
auth_cli = AuthClient(authorizer=ac_authorizer)
user_info = auth_cli.oauth2_userinfo()
print('Hello {}! How are you today?'.format(user_info['name']))

# Revoke tokens now that we're done
client.logout()