Read credentials from the config file
9423
def read_config(self):
        
        with open(self.config_file) as cfg:
            try:
                self.config.read_file(cfg)
            except AttributeError:
                self.config.readfp(cfg)

        self.client_id = self.config.get('exist', 'client_id')
        self.client_secret = self.config.get('exist', 'client_secret')
        self.access_token = self.config.get('exist', 'access_token')
497283
def _read_config_file(self):
        """"""

        try:
            with open(self.config, 'r') as f:
                config_data = json.load(f)
        except FileNotFoundError:
            config_data = {}

        return config_data
1259753
def show_profiles_from_aws_credentials_file(credentials_files = [aws_credentials_file, aws_config_file]):
    
    profiles = get_profiles_from_aws_credentials_file(credentials_files)
    for profile in set(profiles):
        printInfo(' * %s' % profile)
904761
def _get_credentials():
    '''
    
    '''
    ret = {
        'user': False,
        'passwd': False
    }

    # Loop through opts, grains, and pillar
    # Return the first acceptable configuration found
    for item in ret:
        for struct in [__opts__, __grains__, __pillar__]:
            # Look for the config key
            # Support old-style config format and new
            for config_key in __valid_configs[item]:
                value = salt.utils.data.traverse_dict_and_list(
                    struct,
                    config_key,
                    None)
                if value:
                    ret[item] = value
                    break
    return ret['user'], ret['passwd']
1159377
def read_config(config_file):
    '''

    '''
    config = Storage({  # Default values
        'cache_filename': '~/.aadbook_cache',
        'auth_db_filename': '~/.aadbook_auth.json',
        'cache_expiry_hours': '24'})
    config_file = os.path.expanduser(config_file)
    parser = _get_config(config_file)
    if parser:
        config.get_dict().update(dict(parser.items('DEFAULT', raw=True)))

    # Ensure paths are fully expanded
    config.cache_filename = realpath(expanduser(config.cache_filename))
    config.auth_db_filename = realpath(expanduser(config.auth_db_filename))

    config.auth = Auth(config.auth_db_filename)
    # config.creds = config.store.get()

    # What terminal encoding to use
    config.encoding = ENCODING

    log.debug(config)
    return config
29211
def load_password(self):
        """"""
        # Read the password file, if it exists
        with open(self.password_file, 'r') as file_pwd:
            hashed_password = file_pwd.read()

        return hashed_password
913971
def read_user_config(username, path=settings.LOGIN_FILE):
    
    return _decode_config(load_users(path=path)[username]["full_name"])
1260456
def read_config(filename=None):
    
    if not os.path.exists(filename):
        raise IOError('Impossibile trovare il filename %s' % filename)
    shares = []
    config = ConfigParser()
    config.read(filename)
    for share_items in [config.items(share_title) for share_title in
                        config.sections()]:
        dict_share = {}
        for key, value in share_items:
            if key == 'hostname' and '@' in value:
                hostname, credentials = (item[::-1] for item
                                         in value[::-1].split('@', 1))
                dict_share.update({key: hostname})
                credentials = tuple(cred.lstrip('"').rstrip('"')
                                    for cred in credentials.split(':', 1))
                dict_share.update({'username': credentials[0]})
                if len(credentials) > 1:
                    dict_share.update({'password': credentials[1]})
                continue
            dict_share.update({key: value})
        shares.append(dict_share)
    return shares
764491
function readConfig() {
  const patten = `${process.cwd()}/config/*.json`
  return glob.sync(patten).reduce((acc, curr) => {
    var ctx = !env ? require(curr) : require(curr)[env]
    return Object.assign({}, acc, ctx)
  }, {})
}
580739
def read_config_file(filename)
      contents = ""
      File.open(filename, "r") { |f| contents = f.read() } if File.exists?(filename)
      contents
    end
