Django comes with a standard `model level` permission system. You can check whether users are logged-in and have privileges to act on things model wise (can a user add a project? can a user view projects?). Django-guardian adds a `row level` permission system. Now not only can you
(request, project_pk, perms=('view_project',), defer=False)
| 6 | from app import models |
| 7 | |
| 8 | def get_and_check_project(request, project_pk, perms=('view_project',), defer=False): |
| 9 | """ |
| 10 | Django comes with a standard `model level` permission system. You can |
| 11 | check whether users are logged-in and have privileges to act on things |
| 12 | model wise (can a user add a project? can a user view projects?). |
| 13 | Django-guardian adds a `row level` permission system. Now not only can you |
| 14 | decide whether a user can add a project or view projects, you can specify exactly |
| 15 | which projects a user has or has not access to. |
| 16 | |
| 17 | This brings up the reason the following function: tasks are part of a project, |
| 18 | and it would add a tremendous headache (and redundancy) to specify row level permissions |
| 19 | for each task. Instead, we check the row level permissions of the project |
| 20 | to which a task belongs to. |
| 21 | |
| 22 | Perhaps this could be added as a django-rest filter? |
| 23 | |
| 24 | Retrieves a project and raises an exception if the current user |
| 25 | has no access to it. |
| 26 | """ |
| 27 | try: |
| 28 | if defer: |
| 29 | project = models.Project.objects.only('id').get(pk=project_pk, deleting=False) |
| 30 | else: |
| 31 | project = models.Project.objects.get(pk=project_pk, deleting=False) |
| 32 | |
| 33 | for perm in perms: |
| 34 | if not request.user.has_perm(perm, project): raise ObjectDoesNotExist() |
| 35 | except ObjectDoesNotExist: |
| 36 | raise exceptions.NotFound() |
| 37 | return project |
| 38 | |
| 39 | def check_project_perms(request, project, perms=('view_project',)): |
| 40 | for perm in perms: |