Decorator. Use it to specify a RPC method is available only to logged users
551866
def http_basic_auth_login_required(func=None):
    """"""

    wrapper = auth.set_authentication_predicate(http_basic_auth_check_user, [auth.user_is_authenticated])

    # If @http_basic_auth_login_required() is used (with parenthesis)
    if func is None:
        return wrapper

    # If @http_basic_auth_login_required is used without parenthesis
    return wrapper(func)
651734
def user_is(role, get_user=import_user):
    
    def wrapper(func):
        @wraps(func)
        def inner(*args, **kwargs):
            from .models import Role
            current_user = get_user()
            if role in current_user.roles:
                return func(*args, **kwargs)
            raise Forbidden("You do not have access")
        return inner
    return wrapper
852338
def login_required(function=None, username=None, basic=False, must=None):
    

    if function and not callable(function):
        raise ValueError(
            'Decorator receives only named arguments, '
            'try login_required(username="foo")'
        )

    def check(validators):
        """Return in the first validation error, else return None"""
        if validators is None:
            return
        if not isinstance(validators, (list, tuple)):
            validators = [validators]
        for validator in validators:
            error = validator(get_username())
            if error is not None:
                return SimpleLogin.get_message('auth_error', error), 403

    def dispatch(fun, *args, **kwargs):
        if basic and request.is_json:
            return dispatch_basic_auth(fun, *args, **kwargs)

        if is_logged_in(username=username):
            return check(must) or fun(*args, **kwargs)
        elif is_logged_in():
            return SimpleLogin.get_message('access_denied'), 403
        else:
            flash(SimpleLogin.get_message('login_required'), 'warning')
            return redirect(url_for('simplelogin.login', next=request.path))

    def dispatch_basic_auth(fun, *args, **kwargs):
        simplelogin = current_app.extensions['simplelogin']
        auth_response = simplelogin.basic_auth()
        if auth_response is True:
            return check(must) or fun(*args, **kwargs)
        else:
            return auth_response

    if function:
        @wraps(function)
        def simple_decorator(*args, **kwargs):
            """This is for when decorator is @login_required"""
            return dispatch(function, *args, **kwargs)
        return simple_decorator

    def decorator(f):
        """This is for when decorator is @login_required(...)"""
        @wraps(f)
        def wrap(*args, **kwargs):
            return dispatch(f, *args, **kwargs)
        return wrap
    return decorator
1321926
def _redis_strict_pc(func):
    
    phase = "session_%s" % func.__name__

    @functools.wraps(func)
    def wrapper(self, session, *args, **kwargs):
        try:
            func(self, session, *args, **kwargs)
            self.logger.debug("%s -> %s" % (session.meepo_unique_id, phase))
            return True
        except Exception as e:
            if self.strict:
                raise
            if isinstance(e, redis.ConnectionError):
                self.logger.warn("redis connection error in %s: %s" % (
                    phase, session.meepo_unique_id))
            else:
                self.logger.exception(e)
            return False
    return wrapper
545965
def jwt_required(func):
    
    if inspect.isclass(func):
        apply_function_to_members(func, jwt_required)
        return func
    else:
        @functools.wraps(func)
        def deco(*a, **kw):
            if not "Authorization" in request.headers:
                abort(401, "Not Authorized")
            return func(*a, **kw)

        return deco
424279
def superuser_only(view_func):
    
    def _inner(request, *args, **kwargs):
        if not request.user.is_superuser:
            raise PermissionDenied
        return view_func(request, *args, **kwargs)
    return _inner
169975
def requires_auth(self, func):
        '''
        
        '''
        @wraps(func)
        def decorated(*args, **kwargs):
            ''' Wrapper '''
            auth = request.authorization
            if not auth or not self.check_auth(auth.username, auth.password):
                return self.authenticate()
            return func(*args, **kwargs)
        return decorated
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
1151547
def auth_required(method):
    
    @functools.wraps(method)
    def wrapper(*args, **kwargs):
        _verify_and_add_jwt()
        try:
            return method(*args, **kwargs)
        finally:
            remove_jwt_data_from_app_context()
    return wrapper
877293
def observed(func):
    

    def wrapper(*args, **kwargs):
        self = args[0]
        assert(isinstance(self, Observable))

        self._notify_method_before(self, func.__name__, args, kwargs)
        res = func(*args, **kwargs)
        self._notify_method_after(self, func.__name__, res, args, kwargs)
        return res

    log.logger.warning("Decorator observable.observed is deprecated:"
                       "use Observable.observed instead")
    return wrapper
