Checks if the Authorization barer exists. Otherwise throw 401
    :param func:
    :return:
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
764884
def check_role(*roles, **args_map):
    
    def f1(func, roles=roles):
        @wraps(func)
        def f2(*args, **kwargs):
            from uliweb import request, error
            
            arguments = {}
            for k, v in args_map.items():
                if v in kwargs:
                    arguments[k] = kwargs[v]
            if not has_role(request.user, *roles, **arguments):
                error(_("You have no roles to visit this page."))
            return func(*args, **kwargs)
        return f2
    return f1
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
29831
def require_auth(function):
    
    @functools.wraps(function)
    def wrapper(self, *args, **kwargs):
        if not self.access_token():
            raise MissingAccessTokenError
        return function(self, *args, **kwargs)
    return wrapper
231349
def defer_sync(self, func):
        
        latch = Latch()
        def wrapper():
            try:
                latch.put(func())
            except Exception:
                latch.put(sys.exc_info()[1])
        self.defer(wrapper)
        res = latch.get()
        if isinstance(res, Exception):
            raise res
        return res
1329452
def requires_auth(f):
    

    @wraps(f)
    def requires_auth_decorator(*args, **kwargs):

        try:
            authenticate_http_request()
        except PyMacaronException as e:
            return e.http_reply()

        return f(*args, **kwargs)

    return requires_auth_decorator
73242
def check_public_ok(func):
    

    def wrapper(request, *args, **kwargs):
        default_to_open = getattr(settings, 'DEFAULT_TO_OPEN_READ', False)
        database_name = kwargs.get('database_name', "")
        collection_name = kwargs.get('collection_name', "")
        if not default_to_open:
            if not database_name or not collection_name:
                return HttpResponse(unauthorized_json_response(),
                                    content_type="application/json")
            try:
                pub_read_api = PublicReadAPI.objects.get(
                    database_name=database_name, collection_name=collection_name)
            except PublicReadAPI.DoesNotExist:
                return HttpResponse(unauthorized_json_response(),
                                    content_type="application/json")

            # If search keys have been limited...
            if pub_read_api.search_keys:
                search_key_list = shlex.split(pub_read_api.search_keys)
                keys = []
                for k in request.GET.keys():

                    if k not in search_key_list:
                        message = "Search key %s is not allowed." % (k)

                        body = {"code": 400,
                                "message": k,
                                "errors": [message, ]}

                        return HttpResponse(json.dumps(body, indent=4, ),
                                            content_type="application/json")
        return func(request, *args, **kwargs)

    return update_wrapper(wrapper, func)
969511
def login_required(func, permission=None):
    
    @wraps(func)
    def decorated_function(*args, **kwargs):
        if not check_token():
            return login()
        elif not nago.core.has_access(session.get('token')):
            return http403()
        return func(*args, **kwargs)
    return decorated_function
1271173
def perm_check(function, perm_check_func=_perm_check_func, raise_exception=False):
    
    def real_decorator(func):
        def wrapped(request, db, col, cmd, *args, **kwargs):
            bPermPass = perm_check_func(request, db, col, cmd) if perm_check_func else True
            if raise_exception and (not bPermPass):
                raise PermissionDenied
            return func(request, db, col, cmd, *args, **kwargs) if bPermPass else {"error": "permission disallowed"}

        return wrapped
    return real_decorator(function)
344660
def is_auth_alive(self):
        ""
        model = self.model('ir.model')
        try:
            model.search([], None, 1, None)
        except ClientError as err:
            if err and err.message['code'] == 403:
                return False
            raise
        except Exception:
            raise
        else:
            return True
152220
def require(self, lock, guard_func, *guard_args, **guard_kw):
        
        def decorator(f):
            @wraps(f)
            def wrapper(*args, **kw):
                if self.granted(lock):
                    self.msg('Granted {}'.format(lock))
                    return f(*args, **kw)
                if guard_func(*guard_args, **guard_kw) and self.acquire(lock):
                    return f(*args, **kw)
                return None
            return wrapper
        return decorator
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
986735
def allow_staff_or_superuser(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 request.user.is_staff or request.user.is_superuser:
            return True

        return func(*args, **kwargs)

    return func_wrapper
15937
def require_admin(func):
    

    @wraps(func)
    @require_login
    def decorated(*args, **kwargs):
        user = current_user()
        if user and user.is_admin:
            return func(*args, **kwargs)
        else:
            return Response(
                'Forbidden', 403
            )

    return decorated
924033
def run_func(self, func, load):
        '''
        
        '''
        # Don't honor private functions
        if func.startswith('__'):
            # TODO: return some error? Seems odd to return {}
            return {}, {'fun': 'send'}
        # Run the func
        if hasattr(self, func):
            try:
                start = time.time()
                ret = getattr(self, func)(load)
                log.trace(
                    'Master function call %s took %s seconds',
                    func, time.time() - start
                )
            except Exception:
                ret = ''
                log.error('Error in function %s:\n', func, exc_info=True)
        else:
            log.error(
                'Received function %s which is unavailable on the master, '
                'returning False', func
            )
            return False, {'fun': 'send'}
        # Don't encrypt the return value for the _return func
        # (we don't care about the return value, so why encrypt it?)
        if func == '_return':
            return ret, {'fun': 'send'}
        if func == '_pillar' and 'id' in load:
            if load.get('ver') != '2' and self.opts['pillar_version'] == 1:
                # Authorized to return old pillar proto
                return ret, {'fun': 'send'}
            return ret, {'fun': 'send_private', 'key': 'pillar', 'tgt': load['id']}
        # Encrypt the return
        return ret, {'fun': 'send'}
217019
async def syscall(self, func, ignoreException = False):
        
        ev = await self.syscall_noreturn(func)
        if hasattr(ev, 'exception'):
            if ignoreException:
                return
            else:
                raise ev.exception[1]
        else:
            return ev.retvalue
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