Read credentials from a file.
762635
def CredentialsFromFile(path, client_info, oauth2client_args=None):
    """"""
    user_agent = client_info['user_agent']
    scope_key = client_info['scope']
    if not isinstance(scope_key, six.string_types):
        scope_key = ':'.join(scope_key)
    storage_key = client_info['client_id'] + user_agent + scope_key

    if _NEW_FILESTORE:
        credential_store = multiprocess_file_storage.MultiprocessFileStorage(
            path, storage_key)
    else:
        credential_store = multistore_file.get_credential_storage_custom_string_key(  # noqa
            path, storage_key)
    if hasattr(FLAGS, 'auth_local_webserver'):
        FLAGS.auth_local_webserver = False
    credentials = credential_store.get()
    if credentials is None or credentials.invalid:
        print('Generating new OAuth credentials ...')
        for _ in range(20):
            # If authorization fails, we want to retry, rather than let this
            # cascade up and get caught elsewhere. If users want out of the
            # retry loop, they can ^C.
            try:
                flow = oauth2client.client.OAuth2WebServerFlow(**client_info)
                flags = _GetRunFlowFlags(args=oauth2client_args)
                credentials = tools.run_flow(flow, credential_store, flags)
                break
            except (oauth2client.client.FlowExchangeError, SystemExit) as e:
                # Here SystemExit is "no credential at all", and the
                # FlowExchangeError is "invalid" -- usually because
                # you reused a token.
                print('Invalid authorization: %s' % (e,))
            except httplib2.HttpLib2Error as e:
                print('Communication error: %s' % (e,))
                raise exceptions.CredentialsError(
                    'Communication error creating credentials: %s' % e)
    return credentials
1065953
def checkKey(self, credentials):
        
        filename = self._keyfile
        if not os.path.exists(filename):
            return 0
        lines = open(filename).xreadlines()
        for l in lines:
            l2 = l.split()
            if len(l2) < 2:
                continue
            try:
                if base64.decodestring(l2[1]) == credentials.blob:
                    return 1
            except binascii.Error:
                continue
        return 0
1052045
def from_file(cls, path, encoding, dialect, fields, converters, field_index):
        """"""

        return cls(open(path, 'r', encoding=encoding), dialect, fields, converters, field_index)
743773
def _from_dict(cls, _dict):
        """"""
        args = {}
        if 'credentials' in _dict:
            args['credentials'] = [
                Credentials._from_dict(x) for x in (_dict.get('credentials'))
            ]
        return cls(**args)
1268535
def _authenticate(secrets_file):
    
    flow = oauthclient.flow_from_clientsecrets(
        secrets_file,
        scope=OAUTH_SCOPE,
        message=('Failed to initialized OAuth 2.0 flow with secrets '
                 'file: %s' % secrets_file))
    storage = oauthfile.Storage(OAUTH_CREDENTIALS_FILE)
    credentials = storage.get()
    if credentials is None or credentials.invalid:
        credentials = oauthtools.run_flow(flow, storage, oauthtools.argparser.parse_args(args=[]))
    http = httplib2.Http()
    return credentials.authorize(http)
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
1127427
def get(self):
        """"""
        args = self.get_parser.parse_args()
        cred = self.manager.get_credential(args)
        if cred is None:
            return abort(http_client.BAD_REQUEST,
                         message='Unable to decrypt credential value.')
        else:
            return cred
1209607
def read_lines_from_file(cls_name, filename):
  """"""
  with tf.io.gfile.GFile(filename, "rb") as f:
    lines = [tf.compat.as_text(line)[:-1] for line in f]
  header_line = "%s%s" % (_HEADER_PREFIX, cls_name)
  if lines[0] != header_line:
    raise ValueError("File {fname} does not seem to have been created from "
                     "{name}.save_to_file.".format(
                         fname=filename, name=cls_name))
  metadata_dict = json.loads(lines[1][len(_METADATA_PREFIX):])
  return lines[2:], metadata_dict
