python專案篇-許可權二
阿新 • • 發佈:2019-01-04
許可權粒度控制 簡單控制: {% if "users/add" in permissions_list%} 擺脫表控制 更改資料庫結構 class Permission(models.Model): title=models.CharField(max_length=32) url=models.CharField(max_length=32) action=models.CharField(max_length=32,default="") group=models.ForeignKey("PermissionGroup",default=1) def __str__(self):return self.title class PermissionGroup(models.Model): title = models.CharField(max_length=32) def __str__(self): return self.title 登入驗證: permissions = user.roles.all().values("permissions__url","permissions__group_id","permissions__action").distinct() 構建permission_dict permissions: [ {'permissions__url': '/users/add/', 'permissions__group_id': 1, 'permissions__action': 'add'}, {'permissions__url': '/roles/', 'permissions__group_id': 2, 'permissions__action': 'list'}, {'permissions__url': '/users/delete/(\\d+)', 'permissions__group_id': 1, 'permissions__action': 'delete'}, {'permissions__url': 'users/edit/(\\d+)', 'permissions__group_id': 1, 'permissions__action': 'edit'} ] permission_dict { 1: { 'urls': ['/users/', '/users/add/', '/users/delete/(\\d+)', 'users/edit/(\\d+)'], 'actions': ['list', 'add', 'delete', 'edit']}, 2: { 'urls': ['/roles/'], 'actions': ['list']} } 中間價校驗許可權: permission_dict=request.session.get("permission_dict") for item in permission_dict.values(): urls=item['urls'] for reg in urls: reg="^%s$"%reg ret=re.match(reg,current_path) if ret: print("actions",item['actions']) request.actions=item['actions'] return None return HttpResponse("沒有訪問許可權!")