Private API request: wraps _call, requires auth.
320305
private function _privateRequest($method, $path, $param = '') {
    $headers = $this->auth->getAuthHeaders($path, $param, $method);

    return $this->_call($method, $path, $param, $headers);
  }
1067693
def oauth_required(f):
        
        @wraps(f)
        def decorated_function(*args, **kwargs):
            if 'oauth_user_uri' not in session or session['oauth_user_uri'] is None:
                return redirect(url_for('.r_oauth_login', next=request.url))
            return f(*args,**kwargs)
        return decorated_function
1339611
function _wrapCalls(options){
            return function(){
                var api;

                options.func.apply(options.context, Array.prototype.slice.call(arguments, 0));

                for (var i = 0; i < externalAPIS.length; i++) {
                    api = externalAPIS[i];
                    if (api[options.triggerType]) {
                        try {
                            api[options.triggerType].apply(api.context,Array.prototype.slice.call(arguments, 0));
                        }
                        catch (exc) {}
                    }
                }
            };
        }
325812
def authenticated(function):
    """"""
    def wrapped(*args):
        """Wrap function."""
        try:
            return function(*args)
        except FedexError:
            _login(*args)
            return function(*args)
    return wrapped
233932
def call(payload=None):
    '''
    
    '''
    r = None
    try:
        if DETAILS['method'] == 'dev_key':
            # Pass the api key without the target declaration
            conditional_payload = {'key': DETAILS['apikey']}
            payload.update(conditional_payload)
            r = __utils__['http.query'](DETAILS['url'],
                                        data=payload,
                                        method='POST',
                                        decode_type='plain',
                                        decode=True,
                                        verify_ssl=False,
                                        status=True,
                                        raise_error=True)
        elif DETAILS['method'] == 'dev_pass':
            # Pass credentials without the target declaration
            r = __utils__['http.query'](DETAILS['url'],
                                        username=DETAILS['username'],
                                        password=DETAILS['password'],
                                        data=payload,
                                        method='POST',
                                        decode_type='plain',
                                        decode=True,
                                        verify_ssl=False,
                                        status=True,
                                        raise_error=True)
        elif DETAILS['method'] == 'pan_key':
            # Pass the api key with the target declaration
            conditional_payload = {'key': DETAILS['apikey'],
                                   'target': DETAILS['serial']}
            payload.update(conditional_payload)
            r = __utils__['http.query'](DETAILS['url'],
                                        data=payload,
                                        method='POST',
                                        decode_type='plain',
                                        decode=True,
                                        verify_ssl=False,
                                        status=True,
                                        raise_error=True)
        elif DETAILS['method'] == 'pan_pass':
            # Pass credentials with the target declaration
            conditional_payload = {'target': DETAILS['serial']}
            payload.update(conditional_payload)
            r = __utils__['http.query'](DETAILS['url'],
                                        username=DETAILS['username'],
                                        password=DETAILS['password'],
                                        data=payload,
                                        method='POST',
                                        decode_type='plain',
                                        decode=True,
                                        verify_ssl=False,
                                        status=True,
                                        raise_error=True)
    except KeyError as err:
        raise salt.exceptions.CommandExecutionError("Did not receive a valid response from host.")

    if not r:
        raise salt.exceptions.CommandExecutionError("Did not receive a valid response from host.")

    if six.text_type(r['status']) not in ['200', '201', '204']:
        if six.text_type(r['status']) == '400':
            raise salt.exceptions.CommandExecutionError(
                "The server cannot process the request due to a client error.")
        elif six.text_type(r['status']) == '401':
            raise salt.exceptions.CommandExecutionError(
                "The server cannot process the request because it lacks valid authentication "
                "credentials for the target resource.")
        elif six.text_type(r['status']) == '403':
            raise salt.exceptions.CommandExecutionError(
                "The server refused to authorize the request.")
        elif six.text_type(r['status']) == '404':
            raise salt.exceptions.CommandExecutionError(
                "The requested resource could not be found.")
        else:
            raise salt.exceptions.CommandExecutionError(
                "Did not receive a valid response from host.")

    xmldata = ET.fromstring(r['text'])

    # If we are pulling the candidate configuration, we need to strip the dirtyId
    if payload['type'] == 'config' and payload['action'] == 'get':
        xmldata = (_strip_dirty(xmldata))

    return xml.to_dict(xmldata, True)
1360868
def token_protected_endpoint(function):
  
  @wraps(function)
  def decorated(*args, **kwargs):
    auth_token = request.form.get('auth_token')
    if not auth_token:
      return json.dumps({
        'status': 'fail',
        'reason': 'You must provide an auth_token',
      })

    data = dict(request.form)
    del data['auth_token']
    correct_token = create_token(current_app.config['SECRET_KEY'], data)

    if _compare_digest(auth_token, correct_token):
      return function(*args, **kwargs)

    else:
      return json.dumps({
        'status': 'fail',
        'reason': 'Incorrect auth_token',
      })

  return decorated
