IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Python知识库 -> django自带的权限系统和User和jwt -> 正文阅读

[Python知识库]django自带的权限系统和User和jwt

权限系统说明

-- 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)

  Python知识库 最新文章
Python中String模块
【Python】 14-CVS文件操作
python的panda库读写文件
使用Nordic的nrf52840实现蓝牙DFU过程
【Python学习记录】numpy数组用法整理
Python学习笔记
python字符串和列表
python如何从txt文件中解析出有效的数据
Python编程从入门到实践自学/3.1-3.2
python变量
上一篇文章      下一篇文章      查看所有文章
加:2022-01-04 13:23:24  更:2022-01-04 13:24:57 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/16 3:50:22-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码