如何过滤用户可以通过其组访问的页面

问题描述 投票:0回答:1

我正在实现一个搜索功能,该功能返回用户可以通过其组访问的页面。在编辑时,页面通过Wagtail管理页面隐私设置来设置这些设置。

例如,页面只能对“编辑者”组中的用户可见。因此,当不在编辑器组中的用户搜索此页面时,应将其过滤掉。

如何以这种方式有效过滤用户无法访问的页面?我找不到任何明确的方法来进行此操作。

wagtail wagtail-search
1个回答
0
投票

为了搜索引擎优化目的回答我自己的问题。

研究了Wagtail源代码后,我发现Wagtail在内部使用了PageViewRestriction模型。

我最终使用此代码段解决了我的问题:

from wagtail.core.models import Page, PageViewRestriction

def filter_pages(user):
    pages = Page.objects.live()

    # Unauthenticated users can only see public pages
    if not user.is_authenticated:
        pages = pages.public()
    # Superusers can implicitly view all pages. No further filtering required
    elif not user.is_superuser:
        # Get all page ids where the user's groups do NOT have access to
        disallowed_ids = PageViewRestriction.objects.exclude(groups__id=request.user.groups.all()).values_list("page", flat=True)
        # Exclude all pages with disallowed ids
        pages = pages.exclude(id__in=disallowed_ids)

    return pages
© www.soinside.com 2019 - 2024. All rights reserved.