Gets the credentials and project ID from the Cloud SDK.
964252
def _get_gcloud_sdk_credentials():
    """"""
    from google.auth import _cloud_sdk

    # Check if application default credentials exist.
    credentials_filename = (
        _cloud_sdk.get_application_default_credentials_path())

    if not os.path.isfile(credentials_filename):
        return None, None

    credentials, project_id = _load_credentials_from_file(
        credentials_filename)

    if not project_id:
        project_id = _cloud_sdk.get_project_id()

    return credentials, project_id
709437
def getUser(cls, cloud):
        
        try:
            config = d = ConfigDict("cloudmesh.yaml")

            d = ConfigDict("cloudmesh.yaml")

            #
            # bug: cloud is none when adding a group
            #

            config = d["cloudmesh"]["clouds"][cloud]
            credentials = config["credentials"]
            cloud_type = config["cm_type"]

            if cloud_type == "openstack":
                return credentials["OS_USERNAME"]
            else:
                raise ValueError("getUser for this cloud type not yet "
                                 "supported: {}".format(cloud))
        except Exception as ex:
            Console.error("problem getting user")
1052027
def _determine_auth(**kwargs):
    '''
    
    '''
    if 'profile' in kwargs:
        azure_credentials = __salt__['config.option'](kwargs['profile'])
        kwargs.update(azure_credentials)

    service_principal_creds_kwargs = ['client_id', 'secret', 'tenant']
    user_pass_creds_kwargs = ['username', 'password']

    try:
        if kwargs.get('cloud_environment') and kwargs.get('cloud_environment').startswith('http'):
            cloud_env = get_cloud_from_metadata_endpoint(kwargs['cloud_environment'])
        else:
            cloud_env_module = importlib.import_module('msrestazure.azure_cloud')
            cloud_env = getattr(cloud_env_module, kwargs.get('cloud_environment', 'AZURE_PUBLIC_CLOUD'))
    except (AttributeError, ImportError, MetadataEndpointError):
        raise sys.exit('The Azure cloud environment {0} is not available.'.format(kwargs['cloud_environment']))

    if set(service_principal_creds_kwargs).issubset(kwargs):
        if not (kwargs['client_id'] and kwargs['secret'] and kwargs['tenant']):
            raise SaltInvocationError(
                'The client_id, secret, and tenant parameters must all be '
                'populated if using service principals.'
            )
        else:
            credentials = ServicePrincipalCredentials(kwargs['client_id'],
                                                      kwargs['secret'],
                                                      tenant=kwargs['tenant'],
                                                      cloud_environment=cloud_env)
    elif set(user_pass_creds_kwargs).issubset(kwargs):
        if not (kwargs['username'] and kwargs['password']):
            raise SaltInvocationError(
                'The username and password parameters must both be '
                'populated if using username/password authentication.'
            )
        else:
            credentials = UserPassCredentials(kwargs['username'],
                                              kwargs['password'],
                                              cloud_environment=cloud_env)
    elif 'subscription_id' in kwargs:
        try:
            from msrestazure.azure_active_directory import (
                MSIAuthentication
            )
            credentials = MSIAuthentication(cloud_environment=cloud_env)
        except ImportError:
            raise SaltSystemExit(msg='MSI authentication support not availabe (requires msrestazure >= 0.4.14)')

    else:
        raise SaltInvocationError(
            'Unable to determine credentials. '
            'A subscription_id with username and password, '
            'or client_id, secret, and tenant or a profile with the '
            'required parameters populated'
        )

    if 'subscription_id' not in kwargs:
        raise SaltInvocationError(
            'A subscription_id must be specified'
        )

    subscription_id = salt.utils.stringutils.to_str(kwargs['subscription_id'])

    return credentials, subscription_id, cloud_env
479487
@Override
    public AWSCredentials getCredentials() {
        if (SDKGlobalConfiguration.isEc2MetadataDisabled()) {
            throw new AmazonClientException("AWS_EC2_METADATA_DISABLED is set to true, not loading credentials from EC2 Instance "
                                         + "Metadata service");
        }
        AWSCredentials creds = credentialsFetcher.getCredentials();
        shouldRefresh = true;
        return creds;
    }
1189359
public String getProjectId() {
    if (project != null) {
      if (projectId != null) {
        throw new IllegalArgumentException(
            "Configuring <project> and <projectId> is not allowed, please use only <projectId>");
      }
      getLog()
          .warn(
              "Configuring <project> is deprecated,"
                  + " use <projectId> to set your Google Cloud ProjectId");
      return project;
    }
    return projectId;
  }
