当前位置:   article > 正文

Django 自定义权限管理系统(通过中间件认证)_中间件对指定的文件配置权限认证

中间件对指定的文件配置权限认证

1.  创建工程文件, 修改setting.py文件

    django-admin.py startproject project_name

    特别是在 windows 上,如果报错,尝试用 django-admin 代替 django-admin.py 试试

     setting.py 最终的配置文件  

  1. import os
  2. import sys
  3. # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
  4. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  5. sys.path.insert(0,os.path.join(BASE_DIR,"apps"))
  6. # Quick-start development settings - unsuitable for production
  7. # See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/
  8. # SECURITY WARNING: keep the secret key used in production secret!
  9. SECRET_KEY = '!g%gzw+-t8*+c2irzcm=r_#*x$q^(x-(^prn7wpnph3w#j$1gl'
  10. # SECURITY WARNING: don't run with debug turned on in production!
  11. DEBUG = True
  12. ALLOWED_HOSTS = []
  13. # Application definition
  14. INSTALLED_APPS = [
  15. 'django.contrib.admin',
  16. 'django.contrib.auth',
  17. 'django.contrib.contenttypes',
  18. 'django.contrib.sessions',
  19. 'django.contrib.messages',
  20. 'django.contrib.staticfiles',
  21. 'apps.system',
  22. ]
  23. MIDDLEWARE = [
  24. 'django.middleware.security.SecurityMiddleware',
  25. 'django.contrib.sessions.middleware.SessionMiddleware',
  26. 'django.middleware.common.CommonMiddleware',
  27. # 'django.middleware.csrf.CsrfViewMiddleware',
  28. 'django.contrib.auth.middleware.AuthenticationMiddleware',
  29. 'django.contrib.messages.middleware.MessageMiddleware',
  30. 'django.middleware.clickjacking.XFrameOptionsMiddleware',
  31. 'libs.middleware.permission.permissionMiddleware'
  32. ]
  33. ROOT_URLCONF = 'iFactory.urls'
  34. TEMPLATES = [
  35. {
  36. 'BACKEND': 'django.template.backends.django.DjangoTemplates',
  37. 'DIRS': [os.path.join(BASE_DIR, 'templates')],
  38. 'APP_DIRS': True,
  39. 'OPTIONS': {
  40. 'context_processors': [
  41. 'django.template.context_processors.debug',
  42. 'django.template.context_processors.request',
  43. 'django.contrib.auth.context_processors.auth',
  44. 'django.contrib.messages.context_processors.messages',
  45. ],
  46. },
  47. },
  48. ]
  49. WSGI_APPLICATION = 'iFactory.wsgi.application'
  50. # Database
  51. # https://docs.djangoproject.com/en/dev/ref/settings/#databases
  52. DATABASES = {
  53. 'default': {
  54. 'ENGINE': 'django.db.backends.postgresql_psycopg2',
  55. 'NAME': "iFactory",
  56. 'USER': "postgres",
  57. 'PASSWORD': "postgres",
  58. 'HOST': "127.0.0.1",
  59. 'PORT': "5432",
  60. 'CONN_MAX_AGE': 5,
  61. }
  62. }
  63. # Password validation
  64. # https://docs.djangoproject.com/en/dev/ref/settings/#auth-password-validators
  65. AUTH_PASSWORD_VALIDATORS = [
  66. {
  67. 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
  68. },
  69. {
  70. 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
  71. },
  72. {
  73. 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
  74. },
  75. {
  76. 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
  77. },
  78. ]
  79. # Internationalization
  80. # https://docs.djangoproject.com/en/dev/topics/i18n/
  81. LANGUAGE_CODE = 'zh_Hans'
  82. TIME_ZONE = 'Asia/Shanghai'
  83. USE_I18N = True
  84. USE_L10N = True
  85. USE_TZ = True
  86. # Static files (CSS, JavaScript, Images)
  87. # https://docs.djangoproject.com/en/dev/howto/static-files/
  88. STATIC_URL = '/static/'
  89. STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), )
  90. # Session setting
  91. SESSION_COOKIE_AGE = 30 * 60
  92. SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
  93. # session_permisson_key
  94. SESSION_PERMISSION_URL_KEY = "perUrl"
  95. SESSION_MENU_KEY = "menu"
  96. MENU_ALL = "menuAll"
  97. MENU_PERMISSON = "menuPer"
  98. # permisson
  99. LOGIN_URL = '/login/'
  100. REGEX_URL = r'^{url}$' # url作严格匹配
  101. SAFE_URL = [
  102. '/login/',
  103. ]

 

 

2. 根目录创建apps文件夹(python包文件夹),创建应用system, 把应用放入到apps文件夹中

 

 

 

    python manage.py  startapp system, 在setting中的INSTALLED_APPS中添加对应的app

   最终的目录结构

        

