Authenticated call to splunk
435588
def splunk(cmd, user='admin', passwd='changeme'):
    """"""
    return sudo('/opt/splunkforwarder/bin/splunk {c} -auth {u}:{p}'
                .format(c=cmd, u=user, p=passwd))
137123
def authenticated_handler(self, f):
        
        @functools.wraps(f)
        def decorated():
            resp = self._handle_authenticate_response()
            return f(resp)
        self._authenticated_handler = decorated
        return decorated
89130
def invoke(self, headers, body):
        
        xml = Service._create_request(headers, body)

        try:
            response = self.session.post(self.endpoint, verify=False, data=xml)
            logging.debug(response.content)
        except Exception as e:
            traceback.print_exc()
            raise WSManException(e)

        if response.status_code == 200:
            return Service._parse_response(response.content)

        if response.status_code == 401:
            raise WSManAuthenticationException('the remote host rejected authentication')

        raise WSManException('the remote host returned an unexpected http status code: %s' % response.status_code)
694936
def get_sd_auth(val, sd_auth_pillar_name='serverdensity'):
    '''
    
    '''
    sd_pillar = __pillar__.get(sd_auth_pillar_name)
    log.debug('Server Density Pillar: %s', sd_pillar)
    if not sd_pillar:
        log.error('Could not load %s pillar', sd_auth_pillar_name)
        raise CommandExecutionError(
            '{0} pillar is required for authentication'.format(sd_auth_pillar_name)
        )

    try:
        return sd_pillar[val]
    except KeyError:
        log.error('Could not find value %s in pillar', val)
        raise CommandExecutionError('{0} value was not found in pillar'.format(val))
101831
def get_http_authentication(private_key: RsaKey, private_key_id: str) -> HTTPSignatureHeaderAuth:
    
    key = private_key.exportKey()
    return HTTPSignatureHeaderAuth(
        headers=["(request-target)", "user-agent", "host", "date"],
        algorithm="rsa-sha256",
        key=key,
        key_id=private_key_id,
    )
908822
def authenticationResponse():
    """"""
    a = TpPd(pd=0x5)
    b = MessageType(mesType=0x14)  # 00010100
    c = AuthenticationParameterSRES()
    packet = a / b / c
    return packet
1135181
function callServer(ctx, config, callback) {
    const ip = ctx.ip;
    const fullUrl = ctx.fullUrl;
    const vid = ctx.vid || '';
    const pxhd = ctx.pxhd || '';
    const vidSource = ctx.vidSource || '';
    const uuid = ctx.uuid || '';
    const uri = ctx.uri || '/';
    const headers = pxUtil.formatHeaders(ctx.headers, config.SENSITIVE_HEADERS);
    const httpVersion = ctx.httpVersion;
    const riskMode = config.MODULE_MODE === config.MONITOR_MODE.MONITOR ? 'monitor' : 'active_blocking';

    const data = {
        request: {
            ip: ip,
            headers: headers,
            url: fullUrl,
            uri: uri,
            firstParty: config.FIRST_PARTY_ENABLED
        },
        additional: {
            s2s_call_reason: ctx.s2sCallReason,
            http_version: httpVersion,
            http_method: ctx.httpMethod,
            risk_mode: riskMode,
            module_version: config.MODULE_VERSION,
            cookie_origin: ctx.cookieOrigin,
            request_cookie_names: ctx.requestCookieNames
        }
    };

    if (ctx.s2sCallReason === 'cookie_decryption_failed') {
        data.additional.px_orig_cookie = ctx.getCookie(); //No need strigify, already a string
    }

    if (ctx.s2sCallReason === 'cookie_expired' || ctx.s2sCallReason === 'cookie_validation_failed') {
        data.additional.px_cookie = JSON.stringify(ctx.decodedCookie);
    }

    pxUtil.prepareCustomParams(config, data.additional);

    const reqHeaders = {
        Authorization: 'Bearer ' + config.AUTH_TOKEN,
        'Content-Type': 'application/json'
    };

    if (vid) {
        data.vid = vid;
    }
    if (uuid) {
        data.uuid = uuid;
    }
    if (pxhd) {
        data.pxhd = pxhd;
    }
    if (vidSource) {
        data.vid_source = vidSource;
    }
    if (pxhd && data.additional.s2s_call_reason === 'no_cookie') {
        data.additional.s2s_call_reason = 'no_cookie_w_vid';
    }
    if (ctx.originalUuid) {
        data.additional['original_uuid'] = ctx.originalUuid;
    }

    if (ctx.originalTokenError) {
        data.additional['original_token_error'] = ctx.originalTokenError;
    }

    if (ctx.originalToken) {
        data.additional['original_token'] = ctx.originalToken;
    }

    if (ctx.decodedOriginalToken) {
        data.additional['px_decoded_original_token'] = ctx.decodedOriginalToken;
    }

    if(ctx.hmac) {
        data.additional['px_cookie_hmac'] = ctx.hmac;
    }

    ctx.hasMadeServerCall = true;
    return pxHttpc.callServer(data, reqHeaders, config.SERVER_TO_SERVER_API_URI, 'query', config, callback);
}
356376
def _authenticate(self):
        """"""
        data = {'username': self.username,
                'password': self.password}
        url = '{base}/client/login'.format(base=self.base_url)
        response = self._session.get(url, params=data)
        print(response.text)
        data = response.json()
        if not data.get('success'):
            raise InvalidCredentials(data.get('reason', None))
        self._populate_info(data)
