Django 權限控制初探

經過django默認的權限管理來管理權限便可,咱們在基礎上進行一些第三方擴展html

下面給出一個權限控制的示例,這裏url路徑轉發的時候須要添加默認的 別名,咱們須要修改的也是這些別名
前端

models.pypython

class UserProfile(models.Model):
    user = models.OneToOneField(User) 
    name = models.CharField(max_length=64)
    school = models.ForeignKey('School')

    def __unicode__(self):
        return self.name
    class Meta:
        permissions =(('view_customer_list', u"能夠查看客戶列表"),
                      ('view_customer_info',u"能夠查看客戶詳情"),
                      ('edit_own_customer_info',u"能夠修改本身的客戶信息"),
                      ('view_teacher_list',u"能夠查看老師列表"),
                      ('view_school_list',u"能夠查看學校列表"),
                      )


permissions.py 這邊採起的是裝飾的寫法django

# -*- coding:utf-8 -*-
# Author:Alex Li
from django.core.urlresolvers import resolve
from django.shortcuts import render
perm_dic = {
    'view_customer_list': ['customer_list','GET',[]],
    'view_customer_info': ['customer_detail','GET',[]],
    ''''''
    '''後端參數'''
    'edit_own_customer_info': ['customer_detail','POST',[]],
}

def perm_check(*args,**kwargs):
    request = args[0]
    url_resovle_obj = resolve(request.path_info)
    current_url_namespace = url_resovle_obj.url_name
    #app_name = url_resovle_obj.app_name #use this name later
    print("url namespace:",current_url_namespace)
    matched_flag = False # find matched perm item
    matched_perm_key = None
    if current_url_namespace is not None:#if didn't set the url namespace, permission doesn't work
        print("find perm...")
        for perm_key in perm_dic:
            perm_val = perm_dic[perm_key]
            if len(perm_val) == 3:#otherwise invalid perm data format
                url_namespace,request_method,request_args = perm_val
                print(url_namespace,current_url_namespace)
                if url_namespace == current_url_namespace: #matched the url
                    if request.method == request_method:#matched request method
                        if not request_args:#if empty , pass
                            matched_flag = True
                            matched_perm_key = perm_key
                            print('mtched...')
                            break #no need looking for  other perms
                        else:
                            for request_arg in request_args: #might has many args
                                request_method_func = getattr(request,request_method) #get or post mostly
                                #print("----->>>",request_method_func.get(request_arg))
                                if request_method_func.get(request_arg) is not None:
                                    matched_flag = True # the arg in set in perm item must be provided in request data
                                else:
                                    matched_flag = False
                                    print("request arg [%s] not matched" % request_arg)
                                    break #no need go further
                            if matched_flag == True: # means passed permission check ,no need check others
                                print("--passed permission check--")
                                matched_perm_key = perm_key
                                break

    else:#permission doesn't work
        '''這邊若是 沒有定義url別名的話,那麼爲了不影響全局,就讓它默認就有權限'''
        return True

    if matched_flag == True:
        #pass permission check
        perm_str = "crm.%s" %(matched_perm_key) #crm.view_customer_list
        if request.user.has_perm(perm_str):
            print("\033[42;1m--------passed permission check----\033[0m")
            return True
        else:
            print("\033[41;1m ----- no permission ----\033[0m")
            print(request.user,perm_str)
            return False
    else:
        print("\033[41;1m ----- no matched permission  ----\033[0m")
        '''全部的爲空的狀況,也沒有放過'''
        return False

def check_permission(func):
    def wrapper(*args,**kwargs):
        print('---start check perm---')
        if perm_check(*args,**kwargs) is not True:#no permisssion
            return render(args[0],'crm/403.html')
        return func(*args,**kwargs)
    return  wrapper


views.py後端

'''這塊也在前端作了下權限劃分的顯示,成功了'''
@login_required
@check_permission
def teachers(req):
    teachers_list=models.UserProfile.objects.all()
    return  render(req,'crm/teachers.html',{'teachers_list':teachers_list})




◆ 權限驗證(1) 

views 中驗證 
app

if not request.user.has_perm('crm.view_teachers_list') 
return HttpResponse('Forbidden')



◆ 權限驗證(2) 

Template 中的權限檢查 
ide

{% if perms.crm.view_teachers_list %} 
有權限 
{% endif %}

前端權限判斷截圖以下:post

blob.png

相關文章
相關標籤/搜索