dfunckt / django-rules

Awesome Django authorization, without the database

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Autodiscover and model meta

hrbonz opened this issue · comments

I've been wrestling with this a bit thinking that I was doing something wrong. What I've been trying to do is use the rules auto discover function combined with defining model permissions in the Meta class.
I kept getting errors about my rules not being defined from the model and, indeed, if I got the
After trying a few things (change order of installed apps, redefine rules, etc), I decided to go heavy handed and trace the code using pdb. That's where I realized the auto discover code is called in "phase 3" after the models have been initialized (in phase 2).

I might be completely wrong but that would signal the fact that you can't indeed use both at the same time with the current mechanisms. Let me know if I misread the docs or am missing something obvious. If not, I think it would be possible to load the predicate through a lazy loader to get it to work properly without too much impact.

I'm using Django 2.2.7 and rules 2.1 with Python 3.7.3 on a Debian buster system.

Ok, fixed my problem on my own. As usual, it comes from a complete understanding of concepts in a new tool. Those model permissions are set through predicates so wouldn't benefit much from auto discovery (which I suppose is more to populate the default ruleset).
I imported the predicates in the model and applied them directly and everything works well now.
You can see my simple code aligning with the docs examples here. Here's my shell session (with ipython) with debug logging:

In [1]: from django.contrib.auth.models import User

In [2]: from books.models import Book

In [3]: adrian = User.objects.get(username='adrian')

In [4]: martin = User.objects.get(username='martin')

In [5]: guidetodjango = Book.objects.first()

In [7]: adrian.has_perm('books.change_book', guidetodjango)
Testing (is_book_author | is_group_member:editors)
  is_book_author = True
  (is_book_author | is_group_member:editors) = True
Out[7]: True

In [8]: adrian.has_perm('books.delete_book', guidetodjango)
Testing is_book_author
  is_book_author = True
Out[8]: True

In [9]: martin.has_perm('books.change_book', guidetodjango)
Testing (is_book_author | is_group_member:editors)
  is_book_author = False
  is_group_member:editors = True
  (is_book_author | is_group_member:editors) = True
Out[9]: True

In [10]: martin.has_perm('books.delete_book', guidetodjango)                                                         
Testing is_book_author
  is_book_author = False
Out[10]: False