761462
def check_credentials(self, username, password):
        
        return password is not None and self.credentials.get(username, None) == password
305536
def read_config_file(f):
    """"""

    if isinstance(f, basestring):
        f = os.path.expanduser(f)

    try:
        config = ConfigObj(f, interpolation=False, encoding='utf8')
    except ConfigObjError as e:
        log(LOGGER, logging.ERROR, "Unable to parse line {0} of config file "
            "'{1}'.".format(e.line_number, f))
        log(LOGGER, logging.ERROR, "Using successfully parsed config values.")
        return e.config
    except (IOError, OSError) as e:
        log(LOGGER, logging.WARNING, "You don't have permission to read "
            "config file '{0}'.".format(e.filename))
        return None

    return config
250485
def get_drive_api_from_file(path):
    
    f = open(path)
    credentials = client.OAuth2Credentials.from_json(f.read())
    return _get_drive_api(credentials)
550559
def read(fname, URL, URLImage):
    """"""
    readme = open(path.join(path.dirname(__file__), fname)).read()
    if hasattr(readme, 'decode'):
        # In Python 3, turn bytes into str.
        readme = readme.decode('utf8')
    # turn relative links into absolute ones
    readme = re.sub(r'`<([^>]*)>`__',
                    r'`\1 <' + URL + r"/blob/master/\1>`__",
                    readme)
    readme = re.sub(r"\.\. image:: /", ".. image:: " + URLImage + "/", readme)

    return readme
636707
def extract_credentials(self, url):
        
        if isinstance(url, urllib2.Request):
            result = urlparse.urlsplit(url.get_full_url())
        else:
            result = urlparse.urlsplit(url)
        scheme, netloc, path, query, frag = result

        username, password = self.parse_credentials(netloc)
        if username is None:
            return url, None, None
        elif password is None and self.prompting:
            # remove the auth credentials from the url part
            netloc = netloc.replace('%s@' % username, '', 1)
            # prompt for the password
            prompt = 'Password for %s@%s: ' % (username, netloc)
            password = urllib.quote(getpass.getpass(prompt))
        else:
            # remove the auth credentials from the url part
            netloc = netloc.replace('%s:%s@' % (username, password), '', 1)

        target_url = urlparse.urlunsplit((scheme, netloc, path, query, frag))
        return target_url, username, password
