当前位置:网站首页>User management - restrictions
User management - restrictions
2022-07-19 05:04:00 【du fei】
1. Define the model class first
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils import timezone
# Create your models here.
# Permission class
class PermissionType(models.Model):
name = models.CharField(' Authority type ', max_length=30)
def __str__(self):
return self.name
class Meta:
db_table = 'permission_type'
# user
class User(AbstractUser):
mobile = models.CharField(' cell-phone number ', max_length=11)
last_login = models.DateTimeField(' Last login time ', default=timezone.now)
# Join the character
role = models.ManyToManyField(PermissionType)
class Meta:
verbose_name_plural = ' user '
db_table = 'user'
# jurisdiction
class Permission(models.Model):
name = models.CharField(' Permission to name ', max_length=30)
code_name = models.CharField(' jurisdiction ', max_length=100)
type_name = models.ForeignKey(PermissionType, on_delete=models.CASCADE, verbose_name=' Permission class line ')
def __str__(self):
return self.name
class Meta:
verbose_name_plural = ' Limit '
db_table = 'permission'
# User group
class UserGroup(models.Model):
name = models.CharField(' Group name ', max_length=30)
user = models.ManyToManyField(User)
permission = models.ManyToManyField(Permission)
def __str__(self):
return self.name
class Meta:
db_table = 'usergroup'
- You need to configure in the configuration
AUTH_USER_MODEL = 'users.User'
2. Create a RBAC middleware

2. Register the middleware in the configuration item
MIDDLEWARE = [
'RBAC.rbac.MyRBAC',
]
- Write code in the middleware
from django.utils.deprecation import MiddlewareMixin
import redis, re, json
from django.http import JsonResponse
from rest_framework_jwt.utils import jwt_decode_handler
# Customize rbac middleware
class MyRBAC(MiddlewareMixin):
def __init__(self, handler):
super(MyRBAC, self).__init__(handler)
self.redis_conn = redis.Redis(host='127.0.0.1', port=6379)
# Process the request before the request enters the route
def process_request(self, request):
path = request.path_info[1:] # Take off the first /
method = request.method.lower() # GET / POST
# Judge whether the current request is logged in 、 Get SMS verification code 、admin management
if re.findall('login|sms_code|^admin', path, re.I):
# Just let go of these requests
return None
# Handle other requests for resources
# Verify that the user is logged in , jwt token
payload = self.validate_token(request)
if payload:
# User logged in
print(' User's load information :', payload)
# Verify whether the current request has permission
key = 'user_permissions_%s' % payload.get('user_id')
permission_list = self.redis_conn.get(key)
if permission_list:
# Decode byte string ---》 json character string
# figure out json character string ---》 Permission list
permissions_list = json.loads(permission_list.decode())
# Traverse the permission list , Contrast one by one , Check whether you have permission
for permission in permissions_list:
if permission.startswith(method):
print(permission)
print(path)
re_path = permission.split()[1]
if re.findall(re_path, path, re.I):
# Has the authority , Let the current request enter the route matching
return None
return JsonResponse({
'code': 403, 'msg': ' No authority '})
else:
# No permission data
return JsonResponse({
'code': 401, 'msg': ' No authority '})
else:
return JsonResponse({
'code': 401,
'msg': ' User not authenticated '
})
@staticmethod
def validate_token(request):
# obtain jwt token
token = request.headers.get("Authorization")
if not token:
return None
token = token.split()[1]
# decode token
try:
payload = jwt_decode_handler(token)
return payload
except:
return None
- Modify login interface
# Store user permissions
roles = user.role.all()
print('rolse:', roles)
temp_list = []
for role in roles:
# Get the corresponding permissions according to each role
permissions = role.permission_set.all().values_list('code_name')
permissions_list = [i[0] for i in permissions]
temp_list += permissions_list
# Authority de duplication , And stored in memory
temp_list = list(set(temp_list))
print('temp_list:', temp_list)
key = 'user_permissions_%s'%user.id
r = redis.Redis()
r.set(key, json.dumps(temp_list))
3. Add information to super users
- settings.py Configure Chinese
LANGUAGE_CODE = 'zh-Hans'
TIME_ZONE = 'Asia/Shanghai'
- Sign up for super users
python manage.py createsuperuser
- Subapplication admin Write code in the file
from django.contrib import admin
from users.models import *
# Register your models here.
# Manager of model class
class PermissionManager(admin.ModelAdmin):
list_display = ['id', 'name', 'code_name', 'type_name']
list_display_links = ['name']
list_editable = ['code_name']
list_filter = ['type_name']
search_fields = ['name']
admin.site.register(Permission, PermissionManager)
Add information to the permission class

Add some permissions

边栏推荐
猜你喜欢

Attendance check-in and leave system based on SSM framework

卷积神经网络

MD5 password encryption

事务的使用-django、 SQL工具

Fanoutexchange switch is simple to use

泰迪杯A题完整版 优化更新(4/23)

【Batch】批量删除中间文件夹-个人研究脚本

PyGame installation -requirement already satisfied

Conception finale: système distribué de gestion de la santé pour la prévention des épidémies hautement simultanées basé sur vue + socket + redis

用户登录-以及创建验短信证码
随机推荐
DSL查询文档
3. Restclient query document
Web development with fastapi
NoSQL overview
索引库操作基本操作
FanoutExchange交换机简单使用
Cve-2020-10199 recurrence of nexus repository manager3 remote command execution vulnerability
用户的管理-限制
Harmonyos入门
天道酬勤,保持热爱
脱敏字段举例
Differences between substr and substring in JS
POC——DVWA‘s File Inclusion
First training notes of moderlarts
ModelArts第二次培訓筆記
三种高并发方式实现i++
RestClient操作文档
Tidb performance optimization overview
Elment UI usage
HarmonyOS第三次培训笔记