当前位置:网站首页>User management - restrictions
User management - restrictions
2022-07-27 08:33:00 【pink_ Pig___】
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

边栏推荐
- 面试官:什么是脚手架?为什么需要脚手架?常用的脚手架有哪些?
- Realization of specification management and specification option management functions
- Solution to the program design of the sequence structure of one book (Chapter 1)
- 百人参与,openGauss开源社区这群人都在讨论什么?
- Teach you to build a nail warning robot hand in hand
- Flask one to many database creation, basic addition, deletion, modification and query
- Virtual machine cloning
- ERP生产作业控制 华夏
- Eval and assert execute one sentence Trojan horse
- Background coupon management
猜你喜欢

Installation and use of beef XSS
![[ciscn2019 southeast China division]web11 1](/img/94/61ad4f6cbbd46ff66f361462983d7a.png)
[ciscn2019 southeast China division]web11 1
![Connection failed during installation of ros2 [ip: 91.189.91.39 80]](/img/7f/92b7d44cddc03c58364d8d3f19198a.png)
Connection failed during installation of ros2 [ip: 91.189.91.39 80]

带宽 与 货币

"PHP Basics" PHP statements and statement blocks

Use of "PHP Basics" Boolean

OPPO 自研大规模知识图谱及其在数智工程中的应用

情人节,我用字符画出了一个对象!

Demo:st05 find text ID information

Attack and defense world MFW
随机推荐
Flask project configuration
Redis configuration file download
Flask request data acquisition and response
"PHP Basics" uses echo statements to output information
idea远程调试
Realize SKU management in the background
"PHP Basics" tags in PHP
Chapter 2 foreground data display
JS basic exercises
VS Code中#include报错(新建的头文件)
pytorch_ demo1
OPPO 自研大规模知识图谱及其在数智工程中的应用
Have a good laugh
JS rotation chart
Demo:st05 find text ID information
ERP production operation control Huaxia
Solution to the program design of the sequence structure of one book (Chapter 1)
Weekly learning summary
OSI seven layer model and tcp/ip four layer (TCP and UDP) (notes)
海量数据肖枫:共建共治openGauss根社区,共享欣欣向荣新生态