Extended Django Self-bring permission description
The Support object permission is completed on the basis of not rewriting the self-contained permission for small projects.
Suggestions for amendment are welcome
Software support
jsonfield
Database
Create a new 3 table
From django.db import modelsfrom django.contrib.auth.models import Abstractuser, Group, userfrom jsonfield import jsonfie Ldclass Request (models. Model): request = models. Charfield (max_length=16, verbose_name= ' request type (uppercase) ') class meta:db_table = "Request" Verbose_name = "Requested Type" Verbose_name_plural = Verbose_name def __str__ (self): return Self.requestclass rolepermission (models. Model): role = models. Charfield (max_length=32, verbose_name= ' role group ') Table = models. Charfield (max_length=32, verbose_name= ' table name ') Request = models. Manytomanyfield (Request, verbose_name= ' requests ', related_name= ' re ',) Permission = Jsonfield (max_length=1024, Verbose_name = ' Permission condition ') class meta:db_table = "role_permission" verbose_name = "role Group permissions" verbose_name_plural = ver Bose_name def __str__ (self): return Self.roleclass Role (models. Model): Group = models. ForeignKey (Group, verbose_name= ' user group ', on_delete=models. CASCADE) roles = models. ManytomanyfiEld (rolepermission, verbose_name= ' role group permissions ', blank=true,related_name= ' roles ') class meta:db_table = "Role" Verbose_name = "role Group relationship" verbose_name_plural = Verbose_name def __str__ (self): return self.group.name
system/modelsRole 角色组关系 : 系统用户组 <--> 角色组权限Request 请求类型 : GET ,POSTRolePermission 角色组权限 : 角色 表名字 请求 权限条件(JSON类型)
The focus is on the Rolepermission table.
Example
Permission validation Code
Import jsonfrom system.models import rolefrom functools import wrapsfrom django.shortcuts import httpresponsedef role_per Mission_get_list (function): "" "List page CONTROL permission:p Aram function:: Return:" "" @wraps (function) def wrapped ( Self): User = Self.request.user groups = [x[' name '] for x in Self.request.user.groups.values ()] Reque St_type = Self.request.method model = str (self.model._meta). Split (".") [1] filter_dict = {} not_list = [' page ', ' order_by ', ' Csrfmiddlewaretoken '] for K, V in Dict (self.req Uest. GET). Items (): If [i-I in V if I! = "] and (k not in not_list): If ' __in ' in K: Filter_dict[k] = v else:filter_dict[k] = v[0] If not user.is_superuser: Role_groups = Role.objects.filter (group__name__in=groups). Values_list (' roles__table ', ' Roles__reQuest__request ', ' roles__permission ') Permission_dict = {} for I in role_groups:if i[0] = = Model and i[1] = = Request_type: Permission_dict = Json.loads (i[2]) if Permission_dict:if filter_dict: For K, V in Permission_dict.items (): If ' __in ' in k:k1 = K.R Eplace (' __in ', ') if ' __gt ' in k:k1 = K.replace (' __gt ', ') If ' __lt ' in k:k1 = K.replace (' __lt ', ') Else: K1 = k if K1 in list (Filter_dict.keys ()): Del Filter_di CT[K1] If Filter_dict:filter_dict.update (**permission_dict) Else Print (' Empty after query condition processing, default permissions ') Filter_dict = Permission_dict Else: Print (' query condition is NULL, default permissions ') Filter_dict = permission_dict else:print (' No Permissions ') Filter_dict = {' id ':-1} self.filter_dict = filter_dict result = function (self) return Resul T return wrappeddef role_permission_detail (function): "" "Details page CONTROL permission:p Aram function:: Return:" "" @wr APS (function) def wrapped (self, request, *args, **kwargs): User = Self.request.user if not User.is_superu ser:groups = [x[' name '] for x in Self.request.user.groups.values ()] Request_type = Self.request.met Hod model = str (self.model._meta). Split (".") [1] pk = Self.kwargs.get (Self.pk_url_kwarg, None) role_groups = Role.objects.filter (group__name__in= Groups). Values_list (' roles__table ', ' Roles__request__request ', ' roles__permission ') permission_dict = {} for I in role_groups:if i[0] = = Model and i[1] = = Request_type:permission_dict = Json.loads (i[2]) permission_dict[' id '] = PK obj = Self.model.objects.filter (**permission_dict). Count () if not Obj:return Htt Presponse (status=403) result = function (self, request, *args, **kwargs) return result return wrappeddef R Ole_permission_update_delete (function): "" "Details page CONTROL permission:p Aram function:: Return:" "" @wraps (function) def wrapped (self, request): User = Self.request.user if not user.is_superuser:groups = [x[' name ' ] for x in Self.request.user.groups.values ()] Request_type = Self.request.method model = str (self.mo Del._meta). Split (".") [1] PK = self.request.POST.get (' nid ', None) role_groups = Role.objects.filter (group__name__in=groups). V Alues_list (' roles__table ', ' roles__reques T__request ', ' roles__permission ') Permission_dict = {} for I in role_groups:if i[0] = = Model and i[1] = = Request_type: Permission_dict = Json.loads (i[2]) permission_dict[' id '] = PK obj = self.model.objects. Filter (**permission_dict). Count () if not Obj:ret = {' Status ': None, ' Error ': ' no permission, deny ', ' msg ': ' without permission, rejected '} return HttpResponse (Json.dumps (ret)) result = function (self, request ) return result return wrapped
CBV Example
class AssetChange(LoginRequiredMixin, UpdateView): model = Ecs @role_permission_detail def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) @role_permission_update_delete def form_valid(self, form): self.object = form.save() return super().form_valid(form)
class AssetDetail(LoginRequiredMixin, DetailView): model = Ecs @role_permission_detail def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs)
class AssetDel(LoginRequiredMixin, View): model = Ecs @role_permission_update_delete def post(self, request): pass
Django extends its own permissions so that it supports object permissions