1237662
function readConfig() {
  let options = {}
  let cFile = ''

  if (program.config) {
    cFile = path.resolve(cwd, program.config)
    if (fs.existsSync(cFile)) {
      Object.assign(config, require(cFile))
    } else {
      console.warn(`Cannot find configuration file ${program.config}`)
      process.exit()
    }
  } else {
    cFile = path.resolve(cwd, 'deploy.js')
  }

  if (fs.existsSync(cFile)) {
    options = require(cFile)
  }

  ;['server', 'ignore'].forEach(function(name) {
    if (typeof program[name] !== 'undefined') {
      options[name] = program[name]
    }
  })

  if (program.args[0]) {
    options.workspace = path.resolve(cwd, program.args[0])
  }

  if (program.args[1]) {
    options.deployTo = program.args[1]
  }

  return options
}
52899
def get_mysql_credentials(cfg_file):
    """"""

    try:
        parser = ConfigParser.ConfigParser()
        cfg_fp = open(cfg_file)
        parser.readfp(cfg_fp)
        cfg_fp.close()
    except ConfigParser.NoOptionError:
        cfg_fp.close()
        print('Failed to find mysql connections credentials.')
        sys.exit(1)
    except IOError:
        print('ERROR: Cannot open %s.', cfg_file)
        sys.exit(1)

    value = parser.get('dfa_mysql', 'connection')

    try:
        # Find location of pattern in connection parameter as shown below:
        # http://username:password@host/databasename?characterset=encoding'
        sobj = re.search(r"(://).*(@).*(/).*(\?)", value)

        # The list parameter contains:
        # indices[0], is the index of '://'
        # indices[1], is the index of '@'
        # indices[2], is the index of '/'
        # indices[3], is the index of '?'
        indices = [sobj.start(1), sobj.start(2), sobj.start(3), sobj.start(4)]

        # Get the credentials
        cred = value[indices[0] + 3:indices[1]].split(':')

        # Get the host name
        host = value[indices[1] + 1:indices[2]]

        # Get the database name
        db_name = value[indices[2] + 1:indices[3]]

        # Get the character encoding
        charset = value[indices[3] + 1:].split('=')[1]

        return cred[0], cred[1], host, db_name, charset
    except (ValueError, IndexError, AttributeError):
        print('Failed to find mysql connections credentials.')
        sys.exit(1)
952133
def get(profile='default')
      raise 'Config File does not exist' unless File.exists?(@file)

      @credentials = parse if @credentials.nil?
      raise 'The profile is not specified in the config file' unless @credentials.has_key?(profile)

      @credentials[profile]
    end
235862
def _get_credentials(self, request):
        
        authorization = request.headers.get('Authorization')
        if not authorization:
            return None
        try:
            authmeth, authbytes = authorization.split(' ', 1)
        except ValueError:  # not enough values to unpack
            return None
        if authmeth.lower() != 'apikey':
            return None

        if six.PY2 or isinstance(authbytes, bytes):
            try:
                auth = authbytes.decode('utf-8')
            except UnicodeDecodeError:
                auth = authbytes.decode('latin-1')
        else:
            auth = authbytes

        try:
            username, api_key = auth.split(':', 1)
        except ValueError:  # not enough values to unpack
            return None
        return username, api_key
908563
def credentials_loader(self, in_credentials: str = "client_secrets.json") -> dict:
        
        accepted_extensions = (".ini", ".json")
        # checks
        if not path.isfile(in_credentials):
            raise IOError("Credentials file doesn't exist: {}".format(in_credentials))
        else:
            in_credentials = path.normpath(in_credentials)
        if path.splitext(in_credentials)[1] not in accepted_extensions:
            raise ValueError(
                "Extension of credentials file must be one of {}".format(
                    accepted_extensions
                )
            )
        else:
            kind = path.splitext(in_credentials)[1]
        # load, check and set
        if kind == ".json":
            with open(in_credentials, "r") as f:
                in_auth = json.loads(f.read())
            # check structure
            heads = ("installed", "web")
            if not set(in_auth).intersection(set(heads)):
                raise ValueError(
                    "Input JSON structure is not as expected."
                    " First key must be one of: {}".format(heads)
                )
            # set
            if "web" in in_auth:
                # json structure for group application
                auth_settings = in_auth.get("web")
                out_auth = {
                    "auth_mode": "group",
                    "client_id": auth_settings.get("client_id"),
                    "client_secret": auth_settings.get("client_secret"),
                    # if not specified, must be a former file then set classic scope
                    "scopes": auth_settings.get("scopes", ["resources:read"]),
                    "uri_auth": auth_settings.get("auth_uri"),
                    "uri_token": auth_settings.get("token_uri"),
                    "uri_base": self.get_url_base_from_url_token(
                        auth_settings.get("token_uri")
                    ),
                    "uri_redirect": None,
                }
            else:
                # assuming in_auth == 'installed'
                auth_settings = in_auth.get("installed")
                out_auth = {
                    "auth_mode": "user",
                    "client_id": auth_settings.get("client_id"),
                    "client_secret": auth_settings.get("client_secret"),
                    # if not specified, must be a former file then set classic scope
                    "scopes": auth_settings.get("scopes", ["resources:read"]),
                    "uri_auth": auth_settings.get("auth_uri"),
                    "uri_token": auth_settings.get("token_uri"),
                    "uri_base": self.get_url_base_from_url_token(
                        auth_settings.get("token_uri")
                    ),
                    "uri_redirect": auth_settings.get("redirect_uris", None),
                }
        else:
            # assuming file is an .ini
            ini_parser = ConfigParser()
            ini_parser.read(in_credentials)
            # check structure
            if "auth" in ini_parser._sections:
                auth_settings = ini_parser["auth"]
            else:
                raise ValueError(
                    "Input INI structure is not as expected."
                    " Section of credentials must be named: auth"
                )
            # set
            out_auth = {
                "auth_mode": auth_settings.get("CLIENT_TYPE"),
                "client_id": auth_settings.get("CLIENT_ID"),
                "client_secret": auth_settings.get("CLIENT_SECRET"),
                "uri_auth": auth_settings.get("URI_AUTH"),
                "uri_token": auth_settings.get("URI_TOKEN"),
                "uri_base": self.get_url_base_from_url_token(
                    auth_settings.get("URI_TOKEN")
                ),
                "uri_redirect": auth_settings.get("URI_REDIRECT"),
            }
        # method ending
        return out_auth