3. 修改system/model.py 文件

  1. #-*-coding:utf-8-*-
  2. from django.db import models
  3. # Create your models here.
  4. class Menu(models.Model):
  5. '''
  6. 菜单
  7. '''
  8. title = models.CharField(max_length=32, unique=True)
  9. parent = models.ForeignKey("Menu", null=True, blank=True)
  10. def __str__(self):
  11. # 显示层级菜单
  12. title_list = [self.title]
  13. p = self.parent
  14. while p:
  15. title_list.insert(0, p.title)
  16. p = p.parent
  17. return '-'.join(title_list)
  18. class Permission(models.Model):
  19. '''
  20. 权限
  21. '''
  22. title = models.CharField(max_length=32, unique=True)
  23. url = models.CharField(max_length=128, unique=True)
  24. menu = models.ForeignKey("Menu", null=True, blank=True)
  25. # 定义菜单间的自引用关系
  26. # 权限url 在 菜单下;菜单可以有父级菜单;还要支持用户创建菜单,因此需要定义parent字段(parent_id)
  27. # blank=True 意味着在后台管理中填写可以为空,根菜单没有父级菜单
  28. def __str__(self):
  29. # 显示带菜单前缀的权限
  30. return '{menu}---{permission}'.format(menu=self.menu, permission=self.title)
  31. class Role(models.Model):
  32. '''
  33. 角色:绑定权限
  34. '''
  35. title = models.CharField(max_length=32, unique=True)
  36. # 定义角色和权限的多对多关系
  37. permissions = models.ManyToManyField("Permission")
  38. def __str__(self):
  39. return self.title
  40. class User(models.Model):
  41. '''
  42. 用户 -- 角色划分
  43. '''
  44. username = models.CharField(max_length=32)
  45. password = models.CharField(max_length=32)
  46. phone = models.CharField(max_length=11)
  47. email = models.EmailField()
  48. is_admin = models.BooleanField(default=False)
  49. is_push_email = models.BooleanField(default=True)
  50. is_push_phone = models.BooleanField(default=True)
  51. # create_datetime = models.DateTimeField(auto_now_add=True)
  52. # 定义用户和角色的多对多关系
  53. roles = models.ManyToManyField("Role")
  54. def __str__(self):
  55. return '{username}---{phone}' \
  56. ''.format(username=self.username, phone=self.phone)

4. 数据库迁移  

执行 python manage.py makemigrations system 

执行python manage.py migrate system

5.  建立userService.py文件(文件位置看上图目录),代码如下:

  1. from ..models import Menu
  2. def init_user_permission(request, user):
  3. '''
  4. 查询出用户的所有权限,进行分类写入session进行保存
  5. :param request:
  6. :param user:
  7. :return:
  8. '''
  9. # 查询出用户的所有权限
  10. permisson_item_list = user.roles.values('permissons__title',
  11. 'permissons__url',
  12. 'permissons__menu_id'
  13. ).distinct()
  14. permisson_url_list = []
  15. permisson_menu_list = []
  16. all_menu_list = list(Menu.objects.values("id", "title", "parent_id"))
  17. for permission_item in permisson_item_list:
  18. permisson_url_list.append(permission_item["permissons__url"])
  19. if permission_item["permissons__menu__id"]:
  20. temp = {
  21. "title": permission_item["permissons__title"],
  22. "url": permission_item["permissons__url"],
  23. "menu_id": permission_item["permissons__menu_id"]
  24. }
  25. permisson_menu_list.append(temp)
  26. # 写入session
  27. from django.conf import settings
  28. request.session[settings.SESSION_PERMISSION_URL_KEY] = permisson_url_list
  29. request.session[settings.SESSION_MENU_KEY] = {
  30. settings.MENU_ALL: all_menu_list,
  31. settings.MENU_PERMISSON: permisson_menu_list,
  32. }

6. 建立views_user.py 文件:

  1. #-*-coding:utf-8-*-
  2. from django.shortcuts import render
  3. from django.http import JsonResponse, HttpResponse
  4. from apps.system.services import userService
  5. from apps.system.models import User
  6. def user_login(request):
  7. '''
  8. 用户登录
  9. :param request:
  10. :return:
  11. '''
  12. if request.method == "GET":
  13. return render(request, "login.html")
  14. else:
  15. res = {}
  16. username = request.POST.get("username")
  17. password = request.POST.get("password")
  18. user = User.objects.filter(username=username, password=password).first()
  19. if not user:
  20. res["status"]= "false"
  21. else:
  22. userService.init_user_permission(request, user)
  23. return JsonResponse(res)

 

注意: 以上的setting.py 增加的配置:

 

  1. MIDDLEWARE = [
  2. 'django.middleware.security.SecurityMiddleware',
  3. 'django.contrib.sessions.middleware.SessionMiddleware',
  4. 'django.middleware.common.CommonMiddleware',
  5. # 'django.middleware.csrf.CsrfViewMiddleware',
  6. 'django.contrib.auth.middleware.AuthenticationMiddleware',
  7. 'django.contrib.messages.middleware.MessageMiddleware',
  8. 'django.middleware.clickjacking.XFrameOptionsMiddleware',
  9. 'libs.middleware.permission.permissionMiddleware'
  10. ]

 

 

 

  1. # Session setting
  2. SESSION_COOKIE_AGE = 30 * 60
  3. SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
  4. # session_permisson_key
  5. SESSION_PERMISSION_URL_KEY = "perUrl"
  6. SESSION_MENU_KEY = "menu"
  7. MENU_ALL = "menuAll"
  8. MENU_PERMISSON = "menuPer"
  9. # permisson
  10. LOGIN_URL = '/login/'
  11. REGEX_URL = r'^{url}$' # url作严格匹配
  12. SAFE_URL = [
  13. '/login/',
  14. ]

 

 

 

 
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/71746
推荐阅读
相关标签
  

闽ICP备14008679号