79119
def get_default_project_id():
  
  # Try getting default project id from gcloud. If it fails try config.json.
  try:
    proc = subprocess.Popen(['gcloud', 'config', 'list', '--format', 'value(core.project)'],
                            stdout=subprocess.PIPE)
    stdout, _ = proc.communicate()
    value = stdout.strip()
    if proc.poll() == 0 and value:
      if isinstance(value, six.string_types):
        return value
      else:
        # Hope it's a utf-8 string encoded in bytes. Otherwise an exception will
        # be thrown and config.json will be checked.
        return value.decode()
  except:
    pass

  config_file = os.path.join(get_config_dir(), 'config.json')
  if os.path.exists(config_file):
    with open(config_file) as f:
      config = json.loads(f.read())
      if 'project_id' in config and config['project_id']:
        return str(config['project_id'])

  if os.getenv('PROJECT_ID') is not None:
    return os.getenv('PROJECT_ID')
  return None
252391
def _credentials(self):
        

        if self.aws_account_id and self.aws_arn_role_name:
            return 'aws_iam_role=arn:aws:iam::{id}:role/{role}'.format(
                id=self.aws_account_id,
                role=self.aws_arn_role_name
            )
        elif self.aws_access_key_id and self.aws_secret_access_key:
            return 'aws_access_key_id={key};aws_secret_access_key={secret}{opt}'.format(
                key=self.aws_access_key_id,
                secret=self.aws_secret_access_key,
                opt=';token={}'.format(self.aws_session_token) if self.aws_session_token else ''
            )
        else:
            raise NotImplementedError("Missing Credentials. "
                                      "Ensure one of the pairs of auth args below are set "
                                      "in a configuration file, environment variables or by "
                                      "being overridden in the task: "
                                      "'aws_access_key_id' AND 'aws_secret_access_key' OR "
                                      "'aws_account_id' AND 'aws_arn_role_name'")
446065
def _build_credentials_tuple(mech, source, user, passwd, extra):
    
    user = _unicode(user) if user is not None else None
    password = passwd if passwd is None else _unicode(passwd)
    if mech == 'GSSAPI':
        properties = extra.get('authmechanismproperties', {})
        service_name = properties.get('SERVICE_NAME', 'mongodb')
        canonicalize = properties.get('CANONICALIZE_HOST_NAME', False)
        service_realm = properties.get('SERVICE_REALM')
        props = GSSAPIProperties(service_name=service_name,
                                 canonicalize_host_name=canonicalize,
                                 service_realm=service_realm)
        # Source is always $external.
        return MongoCredential(mech, '$external', user, password, props)
    elif mech == 'MONGODB-X509':
        # user can be None.
        return MongoCredential(mech, '$external', user, None, None)
    else:
        if passwd is None:
            raise ConfigurationError("A password is required.")
        return MongoCredential(mech, source, user, password, None)
1142010
def from_credentials(credentials):
        
        return API(username=credentials.username, password=credentials.password,
                   database=credentials.database, session_id=credentials.session_id,
                   server=credentials.server)
638940
private String getProjectIdForProjectName(String projectName) throws SDKException {
    String projectId =
        this.getProjectAgent()
            .findAll()
            .stream()
            .filter(p -> p.getName().equals(projectName))
            .findFirst()
            .orElseThrow(
                () ->
                    new SDKException(
                        "Did not find a Project named " + projectName,
                        null,
                        "Did not find a Project named " + projectName))
            .getId();
    this.projectAgent = null;
    return projectId;
  }
648849
def find_credentials():
    '''
    
    '''

    # if the username and password were already found don't go through the
    # connection process again
    if 'username' in DETAILS and 'password' in DETAILS:
        return DETAILS['username'], DETAILS['password']

    passwords = __pillar__['proxy']['passwords']
    for password in passwords:
        DETAILS['password'] = password
        if not __salt__['vsphere.test_vcenter_connection']():
            # We are unable to authenticate
            continue
        # If we have data returned from above, we've successfully authenticated.
        return DETAILS['username'], password
    # We've reached the end of the list without successfully authenticating.
    raise excs.VMwareConnectionError('Cannot complete login due to '
                                     'incorrect credentials.')
311212
def path(project, credentials):
        """"""
        user, oauth_access_token = parsecredentials(credentials) #pylint: disable=unused-variable
        return settings.ROOT + "projects/" + user + '/' + project + "/"
