Web 開發中權限管理必不可少,不一樣的角色有不一樣的權限,所謂權限也能夠理解爲是否能訪問某些特定頁面。html
下面咱們來實現一個通用權限框架:python
用戶表採用拓展 auth
模塊方式,不用原有的 auth_user
表,而是本身建立一個 UserProfile
表,它在 auth
模塊基礎上進行拓展,同時賦予權限操做。git
from django.db import models from django.contrib.auth.models import User, AbstractUser # 導入 AbstractUser 類 from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser, PermissionsMixin # 權限 ) class UserProfileManager(BaseUserManager): def create_user(self, email, name, password=None): """建立普通帳戶""" if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), name=name, ) user.set_password(password) # set_password():auth 模塊中方法,用於修改密碼,將密碼 md5 加密,具體用法可參考 Django auth 模塊 user.save(using=self._db) # 保存 return user def create_superuser(self, email, name, password): """建立超級用戶""" user = self.create_user( email, password=password, name=name, ) user.is_superuser = True user.save(using=self._db) return user class UserProfile(AbstractBaseUser, PermissionsMixin): email = models.EmailField( verbose_name='郵箱', max_length=255, unique=True, default='hj@qq.com', ) name = models.CharField(max_length=64, verbose_name='姓名') is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=True) detail = models.OneToOneField('UserDetail', verbose_name='員工信息', on_delete=models.CASCADE, blank=True, null=True) role = models.ManyToManyField('Role', blank=True) objects = UserProfileManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] def __str__(self): return self.get_username() def get_full_name(self): # The user is identified by their email address return self.email def get_short_name(self): # The user is identified by their email address return self.email class Meta: verbose_name_plural = '用戶表' # 配置權限 permissions = ( ('app_staff_detail', '能夠查看員工我的信息的數據'), ('app_fina_state', '能夠查看財務報表'), ('app_payroll', '能夠查看工資條'), )
另外在生成 UserProfile
表以前,須要在 settings
中指定路徑:github
AUTH_USER_MODEL = 'app.UserProfile'
配置權限列表 permission_dict
:django
# 鍵:app 名字 + url_name # 值:請求 URL 地址,請求方法(get、post),[]、{} 皆爲過濾條件 from app.my_primission import permission_hook # app 名字_(url_name) perm_dic = { # 'app_table_list': ['table_obj_list', 'GET', [], {}, permission_hook.view_my_own_customers], 'app_staff_detail': ['staff_detail', 'GET', [], {}], # 能夠查看員工我的信息 'app_fina_state': ['fina_state', 'GET', [], {}], # 能夠查看財務報表 'app_payroll': ['payroll', 'GET', [], {}], # 能夠查看工資條 }
核心部分 my_primission.py
:app
from django.urls import resolve from django.shortcuts import render,redirect,HttpResponse from kingadmin.permission_list import perm_dic from django.conf import settings def perm_check(*args, **kwargs): #1.獲取當前請求的url #2.把url解析成url_name(經過resolve) #3.判斷用戶是否已登陸(user.is_authenticated()) #3.拿url_name到permission_dict去匹配,匹配時要包括請求方法和參數 #4.拿匹配到可權限key,調用user.has_perm(key) match_results = [None,] request = args[0] resolve_url_obj = resolve(request.path) # 經過resolve解析出當前訪問的url_name current_url_name = resolve_url_obj.url_name print('---perm:',request.user,request.user.is_authenticated(),current_url_name) #match_flag = False match_key = None #判斷用戶是否登陸 if request.user.is_authenticated() is False: return redirect(settings.LOGIN_URL) for permission_key,permission_val in perm_dic.items(): #key和value(值有四個參數): 好比 'crm_table_index': ['table_index', 'GET', [], {}, ] per_url_name = permission_val[0] per_method = permission_val[1] perm_args = permission_val[2] perm_kwargs = permission_val[3] #若是當前訪問的url_name匹配上了權限裏面定義的url_name if per_url_name == current_url_name: #url_name匹配上,接着匹配方法(post,get....) if per_method == request.method: # if not perm_args: #if no args defined in perm dic, then set this request to passed perm #逐個匹配參數,看每一個參數是否都能對應的上。 args_matched = False #for args only for item in perm_args: #經過反射獲取到request.xxx函數 這裏request_methon_func = request.GET/request.POST request_method_func = getattr(request,per_method) if request_method_func.get(item,None): # request字典中有此參數 args_matched = True else: print("arg not match......") args_matched = False break # 有一個參數不能匹配成功,則斷定爲假,退出該循環。由於可能有不少參數,必須全部參數都同樣才匹配成功 else: # perm_dic裏面的參數可能定義的就是空的,就走這裏 args_matched = True #匹配有特定值的參數 kwargs_matched = False for k,v in perm_kwargs.items(): request_method_func = getattr(request, per_method) arg_val = request_method_func.get(k, None) # request字典中有此參數 print("perm kwargs check:",arg_val,type(arg_val),v,type(v)) if arg_val == str(v): #匹配上了特定的參數 及對應的 參數值, 好比,須要request 對象裏必須有一個叫 user_id=3的參數 kwargs_matched = True else: kwargs_matched = False break # 有一個參數不能匹配成功,則斷定爲假,退出該循環。 else: kwargs_matched = True match_results = [args_matched,kwargs_matched] print("--->match_results ", match_results) #列表裏面的元素都爲真 if all(match_results): #都匹配上了 match_key = permission_key break if all(match_results): # 主要是獲取到app_name,match_key = 'app_staff_detail' app_name, *per_name = match_key.split('_') # app_name: app, per_name=['staff', 'detail'] print("--->matched ", match_results, match_key) print(app_name, *per_name) perm_obj = '%s.%s' % (app_name, match_key) # per_obj = app.app_staff_detail print("perm str:", perm_obj) print('當前用戶全部權限', request.user.get_all_permissions()) # {'app.app_staff_detail', 'app.app_fina_state'} # 使用 Permission 的 has_permission() 方法檢查是否有權限,更多權限可在 auth_permission 表中查看 if request.user.has_perm(perm_obj): print('當前用戶有此權限') return True else: print('當前用戶沒有該權限') return False else: print("未匹配到權限項,當前用戶無權限") def check_permission(func): def inner(*args,**kwargs): if not perm_check(*args,**kwargs): request = args[0] return render(request,'kingadmin/page_403.html') return func(*args,**kwargs) return inner
權限鉤子函數:框架
def view_my_own_customers(request): print("執行權限鉤子函數.....") if str(request.user.id) == request.GET.get('consultant'): print("訪問本身建立的用戶,容許") return True else: return False
使用:ide
@login_required @check_permission def staff_detail(request): """員工我的信息""" user_obj = models.UserProfile.objects.all() return render(request, 'staff_detail.html', {'user_obj': user_obj})
lila 沒有查看員工信息權限,所以訪問是 403:函數
hj 是老闆,全部頁面都能查看,有權限:post
具體權限開關可在 admin
中配置: