Replacement for django.contrib.auth.decorators.permission_required that
    returns 403 Forbidden if the user is already logged in.
774269
def permission_required(perm, login_url=None):
    

    return user_passes_test(lambda u: u.has_perm(perm), login_url=login_url)
1089404
def has_permission(self, request, view):
        
        url_username = request.parser_context.get('kwargs', {}).get('username', '')
        if request.user.username.lower() != url_username.lower():
            if request.user.is_staff:
                return False  # staff gets 403
            raise Http404()
        return True
1259106
def __get_permissions(self, res, **kwargs):
        
        response = res._(**kwargs)
        return response.get('permissions', None)
80395
def permission_denied(request, template_name=None, extra_context=None):
    
    if template_name is None:
        template_name = ('403.html', 'authority/403.html')
    context = {
        'request_path': request.path,
    }
    if extra_context:
        context.update(extra_context)
    return HttpResponseForbidden(loader.render_to_string(
        template_name=template_name,
        context=context,
        request=request,
    ))
394506
def requires_user(fn):
        
        @functools.wraps(fn)
        def wrap(*args, **kwargs):

            subject = WebYosai.get_current_subject()

            if subject.identifiers is None:
                msg = ("Attempting to perform a user-only operation.  The "
                       "current Subject is NOT a user (they haven't been "
                       "authenticated or remembered from a previous login). "
                       "ACCESS DENIED.")
                raise WebYosai.get_current_webregistry().raise_unauthorized(msg)
            return fn(*args, **kwargs)
        return wrap
1104694
def auth_basic(check, realm="private", text="Access denied"):
    '''  '''
    def decorator(func):
        def wrapper(*a, **ka):
            user, password = request.auth or (None, None)
            if user is None or not check(user, password):
                err = HTTPError(401, text)
                err.add_header('WWW-Authenticate', 'Basic realm="%s"' % realm)
                return err
            return func(*a, **ka)
        return wrapper
    return decorator
95271
def auth_required(self, view):
        

        @functools.wraps(view)
        def decorated(*args, **kwargs):
            log.info("Trying to get access to protected resource: '%s'", view.__name__)
            if request.method == 'POST':
                token = request.form['token']
                if self.development or self.authenticated(token):
                    return view(*args, **kwargs)
                else:
                    log.warning("User has not been authorized to get access to resource: %s", view.__name__)
            else:
                log.warning("Bad request type! Expected 'POST', actual '%s'", request.method)

            return abort(403)

        return decorated
994524
def has_permission(
    permission,
    context=None,
):
    
    def wrapper(fn):
        @wraps(fn)
        async def wrapped(*args, **kwargs):
            request = args[-1]
            if not isinstance(request, web.BaseRequest):
                msg = ("Incorrect decorator usage. "
                       "Expecting `def handler(request)` "
                       "or `def handler(self, request)`.")
                raise RuntimeError(msg)

            await check_permission(request, permission, context)
            return await fn(*args, **kwargs)

        return wrapped

    warnings.warn("has_permission decorator is deprecated, "
                  "use check_permission instead",
                  DeprecationWarning)
    return wrapper
1069404
def anonymous_required(function=None, redirect_url=None):
    
    if not redirect_url:
        redirect_url = settings.LOGIN_REDIRECT_URL

    actual_decorator = user_passes_test(
        is_anonymous,
        login_url=redirect_url,
        redirect_field_name=None
    )

    if function:
        return actual_decorator(function)
    return actual_decorator
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
1264756
def require_auth(request: Request, exceptions: bool=True) -> User:
    
    if not request.user or not request.user.is_authenticated:
        if exceptions:
            raise NotAuthenticated()
        return None
    return request.user
1166927
def perform_permissions_check(self, user, obj, perms):
        
        return self.request.forum_permission_handler.can_add_post(obj, user)
1095083
def _auth_required():
    

    login_mechanisms = (
        ('token', lambda: _check_token()),
        ('session', lambda: current_user.is_authenticated),
    )

    def wrapper(fn):
        @wraps(fn)
        def decorated_view(*args, **kwargs):
            for method, mechanism in login_mechanisms:
                if mechanism and mechanism():
                    return fn(*args, **kwargs)
            return security._unauthorized_callback()
        return decorated_view
    return wrapper
671488
def anonymous_required(view, redirect_to=None):
    
    if redirect_to is None:
        redirect_to = settings.LOGIN_REDIRECT_URL

    @wraps(view)
    def wrapper(request, *a, **k):
        if request.user and request.user.is_authenticated():
            return HttpResponseRedirect(redirect_to)
        return view(request, *a, **k)
    return wrapper
910688
def requires_auth(func):
    """"""
    @wraps(func)
    def auth_wrapper(self, *args, **kwargs):
        auth = False
        if hasattr(self, '_session'):
            auth = (self._session.auth or
                    self._session.headers.get('Authorization'))

        if auth:
            return func(self, *args, **kwargs)
        else:
            from .models import GitHubError
            # Mock a 401 response
            r = generate_fake_error_response(
                '{"message": "Requires authentication"}'
            )
            raise GitHubError(r)
    return auth_wrapper
14874
def require_auth(view_func):
    
    from horizon.exceptions import NotAuthenticated

    @functools.wraps(view_func, assigned=available_attrs(view_func))
    def dec(request, *args, **kwargs):
        if request.user.is_authenticated:
            return view_func(request, *args, **kwargs)
        raise NotAuthenticated(_("Please log in to continue."))
    return dec
1370783
def _populate_permissions(resources, content_type_id):
    
    from django.contrib.auth.models import Permission
    # read the whole auth_permission table into memory
    db_perms = [perm.codename for perm in Permission.objects.all()]

    for resource in resources:
        # get all resource's permissions that are not already in db
        perms = [perm for perm in resource.access_controller.get_perm_names(resource) if perm not in db_perms]
        for perm in perms:
            _save_new_permission(perm, content_type_id)