86280
def get_project_id():
    
    if os.name == 'nt':
        command = _CLOUD_SDK_WINDOWS_COMMAND
    else:
        command = _CLOUD_SDK_POSIX_COMMAND

    try:
        output = subprocess.check_output(
            (command,) + _CLOUD_SDK_CONFIG_COMMAND,
            stderr=subprocess.STDOUT)
    except (subprocess.CalledProcessError, OSError, IOError):
        return None

    try:
        configuration = json.loads(output.decode('utf-8'))
    except ValueError:
        return None

    try:
        return configuration['configuration']['properties']['core']['project']
    except KeyError:
        return None
366546
def get_user_data_configuration():
    
    from cloud_inquisitor import get_local_aws_session, app_config

    kms_region = app_config.kms_region
    session = get_local_aws_session()

    if session.get_credentials().method == 'iam-role':
        kms = session.client('kms', region_name=kms_region)
    else:
        sts = session.client('sts')
        audit_role = sts.assume_role(RoleArn=app_config.aws_api.instance_role_arn, RoleSessionName='cloud_inquisitor')
        kms = boto3.session.Session(
            audit_role['Credentials']['AccessKeyId'],
            audit_role['Credentials']['SecretAccessKey'],
            audit_role['Credentials']['SessionToken'],
        ).client('kms', region_name=kms_region)

    user_data_url = app_config.user_data_url
    res = requests.get(user_data_url)

    if res.status_code == 200:
        data = kms.decrypt(CiphertextBlob=b64decode(res.content))
        kms_config = json.loads(zlib.decompress(data['Plaintext']).decode('utf-8'))

        app_config.database_uri = kms_config['db_uri']
    else:
        raise RuntimeError('Failed loading user-data, cannot continue: {}: {}'.format(res.status_code, res.content))
388823
def GetCredentials(package_name, scopes, client_id, client_secret, user_agent,
                   credentials_filename=None,
                   api_key=None,  # pylint: disable=unused-argument
                   client=None,  # pylint: disable=unused-argument
                   oauth2client_args=None,
                   **kwds):
    """"""
    scopes = util.NormalizeScopes(scopes)
    client_info = {
        'client_id': client_id,
        'client_secret': client_secret,
        'scope': ' '.join(sorted(scopes)),
        'user_agent': user_agent or '%s-generated/0.1' % package_name,
    }
    for method in _CREDENTIALS_METHODS:
        credentials = method(client_info, **kwds)
        if credentials is not None:
            return credentials
    credentials_filename = credentials_filename or os.path.expanduser(
        '~/.apitools.token')
    credentials = CredentialsFromFile(credentials_filename, client_info,
                                      oauth2client_args=oauth2client_args)
    if credentials is not None:
        return credentials
    raise exceptions.CredentialsError('Could not create valid credentials')
945796
def get_credentials_arn(self):
        
        role = self.iam.Role(self.role_name)
        self.credentials_arn = role.arn
        return role, self.credentials_arn
629437
def get(project, credentials=None):
        """"""
        user, oauth_access_token = parsecredentials(credentials)
        if not Project.exists(project, user):
            return withheaders(flask.make_response("Project " + project + " was not found for user " + user,404) ,headers={'allow_origin': settings.ALLOW_ORIGIN})#404
        else:
            #if user and not Project.access(project, user) and not user in settings.ADMINS:
            #    return flask.make_response("Access denied to project " +  project + " for user " + user, 401) #401
            datafile = os.path.join(Project.path(project,credentials),'clam.xml')
            statuscode, statusmsg, statuslog, completion = Project.status(project, user) #pylint: disable=unused-variable
            if statuscode == clam.common.status.DONE and os.path.exists(datafile):
                f = io.open(datafile,'r',encoding='utf-8')
                xmldata = f.read(os.path.getsize(datafile))
                f.close()
                data = clam.common.data.CLAMData(xmldata, None,False, Project.path(project,credentials), loadmetadata=False)
                return Project.response(user, project, settings.PARAMETERS,"",False,oauth_access_token,','.join([str(x) for x in data.program.matchedprofiles]) if data.program else "", data.program) #200
            else:
                #HTTP request parameters may be used to pre-set global parameters when starting a project (issue #66)
                for parametergroup, parameterlist in settings.PARAMETERS: #pylint: disable=unused-variable
                    for parameter in parameterlist:
                        value = parameter.valuefrompostdata(flask.request.values)
                        if value is not None:
                            parameter.set(value)
                return Project.response(user, project, settings.PARAMETERS,"",False,oauth_access_token)