Django 自定义权限管理系统详解(通过中间件认证)
1.创建工程文件,修改setting.py文件
django-admin.pystartprojectproject_name
特别是在windows上,如果报错,尝试用django-admin代替django-admin.py试试
setting.py最终的配置文件
importos
importsys
#Buildpathsinsidetheprojectlikethis:os.path.join(BASE_DIR,...)
BASE_DIR=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0,os.path.join(BASE_DIR,"apps"))
#Quick-startdevelopmentsettings-unsuitableforproduction
#Seehttps://docs.djangoproject.com/en/dev/howto/deployment/checklist/
#SECURITYWARNING:keepthesecretkeyusedinproductionsecret!
SECRET_KEY='!g%gzw+-t8*+c2irzcm=r_#*x$q^(x-(^prn7wpnph3w#j$1gl'
#SECURITYWARNING:don'trunwithdebugturnedoninproduction!
DEBUG=True
ALLOWED_HOSTS=[]
#Applicationdefinition
INSTALLED_APPS=[
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'apps.system',
]
MIDDLEWARE=[
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
#'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'libs.middleware.permission.permissionMiddleware'
]
ROOT_URLCONF='iFactory.urls'
TEMPLATES=[
{
'BACKEND':'django.template.backends.django.DjangoTemplates',
'DIRS':[os.path.join(BASE_DIR,'templates')],
'APP_DIRS':True,
'OPTIONS':{
'context_processors':[
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION='iFactory.wsgi.application'
#Database
#https://docs.djangoproject.com/en/dev/ref/settings/#databases
DATABASES={
'default':{
'ENGINE':'django.db.backends.postgresql_psycopg2',
'NAME':"iFactory",
'USER':"postgres",
'PASSWORD':"postgres",
'HOST':"127.0.0.1",
'PORT':"5432",
'CONN_MAX_AGE':5,
}
}
#Passwordvalidation
#https://docs.djangoproject.com/en/dev/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS=[
{
'NAME':'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME':'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME':'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME':'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
#Internationalization
#https://docs.djangoproject.com/en/dev/topics/i18n/
LANGUAGE_CODE='zh_Hans'
TIME_ZONE='Asia/Shanghai'
USE_I18N=True
USE_L10N=True
USE_TZ=True
#Staticfiles(CSS,JavaScript,Images)
#https://docs.djangoproject.com/en/dev/howto/static-files/
STATIC_URL='/static/'
STATICFILES_DIRS=(os.path.join(BASE_DIR,'static'),)
#Sessionsetting
SESSION_COOKIE_AGE=30*60
SESSION_ENGINE='django.contrib.sessions.backends.cache'
#session_permisson_key
SESSION_PERMISSION_URL_KEY="perUrl"
SESSION_MENU_KEY="menu"
MENU_ALL="menuAll"
MENU_PERMISSON="menuPer"
#permisson
LOGIN_URL='/login/'
REGEX_URL=r'^{url}$'#url作严格匹配
SAFE_URL=[
'/login/',
]
2.根目录创建apps文件夹(python包文件夹),创建应用system,把应用放入到apps文件夹中
pythonmanage.pystartappsystem,在setting中的INSTALLED_APPS中添加对应的app
最终的目录结构
3.修改system/model.py文件
#-*-coding:utf-8-*-
fromdjango.dbimportmodels
#Createyourmodelshere.
classMenu(models.Model):
'''
菜单
'''
title=models.CharField(max_length=32,unique=True)
parent=models.ForeignKey("Menu",null=True,blank=True)
def__str__(self):
#显示层级菜单
title_list=[self.title]
p=self.parent
whilep:
title_list.insert(0,p.title)
p=p.parent
return'-'.join(title_list)
classPermission(models.Model):
'''
权限
'''
title=models.CharField(max_length=32,unique=True)
url=models.CharField(max_length=128,unique=True)
menu=models.ForeignKey("Menu",null=True,blank=True)
#定义菜单间的自引用关系
#权限url在菜单下;菜单可以有父级菜单;还要支持用户创建菜单,因此需要定义parent字段(parent_id)
#blank=True意味着在后台管理中填写可以为空,根菜单没有父级菜单
def__str__(self):
#显示带菜单前缀的权限
return'{menu}---{permission}'.format(menu=self.menu,permission=self.title)
classRole(models.Model):
'''
角色:绑定权限
'''
title=models.CharField(max_length=32,unique=True)
#定义角色和权限的多对多关系
permissions=models.ManyToManyField("Permission")
def__str__(self):
returnself.title
classUser(models.Model):
'''
用户--角色划分
'''
username=models.CharField(max_length=32)
password=models.CharField(max_length=32)
phone=models.CharField(max_length=11)
email=models.EmailField()
is_admin=models.BooleanField(default=False)
is_push_email=models.BooleanField(default=True)
is_push_phone=models.BooleanField(default=True)
#create_datetime=models.DateTimeField(auto_now_add=True)
#定义用户和角色的多对多关系
roles=models.ManyToManyField("Role")
def__str__(self):
return'{username}---{phone}'\
''.format(username=self.username,phone=self.phone)
4.数据库迁移
执行pythonmanage.pymakemigrationssystem
执行pythonmanage.pymigratesystem
5.建立userService.py文件(文件位置看上图目录),代码如下:
from..modelsimportMenu
definit_user_permission(request,user):
'''
查询出用户的所有权限,进行分类写入session进行保存
:paramrequest:
:paramuser:
:return:
'''
#查询出用户的所有权限
permisson_item_list=user.roles.values('permissons__title',
'permissons__url',
'permissons__menu_id'
).distinct()
permisson_url_list=[]
permisson_menu_list=[]
all_menu_list=list(Menu.objects.values("id","title","parent_id"))
forpermission_iteminpermisson_item_list:
permisson_url_list.append(permission_item["permissons__url"])
ifpermission_item["permissons__menu__id"]:
temp={
"title":permission_item["permissons__title"],
"url":permission_item["permissons__url"],
"menu_id":permission_item["permissons__menu_id"]
}
permisson_menu_list.append(temp)
#写入session
fromdjango.confimportsettings
request.session[settings.SESSION_PERMISSION_URL_KEY]=permisson_url_list
request.session[settings.SESSION_MENU_KEY]={
settings.MENU_ALL:all_menu_list,
settings.MENU_PERMISSON:permisson_menu_list,
}
6.建立views_user.py文件:
#-*-coding:utf-8-*-
fromdjango.shortcutsimportrender
fromdjango.httpimportJsonResponse,HttpResponse
fromapps.system.servicesimportuserService
fromapps.system.modelsimportUser
defuser_login(request):
'''
用户登录
:paramrequest:
:return:
'''
ifrequest.method=="GET":
returnrender(request,"login.html")
else:
res={}
username=request.POST.get("username")
password=request.POST.get("password")
user=User.objects.filter(username=username,password=password).first()
ifnotuser:
res["status"]="false"
else:
userService.init_user_permission(request,user)
returnJsonResponse(res)
注意:以上的setting.py增加的配置:
MIDDLEWARE=[ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', #'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'libs.middleware.permission.permissionMiddleware' ]
#Sessionsetting
SESSION_COOKIE_AGE=30*60
SESSION_ENGINE='django.contrib.sessions.backends.cache'
#session_permisson_key
SESSION_PERMISSION_URL_KEY="perUrl"
SESSION_MENU_KEY="menu"
MENU_ALL="menuAll"
MENU_PERMISSON="menuPer"
#permisson
LOGIN_URL='/login/'
REGEX_URL=r'^{url}$'#url作严格匹配
SAFE_URL=[
'/login/',
]
以上这篇Django自定义权限管理系统详解(通过中间件认证)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。