529947
def xmlrpc_machine_required(function=None):
    
    def actual_decorator(func):
        def wrapper(machine_name, password, *args):
            from django_xmlrpc.decorators import AuthenticationFailedException
            from karaage.machines.models import Machine
            machine = Machine.objects.authenticate(machine_name, password)
            if machine is None:
                raise AuthenticationFailedException
            return func(machine, *args)

        if hasattr(func, '_xmlrpc_signature'):
            sig = func._xmlrpc_signature
            sig['args'] = (['string'] * 2) + sig['args']
            wrapper._xmlrpc_signature = sig

        if func.__doc__:
            wrapper.__doc__ = func.__doc__ + \
                "\nNote: Machine authentication is required."
        return wrapper

    if function:
        return actual_decorator(function)
    return actual_decorator
248294
def operations():
    
    def decorator(func):
        @wraps(func)
        def wrapped_func(*args, **kwargs):

            self = args[0]
            assert self.__can_use, "User operation queue only in 'with' block"

            def defaults_dict():
                f_args, varargs, keywords, defaults = inspect.getargspec(func)
                defaults = defaults or []
                return dict(zip(f_args[-len(defaults)+len(args[1:]):], defaults[len(args[1:]):]))

            route_args = dict(defaults_dict().items() + kwargs.items())

            func(*args, **kwargs)
            self.operations.append((func.__name__, args[1:], route_args, ))

        return wrapped_func
    def decorate(clazz):

        for attr in clazz.__dict__:
            if callable(getattr(clazz, attr)):
                setattr(clazz, attr, decorator(getattr(clazz, attr)))
        def __init__(self):  # simple parameter-less constructor
            self.operations = []
            self.__can_use = True
        def invalidate(self):
            self.__can_use = False
        clazz.__init__ = __init__
        clazz.invalidate = invalidate
        return clazz
    return decorate
684630
def require_sender(f):
    
    @wraps(f)
    def decorator(*args, **kwargs):
        if not request.authorization:
            return jsonify({'message': 'unauthorized'}), 401

        username = request.authorization.username
        password = request.authorization.password

        if not validate_sender(username, password):
            return jsonify({'message': 'forbidden'}), 403

        return f(*args, **kwargs)
    return decorator
549743
def login_required(func=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):
    
    def decorator(view_func):
        @functools.wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):
            if is_authenticated(request.user):
                return view_func(request, *args, **kwargs)
            return handle_redirect_to_login(
                request,
                redirect_field_name=redirect_field_name,
                login_url=login_url
            )
        return _wrapped_view
    if func:
        return decorator(func)
    return decorator
1215378
def _wrap_rpc_behavior(handler, fn):
    """"""
    if handler is None:
        return None

    if handler.request_streaming and handler.response_streaming:
        behavior_fn = handler.stream_stream
        handler_factory = grpc.stream_stream_rpc_method_handler
    elif handler.request_streaming and not handler.response_streaming:
        behavior_fn = handler.stream_unary
        handler_factory = grpc.stream_unary_rpc_method_handler
    elif not handler.request_streaming and handler.response_streaming:
        behavior_fn = handler.unary_stream
        handler_factory = grpc.unary_stream_rpc_method_handler
    else:
        behavior_fn = handler.unary_unary
        handler_factory = grpc.unary_unary_rpc_method_handler

    return handler_factory(
        fn(behavior_fn, handler.request_streaming,
           handler.response_streaming),
        request_deserializer=handler.request_deserializer,
        response_serializer=handler.response_serializer
    )
229625
def disable_logging(func):
    return func
    
    handler = logging.NullHandler()

    @wraps(func)
    def wrapper(*args, **kwargs):
        logger = logging.getLogger()
        logger.addHandler(handler)
        resp = func(*args, **kwargs)
        logger.removeHandler(handler)
        return resp
    return wrapper
647394
def authenticated_users(func):
    
    is_object_permission = "has_object" in func.__name__

    @wraps(func)
    def func_wrapper(*args, **kwargs):
        request = args[0]
        # use second parameter if object permission
        if is_object_permission:
            request = args[1]

        if not(request.user and request.user.is_authenticated):
            return False

        return func(*args, **kwargs)

    return func_wrapper