830010
function authenticatedAction(data, socketSend) {
		var type = data.type
		switch(type) {
		case 'getApps':
			socketSend(godModel.getApps()) // does not fail and has no callback
			break
		case 'reload':
			godModel.reload(result)
			break
		case 'nodebug':
			type = 'run'
		case 'run':
		case 'stop':
		case 'debug':
		case 'restart':
			godModel.write(data.app, type, result)
			break
		default:
			log('Unknown command:', data)
			socketSend({err: 'unknown command'})
		}

		function result(err) {
			if (err) socketSend({err: err.message})
		}
	}
746619
function authenticate(ctx) {
  var fn = lookup(ctx.operation, 'middleware', 'authenticate');
  var prefix = describe(ctx);

  if (fn) {
    return fn(ctx);
  } else {
    debug(prefix + 'authenticate middleware disabled (not defined)');
  }
}
664147
private <ReqT, RespT> boolean authenticateCall(ServerCall<ReqT, RespT> call, Metadata headers) {
    // Fail validation for cancelled server calls.
    if (call.isCancelled()) {
      LOG.debug("Server call has been cancelled: %s",
          call.getMethodDescriptor().getFullMethodName());
      return false;
    }

    // Try to fetch channel Id from the metadata.
    UUID channelId = headers.get(ChannelIdInjector.S_CLIENT_ID_KEY);
    boolean callAuthenticated = false;
    if (channelId != null) {
      try {
        // Fetch authenticated username for this channel and set it.
        AuthenticatedUserInfo userInfo = mAuthenticationServer.getUserInfoForChannel(channelId);
        if (userInfo != null) {
          AuthenticatedClientUser.set(userInfo.getAuthorizedUserName());
          AuthenticatedClientUser.setConnectionUser(userInfo.getConnectionUserName());
          AuthenticatedClientUser.setAuthMethod(userInfo.getAuthMethod());
        } else {
          AuthenticatedClientUser.remove();
        }
        callAuthenticated = true;
      } catch (UnauthenticatedException e) {
        String message = String.format("Channel: %s is not authenticated for call: %s",
            channelId.toString(), call.getMethodDescriptor().getFullMethodName());
        call.close(Status.UNAUTHENTICATED.withDescription(message), headers);
      }
    } else {
      String message = String.format("Channel Id is missing for call: %s.",
          call.getMethodDescriptor().getFullMethodName());
      call.close(Status.UNAUTHENTICATED.withDescription(message), headers);
    }
    return callAuthenticated;
  }
1218542
def authenticated(viewfunc):
    """"""
    @wraps(viewfunc)
    def wrapper(*args, **kwargs):
        ctx = stack.top
        if ctx and hasattr(ctx, 'htauth'):
            auth_header = request.headers.get('Authorization', None)
            if not auth_header:
                return _unauthorized_response()

            if not auth_header.startswith('Basic '):
                raise RuntimeError('Flask-HTAuth supports only Basic auth.')

            auth_header = auth_header.replace('Basic ', '')
            auth_header = base64.b64decode(auth_header)
            username, password = auth_header.split(':', 1)

            if not username in ctx.htauth['users']:
                return _unauthorized_response()

            if not check_password(password, ctx.htauth['users'][username]):
                return _unauthorized_response()

            g.htauth_user = username

        return viewfunc(*args, **kwargs)

    return wrapper
