Skip to content

Commit

Permalink
fix(generic): move permission check to individual rows
Browse files Browse the repository at this point in the history
This allows us to use the table without a model set and with records of
different models
  • Loading branch information
b1rger committed Mar 28, 2024
1 parent ea58f54 commit 7e56d6c
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 16 deletions.
8 changes: 1 addition & 7 deletions apis_core/apis_entities/tables.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from apis_core.generic.helpers import permission_fullname
from apis_core.generic.tables import GenericTable, ActionColumn


Expand All @@ -8,16 +7,11 @@ class DuplicateColumn(ActionColumn):
"""

template_name = "columns/duplicate.html"
permission = "create"


class AbstractEntityTable(GenericTable):
noduplicate = DuplicateColumn()

class Meta(GenericTable.Meta):
sequence = ("...", "view", "edit", "delete", "noduplicate")

def before_render(self, request):
super().before_render(request)
if model := getattr(self.Meta, "model"):
if not request.user.has_perm(permission_fullname("create", model)):
self.columns.hide("noduplicate")
18 changes: 9 additions & 9 deletions apis_core/generic/tables.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,20 @@ class ActionColumn(CustomTemplateColumn):
verbose_name = ""
attrs = {"td": {"style": "width:1%;"}}

def render(self, record, table, *args, **kwargs):
if permission := getattr(self, "permission", False):
if not table.context.request.user.has_perm(permission_fullname(permission, record)):
return ""
return super().render(record, table, *args, **kwargs)


class DeleteColumn(ActionColumn):
"""
A column showing a delete button
"""

template_name = "columns/delete.html"
permission = "delete"


class EditColumn(ActionColumn):
Expand All @@ -52,6 +59,7 @@ class EditColumn(ActionColumn):
"""

template_name = "columns/edit.html"
permission = "change"


class ViewColumn(ActionColumn):
Expand All @@ -60,6 +68,7 @@ class ViewColumn(ActionColumn):
"""

template_name = "columns/view.html"
permission = "view"


class DescriptionColumn(CustomTemplateColumn):
Expand All @@ -85,12 +94,3 @@ class GenericTable(tables.Table):
class Meta:
fields = ["id", "desc"]
sequence = ("...", "view", "edit", "delete")

def before_render(self, request):
if model := getattr(self.Meta, "model"):
if not request.user.has_perm(permission_fullname("delete", model)):
self.columns.hide("delete")
if not request.user.has_perm(permission_fullname("change", model)):
self.columns.hide("edit")
if not request.user.has_perm(permission_fullname("view", model)):
self.columns.hide("view")

0 comments on commit 7e56d6c

Please sign in to comment.