权限系统说明
-- django 自带的user数据迁移后会产生几个表auth_group、auth_group_permissions、auth_permission、user_user、user_user_groups、user_user_user_permissions
-- 权限系统分为user、group、permission、model。可以设置group/user对每张表的权限设置
-- jwt和user的权限分开验证,jwt对token进行验证,user需要通过表查询进行验证(还没查到怎么统一验证)
直接上代码:
settings
"""
Django settings for django_test_20211225 project.
Generated by 'django-admin startproject' using Django 4.0.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""
import datetime
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'user',
'rest_framework',
'rest_framework.authtoken'
]
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',
# 'django_test_20211225.my_middleware.TestMiddleware', # 注册中间件类 (中间件类所在py文件路径.类名)
# 'django_test_20211225.my_middleware.ExceptionTestMiddleware',
]
ROOT_URLCONF = 'django_test_20211225.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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 = 'django_test_20211225.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'django_test_db', # 要连接的数据库,连接前需要创建好
'USER': 'root', # 连接数据库的用户名
'PASSWORD': 'root', # 连接数据库的密码
'HOST': '127.0.0.1', # 连接主机,默认本级
'PORT': 3306, # 端口 默认3306
}
}
# Password validation
# https://docs.djangoproject.com/en/4.0/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/4.0/topics/i18n/
# LANGUAGE_CODE = 'en-us'
#
# TIME_ZONE = 'UTC'
#
# USE_I18N = True
#
# USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# 本地国际化
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = False
# 用户
AUTH_USER_MODEL = "user.User"
# jwt载荷中的有效期设置
JWT_AUTH = {
# 1、获取到token 2、通过token获取到refresh_token 3、token过期后,调用
# 是否开启允许Token刷新服务,及限制Token刷新间隔时间,从原始Token获取开始计算
'JWT_ALLOW_REFRESH': True,
'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=100), # REFRESHtoken 时间长
'JWT_EXPIRATION_DELTA': datetime.timedelta(days=100), # token时间短,失败了可以通过token获取REFRESHtoken
}
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-&-zx@r3)9*t8u!&f#ylotf_4y+7w^$2hv-26(g3qp7r4ch+he@'
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
),
}
AUTHENTICATION_BACKENDS = (
'user.views.CustomBackend', # 自定义手机号密码登陆
# 'social_core.backends.weibo.WeiboOAuth2', #第三方登录
# 'django.contrib.auth.backends.ModelBackend' # 默认的验证登陆
)
项目的url
from django.contrib import admin
from rest_framework_jwt.views import refresh_jwt_token
from django.urls import path,include
from rest_framework_jwt.views import obtain_jwt_token
urlpatterns = [
path('admin/', admin.site.urls),
path('user/', include("user.urls")),
path(r'login/', obtain_jwt_token),
path(r'api-token-refresh/', refresh_jwt_token)
]
user.view
from django.contrib.auth.backends import ModelBackend
from django.contrib.contenttypes.models import ContentType
from django.db.models import Q
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
# Create your views here.
from rest_framework import mixins, generics
from rest_framework.generics import CreateAPIView, ListAPIView, RetrieveAPIView
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet, ViewSet
from user.models import User
from user.serializers import UserModelSerializer, UserItemSerializer
from django.contrib.auth.models import Group, Permission
class CustomBackend(ModelBackend):
def authenticate(self, request, username=None, password=None, **kwargs):
try:
user = User.objects.get(Q(username=username) | Q(email=username))
if user.check_password(password):
return user
except Exception as e:
print(e)
return None
class UserAPIViewList(ListAPIView):
permission_classes = [IsAuthenticated] # 只用通过登录认证的才能访问
queryset = User.objects.all()
serializer_class = UserModelSerializer
def get(self, request, *args, **kwargs):
per_status = request.user.has_perm('user.add_user') # 对jwt验证后再次对user验证是否对表有访问权限
if per_status:
JsonResponse({"code": 1,"info":"没有访问权限"})
return self.list(request, *args, **kwargs)
class GroupPermission(APIView):
# 增加用户组
permission_classes = [AllowAny] # 只用通过登录认证的才能访问
def get(self, request, *args, **kwargs):
group_name = request.GET.get('group_name', default='110')
print(group_name)
group = Group.objects.create(name=group_name)
group.save()
return JsonResponse({"code": 0})
class UserAddGroup(APIView):
# 把用户增加进用户组
permission_classes = [AllowAny] # 只用通过登录认证的才能访问
def get(self, request, *args, **kwargs):
group_name = request.GET.get('group_name', default='110')
user_name = request.GET.get('user_name', default='110')
user = User.objects.get(username=user_name)
group = Group.objects.get(name=group_name)
user.groups.add(group)
return JsonResponse({"code": 0})
class GroupAddPermission(APIView):
# 给用户组添加表的权限
permission_classes = [AllowAny] # 只用通过登录认证的才能访问
def get(self, request, *args, **kwargs):
model_name = request.GET.get('model', default='110')
group_name = request.GET.get('group_name', default='110')
group = Group.objects.get(name=group_name)
permissions = Permission.objects.filter(content_type__model=model_name)
for permission in permissions:
group.permissions.add(permission)
return JsonResponse({"code": 0})
class UserItem(APIView):
permission_classes = [AllowAny] # 只用通过登录认证的才能访问
def get(self, request):
return JsonResponse({"code": 1})
class UserAPIViewCreate(CreateAPIView):
permission_classes = [AllowAny] # 只用通过登录认证的才能访问
queryset = User.objects.all()
serializer_class = UserModelSerializer
user.url
# from rest_framework.routers import DefaultRouter
#
# from user import views
#
# urlpatterns = [] # 路由列表
#
# router = DefaultRouter() # 可以处理视图的路由器
#
# router.register('userinfocreate', views.UserAPIViewCreate) # url进行注册
# # router.register('userinfolist', views.UserAPIViewList) # url进行注册
# router.register('useritem', views.UserItem,basename='useritem') # url进行注册
#
# urlpatterns += router.urls # 将路由器中的所有路由信息追加到django的路由列表中
#
# print(urlpatterns)
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'useritem', views.UserItem.as_view()),
url(r'userinfocreate', views.UserAPIViewCreate.as_view()),
url(r'userinfolist', views.UserAPIViewList.as_view()),
url(r'add_group_permission', views.GroupPermission.as_view()),
url(r'user_add_group', views.UserAddGroup.as_view()),
url(r'group_add_permission', views.GroupAddPermission.as_view()),
]
user.serializers
from rest_framework import serializers
from user.models import User
class UserModelSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = "__all__"
def create(self, validated_data):
user = super().create(validated_data)
user.set_password(user.password)
user.save()
return user
class UserItemSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = "__all__"
model
from django.db import models
# Create your models here.
from django.contrib.auth.models import AbstractUser
from django.db import models
class User(AbstractUser):
# 只添加手机号一个字段
mobile = models.CharField(max_length=100)
is_active = models.SmallIntegerField(default=1)
admin
from django.contrib import admin
# Register your models here.
from django.contrib import admin
# Register your models here.
from django.contrib.auth.admin import UserAdmin as DjangoUserAdmin
from user import models
class UserAdmin(DjangoUserAdmin):
# 添加用户课操作字段
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('username', 'password1', 'password2', 'is_staff', 'mobile', 'groups', 'user_permissions'),
}),
)
# 展示用户呈现的字段
list_display = ('username', 'mobile', 'is_staff', 'is_active', 'is_superuser')
admin.site.register(models.User)
|