当前位置:   article > 正文

Django 自定义权限管理系统详解(通过中间件认证)_django中间件权限验证

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

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

最终的目录结构

  1. 修改system/model.py 文件

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

执行 python manage.py makemigrations system

执行python manage.py migrate system

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

  1.    from ..models import Menu
  2.    
  3.    def init_user_permission(request, user):
  4.      '''
  5.     查询出用户的所有权限,进行分类写入session进行保存
  6.     :param request:
  7.     :param user:
  8.     :return:
  9.     '''
  10.      # 查询出用户的所有权限
  11.      permisson_item_list = user.roles.values('permissons__title',
  12.                          'permissons__url',
  13.                          'permissons__menu_id'
  14.                         ).distinct()
  15.      permisson_url_list = []
  16.      permisson_menu_list = []
  17.      all_menu_list = list(Menu.objects.values("id", "title", "parent_id"))
  18.      for permission_item in permisson_item_list:
  19.        permisson_url_list.append(permission_item["permissons__url"])
  20.        if permission_item["permissons__menu__id"]:
  21.          temp = {
  22.            "title": permission_item["permissons__title"],
  23.            "url": permission_item["permissons__url"],
  24.            "menu_id": permission_item["permissons__menu_id"]
  25.         }
  26.          permisson_menu_list.append(temp)
  27.      # 写入session
  28.      from django.conf import settings
  29.      request.session[settings.SESSION_PERMISSION_URL_KEY] = permisson_url_list
  30.      request.session[settings.SESSION_MENU_KEY] = {
  31.        settings.MENU_ALL: all_menu_list,
  32.        settings.MENU_PERMISSON: permisson_menu_list,
  33.     }
  34.    
  1. 建立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.    
  7.    def user_login(request):
  8.      '''
  9.     用户登录
  10.     :param request:
  11.     :return:
  12.     '''
  13.      if request.method == "GET":
  14.        return render(request, "login.html")
  15.      else:
  16.        res = {}
  17.        username = request.POST.get("username")
  18.        password = request.POST.get("password")
  19.        user = User.objects.filter(username=username, password=password).first()
  20.        if not user:
  21.          res["status"]= "false"
  22.        else:
  23.          userService.init_user_permission(request, user)
  24.        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.   ]
  11.    
  1.    # Session setting
  2.    SESSION_COOKIE_AGE = 30 * 60
  3.    SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
  4.    
  5.    # session_permisson_key
  6.    SESSION_PERMISSION_URL_KEY = "perUrl"
  7.    SESSION_MENU_KEY = "menu"
  8.    MENU_ALL = "menuAll"
  9.    MENU_PERMISSON = "menuPer"
  10.    
  11.    # permisson
  12.    LOGIN_URL = '/login/'
  13.    REGEX_URL = r'^{url}$' # url作严格匹配
  14.    SAFE_URL = [
  15.      '/login/',
  16.   ]
  17.    

以上这篇Django 自定义权限管理系统详解(通过中间件认证)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

 

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

闽ICP备14008679号