201697
def call_and_wrap(func, *args, **kw):
    '''
    '''
    try:
        return func(*args, **kw)
    except api.exceptions.APIException as ex:
        click_exception(ex)
    except urllib3exc.SSLError:
        # see monkey patch above re InsecurePlatformWarning
        if _insecure_warning:
            click.echo(click.style(str(_insecure_warning[0]), fg='red'))
        raise
799591
def handle_authn_request(self, context):
        
        internal_req = self._handle_authn_request(context)
        if not isinstance(internal_req, InternalData):
            return internal_req
        return self.auth_req_callback_func(context, internal_req)
1294233
def wraps(self, f):
        
        @_utils.wraps(f)
        def wrapped_f(*args, **kw):
            return self.call(f, *args, **kw)

        def retry_with(*args, **kwargs):
            return self.copy(*args, **kwargs).wraps(f)

        wrapped_f.retry = self
        wrapped_f.retry_with = retry_with

        return wrapped_f
239076
def called_with(self, *args, **kwargs):
        
        expected_call = Call(*args, **kwargs)
        if expected_call in calls(self.spy):
            return True
        raise VerificationError(
            "expected %s to be called with %s, but it wasn't" % (
                self.spy, expected_call.formatted_args))
871637
def call(self, func, *args, **kwargs):
        
        wrapped = self.wrap(func)
        return wrapped(*args, **kwargs)
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
110592
function _loginEvrythng(credentials, successCallback, errorCallback) {

    if(!credentials || Utils.isFunction(credentials)) {
      throw new TypeError('Credentials are missing.');
    }

    // Send the authentication request to the REST API, which is a Promise.
    // Note that the context is passed from the above *app.login()* method
    // until the raw call in order to pass the correct scope's Api Key.
    return _authEvrythng.call(this, credentials).then(function (userResponse) {

      // Login was successful, apply callback and propagate response to the
      // next promise handler.
      if(successCallback) {
        Logger.warnCallbackDeprecation();
        successCallback(userResponse);
      }
      return userResponse;

    }, function (response) {

      // Login was not successful, call error callback and re-throw error.
      if(errorCallback) {
        Logger.warnCallbackDeprecation();
        errorCallback(response);
      }
      throw response;

    });
  }
738639
def authenticated(function):
    """"""
    def wrapped(*args):
        """Wrap function."""
        try:
            return function(*args)
        except MoparError:
            _LOGGER.info("attempted to access page before login")
            _login(args[0])
            return function(*args)
    return wrapped
258921
def requires_auth(f):
    
    @wraps(f)

    def decorated(self, *args, **kwargs):
        

        # Fetch auth options from args
        auth_options = {}
        nipap_args = {}

        # validate function arguments
        if len(args) == 1:
            nipap_args = args[0]
        else:
            self.logger.debug("Malformed request: got %d parameters" % len(args))
            raise Fault(1000, ("NIPAP API functions take exactly 1 argument (%d given)") % len(args))

        if type(nipap_args) != dict:
            self.logger.debug("Function argument is not struct")
            raise Fault(1000, ("Function argument must be XML-RPC struct/Python dict (Python %s given)." %
                type(nipap_args).__name__ ))

        # fetch auth options
        try:
            auth_options = nipap_args['auth']
            if type(auth_options) is not dict:
                raise ValueError()
        except (KeyError, ValueError):
            self.logger.debug("Missing/invalid authentication options in request.")
            raise Fault(1000, ("Missing/invalid authentication options in request."))

        # fetch authoritative source
        try:
            auth_source = auth_options['authoritative_source']
        except KeyError:
            self.logger.debug("Missing authoritative source in auth options.")
            raise Fault(1000, ("Missing authoritative source in auth options."))

        if not request.authorization:
            return authenticate()

        # init AuthFacory()
        af = AuthFactory()
        auth = af.get_auth(request.authorization.username,
                request.authorization.password, auth_source, auth_options or {})

        # authenticated?
        if not auth.authenticate():
            self.logger.debug("Incorrect username or password.")
            raise Fault(1510, ("Incorrect username or password."))

        # Replace auth options in API call arguments with auth object
        new_args = dict(args[0])
        new_args['auth'] = auth

        return f(self, *(new_args,), **kwargs)

    return decorated
1107536
def http_auth_required(realm):
    """"""

    def decorator(fn):
        @wraps(fn)
        def wrapper(*args, **kwargs):
            if _check_http_auth():
                return fn(*args, **kwargs)
            if _security._unauthorized_callback:
                return _security._unauthorized_callback()
            else:
                r = _security.default_http_auth_realm \
                    if callable(realm) else realm
                h = {'WWW-Authenticate': 'Basic realm="%s"' % r}
                return _get_unauthorized_response(headers=h)
        return wrapper

    if callable(realm):
        return decorator(realm)
    return decorator
1110145
def add_auth(f):
    """"""

    def add_auth_decorator(*args, **kwargs):
        token = get_user_token()
        if 'headers' not in kwargs:
            kwargs['headers'] = {}
        kwargs['headers']['Authorization'] = "Bearer %s" % token
        return f(*args, **kwargs)

    return add_auth_decorator