Gate function for _htpasswd and _htdigest authentication backends
968442
def _htfile(username, password, **kwargs):
    '''
    
    '''

    filetype = kwargs.get('filetype', 'htpasswd').lower()

    try:
        import passlib
        kwargs['passlib_version'] = passlib.__version__
    except ImportError:
        log.error('salt.auth.file: The python-passlib library is required '
                  'for %s filetype', filetype)
        return False

    if filetype == 'htdigest':
        return _htdigest(username, password, **kwargs)
    else:
        return _htpasswd(username, password, **kwargs)
331252
def _prep_ssh(
            self,
            tgt,
            fun,
            arg=(),
            timeout=None,
            tgt_type='glob',
            kwarg=None,
            **kwargs):
        '''
        
        '''
        opts = copy.deepcopy(self.opts)
        opts.update(kwargs)
        if timeout:
            opts['timeout'] = timeout
        arg = salt.utils.args.condition_input(arg, kwarg)
        opts['argv'] = [fun] + arg
        opts['selected_target_option'] = tgt_type
        opts['tgt'] = tgt
        opts['arg'] = arg
        return salt.client.ssh.SSH(opts)
1252592
def _replace_pg_hba(self):
        

        # when we are doing custom bootstrap we assume that we don't know superuser password
        # and in order to be able to change it, we are opening trust access from a certain address
        if self._running_custom_bootstrap:
            addresses = {'': 'local'}
            if 'host' in self._local_address and not self._local_address['host'].startswith('/'):
                for _, _, _, _, sa in socket.getaddrinfo(self._local_address['host'], self._local_address['port'],
                                                         0, socket.SOCK_STREAM, socket.IPPROTO_TCP):
                    addresses[sa[0] + '/32'] = 'host'

            with open(self._pg_hba_conf, 'w') as f:
                f.write(self._CONFIG_WARNING_HEADER)
                for address, t in addresses.items():
                    f.write((
                        '{0}\treplication\t{1}\t{3}\ttrust\n'
                        '{0}\tall\t{2}\t{3}\ttrust\n'
                    ).format(t, self._replication['username'], self._superuser.get('username') or 'all', address))
        elif not self._server_parameters.get('hba_file') and self.config.get('pg_hba'):
            with open(self._pg_hba_conf, 'w') as f:
                f.write(self._CONFIG_WARNING_HEADER)
                for line in self.config['pg_hba']:
                    f.write('{0}\n'.format(line))
            return True
75387
def www_authenticate(self):
        """"""
        def on_update(www_auth):
            if not www_auth and 'www-authenticate' in self.headers:
                del self.headers['www-authenticate']
            elif www_auth:
                self.headers['WWW-Authenticate'] = www_auth.to_header()
        header = self.headers.get('www-authenticate')
        return parse_www_authenticate_header(header, on_update)
713720
def pub_ret(self, load, skip_verify=False):
        '''
        
        '''
        if not skip_verify and any(key not in load for key in ('jid', 'id')):
            return {}
        else:
            auth_cache = os.path.join(
                    self.opts['cachedir'],
                    'publish_auth')
            if not os.path.isdir(auth_cache):
                os.makedirs(auth_cache)
            jid_fn = os.path.join(auth_cache, load['jid'])
            with salt.utils.files.fopen(jid_fn, 'r') as fp_:
                if not load['id'] == salt.utils.stringutils.to_unicode(fp_.read()):
                    return {}

            return self.local.get_cache_returns(load['jid'])
106531
def cli(self, eauth):
        '''
        
        '''
        ret = {}
        if not eauth:
            print('External authentication system has not been specified')
            return ret
        fstr = '{0}.auth'.format(eauth)
        if fstr not in self.auth:
            print(('The specified external authentication system "{0}" is '
                   'not available').format(eauth))
            print("Available eauth types: {0}".format(", ".join(self.auth.file_mapping.keys())))
            return ret

        args = salt.utils.args.arg_lookup(self.auth[fstr])
        for arg in args['args']:
            if arg in self.opts:
                ret[arg] = self.opts[arg]
            elif arg.startswith('pass'):
                ret[arg] = getpass.getpass('{0}: '.format(arg))
            else:
                ret[arg] = input('{0}: '.format(arg))
        for kwarg, default in list(args['kwargs'].items()):
            if kwarg in self.opts:
                ret['kwarg'] = self.opts[kwarg]
            else:
                ret[kwarg] = input('{0} [{1}]: '.format(kwarg, default))

        # Use current user if empty
        if 'username' in ret and not ret['username']:
            ret['username'] = salt.utils.user.get_user()

        return ret
