Issue with Django rules

623 Views Asked by At

I'm working with rules library from Django and I don't overcome to define rules for specific menu.

Rules library is available there : rules library

I'm logged as admin in my web application.

I have a menus.py file like this :

class AdminMenuItem(MenuItem):
    def check(self, request):
        return self.allow(request.user)

    @staticmethod
    def allow(user):
        return user.has_perm('app.access_admin_menu')

Menu.add_item('admin', MenuItem('Admin', '#admin', children=settings_children,
                            check=lambda request: AdminMenuItem.allow(request.user)))

settings_children = (
    ...
    AdminMenuItem("Manage Animals", reverse("animal-list-crud"), weight=10),
    AdminMenuItem("Statistics", reverse("statistics"), weight=140)
)

Then I defined in my rules.py file :

from rules.permissions import add_perm
from rules.predicates import predicate


@predicate
def is_admin(user):
    if user.is_anonymous:
        return False
    return True if user.profile.type == 'ED' and user.profile.role == 'AD' else False

# Rules for admin_menu.
add_perm('app.access_admin_menu', is_admin)

# Rules for animal.
add_perm('app.view_animal', is_admin)
add_perm('app.add_animal', is_admin)
add_perm('app.change_animal', is_admin)
add_perm('app.delete_animal', is_admin)

It works fine for Animal menu (it's a CRUD part). But when I try to access to the statistics part (which is not a CRUD), I have an error 403 Access forbidden.

I forgot something in my code ?

Thank you

1

There are 1 best solutions below

0
Essex On

I found the solution. The code exposed above is good, but it missed something in my main.py code.

class StatisticsView(PermissionRequiredMixin, View):
    """ Render the statistics page with a form to generate various stats """

    permission_required = 'app.access_statistics'
    ...

In my class, I forgot the attribute PermissionRequiredMixin with permission_required = 'app.access_statistics'. By adding both elements, it works now !