Specific (basic) authentication decorator.

    This is used to note which object methods require username/password
    authorization and won't work with token based authorization.
544988
def requires_basic_auth(func):
    
    @wraps(func)
    def auth_wrapper(self, *args, **kwargs):
        if hasattr(self, '_session') and self._session.auth:
            return func(self, *args, **kwargs)
        else:
            from .models import GitHubError
            # Mock a 401 response
            r = generate_fake_error_response(
                '{"message": "Requires username/password authentication"}'
            )
            raise GitHubError(r)
    return auth_wrapper
837237
def authenticate(self, username, password):
        

        r = self._query_('/users/authenticate', 'POST',
                         params={'username': username,
                                 'password': password})
        if r.status_code == 201:
            return r.text.strip('"')
        else:
            raise ValueError('Authentication invalid.')
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
201713
def auth(context, request):
    

    if ploneapi.user.is_anonymous():
        request.response.setStatus(401)
        request.response.setHeader('WWW-Authenticate',
                                   'basic realm="JSONAPI AUTH"', 1)

    logger.info("*** BASIC AUTHENTICATE ***")
    return {}
940393
def requires_auth(func):
    """"""
    @wraps(func)
    def wrapper(self, *args, **kwargs):
        if self.token is None or self.token_expired:
            self.login()
        elif self.token_needs_refresh:
            self.refresh_token()
        return func(self, *args, **kwargs)
    return wrapper
1193220
def authenticator(function, challenges=()):
    
    challenges = challenges or ('{} realm="simple"'.format(function.__name__), )

    def wrapper(verify_user):
        def authenticate(request, response, **kwargs):
            result = function(request, response, verify_user, **kwargs)

            def authenticator_name():
                try:
                    return function.__doc__.splitlines()[0]
                except AttributeError:
                    return function.__name__

            if result is None:
                raise HTTPUnauthorized('Authentication Required',
                                       'Please provide valid {0} credentials'.format(authenticator_name()),
                                       challenges=challenges)

            if result is False:
                raise HTTPUnauthorized('Invalid Authentication',
                                       'Provided {0} credentials were invalid'.format(authenticator_name()),
                                       challenges=challenges)

            request.context['user'] = result
            return True

        authenticate.__doc__ = function.__doc__
        return authenticate

    return wrapper
869380
def auth(self, user=None, password=None, jsonp=None):
        
        if not user:
            user = self.user
        if not password:
            password = self.password
        parameters = {
                      'username' : self.user,
                      'password' : self.password
                     }
        if jsonp is not None:
            parameters['jsonp'] = jsonp
        status, headers = self._query(self.authurl, parameters)
        # return the callback call if we want jsonp
        if jsonp is not None:
            return status
        return (int(status), self.auth_status_codes[int(status)])
544552
def requires_authentication(fn):
        

        @functools.wraps(fn)
        def wrap(*args, **kwargs):
            subject = WebYosai.get_current_subject()

            if not subject.authenticated:
                msg = "The current Subject is not authenticated.  ACCESS DENIED."
                raise WebYosai.get_current_webregistry().raise_unauthorized(msg)

            return fn(*args, **kwargs)
        return wrap
77543
def check_auth(func):
    
    def wrapper(handler, *args, **kwargs):
        if handler.check_auth_header():
            return func(handler, *args, **kwargs)
    return wrapper
172174
def authTryNextMethod(self):
        
        if not self.authOrder:
            raise DBusAuthenticationFailed()
        
        self.authMech  = self.authOrder.pop()
            
        if self.authMech == 'DBUS_COOKIE_SHA1':
            self.sendAuthMessage('AUTH ' + self.authMech + ' ' +
                                 hexlify(getpass.getuser()))
        elif self.authMech == 'ANONYMOUS':
            self.sendAuthMessage('AUTH ' + self.authMech + ' ' +
                                 hexlify("txdbus"))
        else:
            self.sendAuthMessage('AUTH ' + self.authMech)
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
234200
def login_required(wrapped):
    
    @wraps(wrapped)
    def wrapper(*args, **kwargs):
        request = args[1]

        auth_collection = settings.AUTH_COLLECTION[
            settings.AUTH_COLLECTION.rfind('.') + 1:
        ].lower()
        auth_document = request.environ.get(auth_collection)

        if auth_document and auth_document.is_authorized(request):
            setattr(request, auth_collection, auth_document)
            return wrapped(*args, **kwargs)

        return Response(response=serialize(UnauthorizedError()), status=401)

    if hasattr(wrapped, 'decorators'):
        wrapper.decorators = wrapped.decorators
        wrapper.decorators.append('login_required')
    else:
        wrapper.decorators = ['login_required']

    return wrapper
618161
def basic_auth_handler(url, method, timeout, headers, data, username=None, password=None):
    """"""

    def handle():
        """Handler that implements HTTP Basic Auth.
        """
        if username is not None and password is not None:
            auth_value = '{0}:{1}'.format(username, password).encode('utf-8')
            auth_token = base64.b64encode(auth_value)
            auth_header = b'Basic ' + auth_token
            headers.append(['Authorization', auth_header])
        default_handler(url, method, timeout, headers, data)()

    return handle
130902
def basic_auth(f):
    

    def wrapper(*args, **kwargs):
        self = args[0]
        if 'auth' in kwargs:
            raise AttributeError("don't set auth token explicitly")
        assert self.is_connected, "not connected, call router.connect(email, password) first"

        if self._jwt_auth:
            kwargs['auth'] = self._jwt_auth
        elif self._auth:
            kwargs['auth'] = self._auth
        else:
            assert False, "no basic token, no JWT, but connected o_O"

        return f(*args, **kwargs)

    return wrapper
829060
def authenticate(self, username=None, password=None):
        
        data = api_client.authenticate(username, password)
        if not data:
            return

        return User(
            data.get('pk'), data.get('token'), data.get('user_data')
        )
883990
def _apply_auth(self, view_func):
        
        @functools.wraps(view_func)
        def decorated(*args, **kwargs):
            if not self.auth:
                return view_func(*args, **kwargs)

            auth_data = self.auth.get_authorization()

            if auth_data is None:
                return self._handle_authentication_error()

            if not self._authentication_callback or not self._authentication_callback(auth_data):
                return self._handle_authentication_error()

            return view_func(*args, **kwargs)

        return decorated