Django permissions via related objects permissions
Asked Answered
G

1

2

I am relatively new to Django and I'm looking for some guidance in how to setup permissions in a certain way. Basically I have an app that consists of a couple of models similar to this:

class Project(models.Model):
    name = models.CharField(max_length=100)
    users = models.ManyToManyField(CustomUser, related_name="projects")

class Task(models.Model):
    name = models.CharField(max_length=100)
    project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name="tasks")

class Asset(models.Model):
    name = models.CharField(max_length=100)
    project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name="assets")

My idea is that if a user is "assigned" to a project (via M2M field), that user will have access to all assets and tasks that are related to that Project. I have looked into django-guardian for per-object permissions and I think that could be the way to go, but to me it seems like I then would have to setup those permissions on each model..?

It feels like this should be a pretty common way of setting up permissions for any project-based app but I have a hard time finding similar examples and starting to wonder if I'm overthinking this or looking in the wrong direction?

Thank you, Jonas

Garlic answered 2/11, 2020 at 10:0 Comment(0)
C
2

You can use django-rules to take advantage of object-level permissions without a database; with it, you can add permissions in many levels - models, views, templates, admin or DRF.

So, you'd need to create a predicate like

@rules.predicate
def is_project_manager(user, project):
     return project.users == user

which will return True if the project's manager is the given user, False otherwise.

Then, to add it in a model, you'd do something like

import rules
from rules.contrib.models import RulesModel

class Project(RulesModel):
    class Meta:
        rules_permissions = {
            "add": rules.is_project_manager,
            "read": rules.is_authenticated,
        }

There's ofc other considerations to attend to but I think that gives an overview of how it works.

Castanon answered 2/11, 2020 at 10:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.