814127
def process_auth(self):
        
        r = self._reader
        w = self._writer
        pdu_size = r.get_smallint()
        if not self.authentication:
            raise tds_base.Error('Got unexpected token')
        packet = self.authentication.handle_next(readall(r, pdu_size))
        if packet:
            w.write(packet)
            w.flush()
230795
def load_verifying_key(verifying_key, crypto_backend=default_backend()):
    
    if not isinstance(crypto_backend, (Backend, MultiBackend)):
        raise ValueError('backend must be a valid Backend object')

    if isinstance(verifying_key, EllipticCurvePublicKey):
        return verifying_key
    elif isinstance(verifying_key, (str, unicode)):
        try:
            return load_der_public_key(
                verifying_key, backend=crypto_backend)
        except:
            try:
                return load_pem_public_key(
                    verifying_key, backend=crypto_backend)
            except Exception:
                raise ValueError('Invalid verifying key format')
    else:
        raise ValueError('Invalid verification key type')
64980
def authenticationAndCipheringReject():
    """"""
    a = TpPd(pd=0x3)
    b = MessageType(mesType=0x14)  # 00010100
    packet = a / b
    return packet
600254
def auth_tls(self, mount_point='cert', use_token=True):
        
        return self.login('/v1/auth/{0}/login'.format(mount_point), use_token=use_token)
213121
def parse_auth(header):
    
    try:
        method, data = header.split(None, 1)
        if method.lower() == 'basic':
            data = base64.b64decode(uniorbytes(data, bytes))
            user, pwd = uniorbytes(data).split(':', 1)
            return user, pwd
    except (KeyError, AttributeError, ValueError):
        return (None, None)
1098621
def pcwd(func):
    """"""
    
    @wraps(func)
    def inner(*args, **kw):
        with PreserveWorkingDirectory():
            return func(*args, **kw)
    
    return inner
409728
def _security_auth_headers(self, username, password, headers):
        
        userColonPassword = username + ":" + password
        b64UserColonPassword = base64. \
            b64encode(str_to_bytes(userColonPassword)).decode("ascii")
        headers['Authorization'] = 'Basic %s' % b64UserColonPassword
610914
def __prepare_gprest_call(self, requestURL, params=None, headers=None, restType='GET', body=None):
        
        if self.__serviceAccount.is_iam_enabled():
            auth = None
            iam_api_key_header = {
                self.__AUTHORIZATION_HEADER_KEY: str('API-KEY '+self.__serviceAccount.get_api_key())
            }
            if not headers is None:
                headers.update(iam_api_key_header)
            else:
                headers = iam_api_key_header
        elif self.__auth == self.BASIC_AUTH:
            auth = (self.__serviceAccount.get_user_id(),
                    self.__serviceAccount.get_password())
        elif self.__auth == self.HMAC_AUTH:
            auth = None

            # need to prepare url by appending params to the end
            # before creating the hmac headers
            fakeRequest = requests.PreparedRequest()
            fakeRequest.prepare_url(requestURL, params=params)
            preparedUrl = fakeRequest.url

            hmacHeaders = self.__get_gaas_hmac_headers(method=restType,
                                                       url=preparedUrl, body=body)
            if not headers is None:
                headers.update(hmacHeaders)
            else:
                headers = hmacHeaders
        return auth, headers
889478
def authenticated(function):
    """"""
    def wrapped(*args):
        """Wrap function."""
        try:
            return function(*args)
        except UPSError:
            _login(*args)
            return function(*args)
    return wrapped
1362181
function auth(cmd, args, info) {
  var pass = args[0];
  if(pass instanceof Buffer) {
    pass = pass.toString();
  }
  if(!info.conf.requirepass) {
    throw AuthNotSet;
  }else if(pass !== info.conf.requirepass) {
    throw InvalidPassword;
  }
  return true;
}
4391
def authentication(self):
        """"""
        if self.session.digest:
            authentication = self.session.generate_digest()
        elif self.session.basic:
            authentication = self.session.generate_basic()
        else:
            return ''
        return "Authorization: " + authentication + '\r\n'