513841
def read_config(self, config_file):
        
        cfg = ConfigParser.SafeConfigParser()
        try:
            cfg.read(config_file)
        except ConfigParser.MissingSectionHeaderError as e:
            # The file exists, but doesn't have the correct format.
            raise exc.InvalidConfigurationFile(e)

        def safe_get(section, option, default=None):
            try:
                return cfg.get(section, option)
            except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
                return default

        # A common mistake is including credentials in the config file. If any
        # values are found, issue a warning so that the developer can correct
        # this problem.
        creds_found = False
        for section in cfg.sections():
            if section == "settings":
                section_name = "default"
                self._default_set = True
            else:
                section_name = section
            # Check for included credentials
            for key in ("username", "password", "api_key"):
                if creds_found:
                    break
                if safe_get(section, key):
                    creds_found = True
            dct = self._settings[section_name] = {}
            dct["region"] = safe_get(section, "region", default_region)
            ityp = safe_get(section, "identity_type")
            if ityp:
                dct["identity_type"] = _id_type(ityp)
                dct["identity_class"] = _import_identity(ityp)
            # Handle both the old and new names for this setting.
            debug = safe_get(section, "debug")
            if debug is None:
                debug = safe_get(section, "http_debug", "False")
            dct["http_debug"] = debug == "True"
            verify_ssl = safe_get(section, "verify_ssl", "True")
            dct["verify_ssl"] = verify_ssl == "True"
            dct["keyring_username"] = safe_get(section, "keyring_username")
            dct["encoding"] = safe_get(section, "encoding", default_encoding)
            dct["auth_endpoint"] = safe_get(section, "auth_endpoint")
            dct["tenant_name"] = safe_get(section, "tenant_name")
            dct["tenant_id"] = safe_get(section, "tenant_id")
            use_servicenet = safe_get(section, "use_servicenet", "False")
            dct["use_servicenet"] = use_servicenet == "True"
            app_agent = safe_get(section, "custom_user_agent")
            if app_agent:
                # Customize the user-agent string with the app name.
                dct["user_agent"] = "%s %s" % (app_agent, USER_AGENT)
            else:
                dct["user_agent"] = USER_AGENT

            # If this is the first section, make it the default
            if not self._default_set:
                self._settings["default"] = self._settings[section]
                self._default_set = True
        if creds_found:
            warnings.warn("Login credentials were detected in your .pyrax.cfg "
                    "file. These have been ignored, but you should remove "
                    "them and either place them in a credential file, or "
                    "consider using another means of authentication. More "
                    "information on the use of credential files can be found "
                    "in the 'docs/getting_started.md' document.")
348992
def read(config_file, configspec, server_mode=False, default_section='default_settings', list_values=True):
    '''
    
    '''
#    configspec = ConfigObj(path.join(path.abspath(path.dirname(__file__)), configspec),
#                           encoding='UTF8',
#                           interpolation='Template',
#                           list_values=False,
#                           _inspec=True)
    config = ConfigObj(config_file,
                       configspec=path.join(path.abspath(path.dirname(__file__)),
                                            configspec),
                                            list_values=list_values)
    validation = config.validate(validate.Validator(), preserve_errors=True)

    if validation == True:
        config = dict(config)
        for section in config:
            if section != default_section:
                if server_mode: # When it's a servers config file, retrieve the correct fqdn
                    config[section]['availability'] = True
                    if config[section]['custom_fqdn'] == None:
                        config[section]['custom_fqdn'] = socket.getfqdn()
                for option in config[section]:  # retrieve default configuration for missing values
                    if config[section][option] == None:
                        config[section][option] = config[default_section][option]

        del(config[default_section])

        return config
    else:
        raise ConfiguratorException(config_file, validation)