dfunckt / django-rules

Awesome Django authorization, without the database

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to identify the rule or permission name with in predicator?

ramana-kk opened this issue · comments

Hi, Is it possible to get rule or permission name within predicator function? Becuase, I have written a generic function which checks and provides True or False. However, it needs the permission name.

Is there any solution?

There is no good way currently, though I did play around a bit a while ago to refactor rules in order to support this but it turns out it’s a pretty invasive change I’m not sure I want to pursue. More context and link to the branch if you want to play with it here: #44

Closing as a duplicate of that issue, feel free to continue the discussion there

It's not ideal, but you might be able to use partials to bind the permission name to your function. e.g.,

def generic(obj, target, *, perm_name):
    ...

can_view_book = predicate(partial(generic, perm_name='can_view_book'))
can_edit_book = predicate(partial(generic, perm_name='can_edit_book'))
# etc...

Thanks @rpkilby for the quick suggestion.

I am getting the following error as * is not allowed.

def has_permission(user, perm_obj, *,  perm_name):
                                    ^

SyntaxError: invalid syntax

if I remove the * argument, I am getting error ...

assert num_args <= 2, 'Incompatible predicate.'

AssertionError: Incompatible predicate.

Kindly advice.

Hm. rules might be checking the signature. You could also just wrap in another function.

def generic(obj, target, perm_name):
    ...

@predicate
def can_view_book(obj, target): 
    return generic(obj, target, perm_name='can_view_book')

So, I need to create as many wrapper functions as I have the tags. So there is no point in generic function.

So currently, I am passing a string to predicate in my view as fn. i.e

@permission_required('perm_check', fn='Executes_key2')
def progress_dashboard(emp):

here, perm_check is rule permission. "Exceutes_key2' is key which is getting passed to predicate to identify what permissions to check.