825005
function (callback) {
    fs.readFile(clientSecretPath, function processClientSecrets(err, content) {
        if (err) {
            debug('Error loading client secret file: ' + err);
            return callback(err);
        } else {
            credentials = JSON.parse(content);
            return callback();
        }
    });
}
582842
static AuthFile parse(File file) throws IOException {
        String content = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8);

        AuthFile authFile;
        if (isJsonBased(content)) {
            authFile = ADAPTER.deserialize(content, AuthFile.class, SerializerEncoding.JSON);
            Map<String, String> endpoints = ADAPTER.deserialize(content, new TypeToken<Map<String, String>>() { }.getType(), SerializerEncoding.JSON);
            authFile.environment.endpoints().putAll(endpoints);
        } else {
            // Set defaults
            Properties authSettings = new Properties();
            authSettings.put(CredentialSettings.AUTH_URL.toString(), AzureEnvironment.AZURE.activeDirectoryEndpoint());
            authSettings.put(CredentialSettings.BASE_URL.toString(), AzureEnvironment.AZURE.resourceManagerEndpoint());
            authSettings.put(CredentialSettings.MANAGEMENT_URI.toString(), AzureEnvironment.AZURE.managementEndpoint());
            authSettings.put(CredentialSettings.GRAPH_URL.toString(), AzureEnvironment.AZURE.graphEndpoint());
            authSettings.put(CredentialSettings.VAULT_SUFFIX.toString(), AzureEnvironment.AZURE.keyVaultDnsSuffix());

            // Load the credentials from the file
            StringReader credentialsReader = new StringReader(content);
            authSettings.load(credentialsReader);
            credentialsReader.close();

            authFile = new AuthFile();
            authFile.clientId = authSettings.getProperty(CredentialSettings.CLIENT_ID.toString());
            authFile.tenantId = authSettings.getProperty(CredentialSettings.TENANT_ID.toString());
            authFile.clientSecret = authSettings.getProperty(CredentialSettings.CLIENT_KEY.toString());
            authFile.clientCertificate = authSettings.getProperty(CredentialSettings.CLIENT_CERT.toString());
            authFile.clientCertificatePassword = authSettings.getProperty(CredentialSettings.CLIENT_CERT_PASS.toString());
            authFile.subscriptionId = authSettings.getProperty(CredentialSettings.SUBSCRIPTION_ID.toString());
            authFile.environment.endpoints().put(AzureEnvironment.Endpoint.MANAGEMENT.identifier(), authSettings.getProperty(CredentialSettings.MANAGEMENT_URI.toString()));
            authFile.environment.endpoints().put(AzureEnvironment.Endpoint.ACTIVE_DIRECTORY.identifier(), authSettings.getProperty(CredentialSettings.AUTH_URL.toString()));
            authFile.environment.endpoints().put(AzureEnvironment.Endpoint.RESOURCE_MANAGER.identifier(), authSettings.getProperty(CredentialSettings.BASE_URL.toString()));
            authFile.environment.endpoints().put(AzureEnvironment.Endpoint.GRAPH.identifier(), authSettings.getProperty(CredentialSettings.GRAPH_URL.toString()));
            authFile.environment.endpoints().put(AzureEnvironment.Endpoint.KEYVAULT.identifier(), authSettings.getProperty(CredentialSettings.VAULT_SUFFIX.toString()));
        }
        authFile.authFilePath = file.getParent();

        return authFile;
    }
1272411
def make_http_credentials(username=None, password=None):
    """"""
    credentials = ''
    if username is None:
        return credentials
    if username is not None:
        if ':' in username:
            return credentials
        credentials += username
    if credentials and password is not None:
        credentials += ":%s" % password
    return "%s@" % credentials
1325747
def _from_dict(cls, _dict):
        """"""
        args = {}
        if 'credential_type' in _dict:
            args['credential_type'] = _dict.get('credential_type')
        if 'client_id' in _dict:
            args['client_id'] = _dict.get('client_id')
        if 'enterprise_id' in _dict:
            args['enterprise_id'] = _dict.get('enterprise_id')
        if 'url' in _dict:
            args['url'] = _dict.get('url')
        if 'username' in _dict:
            args['username'] = _dict.get('username')
        if 'organization_url' in _dict:
            args['organization_url'] = _dict.get('organization_url')
        if 'site_collection.path' in _dict:
            args['site_collection_path'] = _dict.get('site_collection.path')
        if 'client_secret' in _dict:
            args['client_secret'] = _dict.get('client_secret')
        if 'public_key_id' in _dict:
            args['public_key_id'] = _dict.get('public_key_id')
        if 'private_key' in _dict:
            args['private_key'] = _dict.get('private_key')
        if 'passphrase' in _dict:
            args['passphrase'] = _dict.get('passphrase')
        if 'password' in _dict:
            args['password'] = _dict.get('password')
        if 'gateway_id' in _dict:
            args['gateway_id'] = _dict.get('gateway_id')
        if 'source_version' in _dict:
            args['source_version'] = _dict.get('source_version')
        if 'web_application_url' in _dict:
            args['web_application_url'] = _dict.get('web_application_url')
        if 'domain' in _dict:
            args['domain'] = _dict.get('domain')
        if 'endpoint' in _dict:
            args['endpoint'] = _dict.get('endpoint')
        if 'access_key_id' in _dict:
            args['access_key_id'] = _dict.get('access_key_id')
        if 'secret_access_key' in _dict:
            args['secret_access_key'] = _dict.get('secret_access_key')
        return cls(**args)