98311
def authenticate(cmd_args, endpoint='', force=False):
    
    server = server_url(cmd_args)
    network.check_ssl()
    access_token = None

    try:
        assert not force
        access_token = refresh_local_token(server)
    except Exception:
        print('Performing authentication')
        access_token = perform_oauth(get_code, cmd_args, endpoint)
        email = display_student_email(cmd_args, access_token)
        if not email:
            log.warning('Could not get login email. Try logging in again.')

    log.debug('Authenticated with access token={}'.format(access_token))

    return access_token
142409
def publish_to_splunk(
            self,
            payload=None):
        
        self.debug_log('publish_to_splunk - start')

        use_payload = payload
        if not use_payload:
            use_payload = self.log_payload

        self.num_sent = 0

        if use_payload:
            url = 'https://{}:{}/services/collector'.format(
                self.host,
                self.port)
            self.debug_log('splunk url={}'.format(
                url))

            try:
                if self.debug:
                    try:
                        msg_dict = json.loads(use_payload)
                        event_data = json.loads(msg_dict['event'])
                        msg_dict['event'] = event_data
                        self.debug_log((
                            'sending payload: {}').format(
                                ppj(msg_dict)))
                    except Exception:
                        self.debug_log((
                            'sending data payload: {}').format(
                                use_payload))
                if self.num_sent > 100000:
                    self.num_sent = 1
                else:
                    self.num_sent += 1
                send_to_splunk.send_to_splunk(
                    session=self.session,
                    url=url,
                    data=use_payload,
                    headers={'Authorization': 'Splunk {}'.format(
                        self.token)},
                    verify=self.verify,
                    timeout=self.timeout)
                self.debug_log('payload sent success')
            except Exception as e:
                try:
                    self.write_log(
                        'Exception in Splunk logging handler: {}'.format(
                            e))
                    self.write_log(traceback.format_exc())
                except Exception:
                    self.debug_log(
                        'Exception encountered,'
                        'but traceback could not be formatted')

            self.log_payload = ''
        else:
            self.debug_log(
                'no logs to send')

        self.debug_log((
            'publish_to_splunk - done - '
            'self.is_shutting_down={} self.shutdown_now={}').format(
                self.is_shutting_down(shutdown_event=self.shutdown_event),
                self.shutdown_now))
1058144
def authenticated(f):
    """"""
    @wraps(f)
    def new_f(self, *args, **kwargs):
        if not self.nova_client.client.auth_token:
            self.authenticate()
        return f(self, *args, **kwargs)
    return new_f
72125
function logon() {
    var dfrd = Q.defer();
    var token = cache.get('token');

    function extractToken(xml) {
      var r = _parse(xml, dfrd);
      if (r) {
        return r.response.token[0];
      }
    }

    if (token) {
      dfrd.resolve({
        token: token,
        cached: true
      });
    }

    request(format(URLs.logon, PROTOCOL, conf.host, conf.username,
        conf.password),
      function(err, res, body) {
        var newToken;
        if (err) {
          dfrd.reject(err);
        } else {
          newToken = extractToken(body);
          if (!newToken) {
            dfrd.reject(MODULE_ERRORS.unknown);
          } else {
            cache.put('token', newToken);
            dfrd.resolve({
              token: newToken,
              cached: false
            });
          }
        }
      });
    return dfrd.promise;
  }
785497
def _get_splunk(profile):
    '''
    
    '''
    config = __salt__['config.option'](profile)

    key = "splunk.{0}:{1}:{2}:{3}".format(
        config.get('host'),
        config.get('port'),
        config.get('username'),
        config.get('password')
    )

    if key not in __context__:
        __context__[key] = splunklib.client.connect(
            host=config.get('host'),
            port=config.get('port'),
            username=config.get('username'),
            password=config.get('password'))

    return __context__[key]