RBAC在Django中基于中间件的AJAX应用案例

Posted open-yang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了RBAC在Django中基于中间件的AJAX应用案例相关的知识,希望对你有一定的参考价值。

项目文件:

 

   技术图片

models.py

技术图片
 1 from django.db import models
 2 from django.contrib.auth.models import AbstractUser
 3 # Create your models here.
 4  
 5 class UserInfo(AbstractUser):
 6     role=models.ManyToManyField(to=Role,verbose_name=角色,null=True,blank=True)
 7     def __str__(self):
 8         if self.role:
 9             return fself.username(self.role.name)
10         else:
11             return fself.username(未分配)
12  
13 class Role(models.Model):
14     name=models.CharField(max_length=32,verbose_name=角色名称)
15     permission=models.ManyToManyField(to=Permission,verbose_name=权限)
16     def __str__(self):
17         return self.name
18  
19 class Permission(models.Model):
20     name=models.CharField(max_length=32,verbose_name="权限")
21     url=models.CharField(max_length=64,verbose_name=url)
22     def __str__(self):
23         return self.name
models.py

middlewares.py(自定义中间件) 

技术图片
 1 from django.utils.deprecation import MiddlewareMixin
 2 from django.shortcuts import redirect,HttpResponse
 3 import re
 4 class AuthPerminssion(MiddlewareMixin):
 5     def process_request(self,request):
 6         url=[/admin/.*,/register/,/login/]
 7         for i in url:
 8             if re.match(i, request.path):
 9                 return None
10         else:
11             if request.user.is_authenticated:
12  
13                 for url in request.session.get(permission):
14                     print(request.path)
15                     print(request.session.get(permission))
16                     if re.match(furl$,request.path):
17    #if re.search(f‘^url$‘,request.path):
18                         return None
19                     else:
20                         return  HttpResponse(无权访问!)
21             else:
22                 return redirect(login)
middlewares.py

settings.py(中间件注册和auth表指定)

技术图片
 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 app01.middlewares.AuthPerminssion,
10 ]
11  
12  
13 AUTH_USER_MODEL=app01.UserInfo#配置自定义auth认真表
14  
15 STATIC_URL=/static/
16 STATICFILES_DIRS=[
17 os.path.join(BASE_DIR,static_files)
18 ]
settings.py

urls.py

技术图片
 1 from django.conf.urls import url
 2 from django.contrib import admin
 3 from app01 import views
 4  
 5 urlpatterns = [
 6     url(r^admin/, admin.site.urls),
 7     url(r^register/, views.Register.as_view(), name=register),
 8     url(r^login/, views.Login.as_view(), name=login),
 9  
10     url(r^order/$, views.order, name=order),
11     url(r^order/add/, views.addorder, name=addorder),
12     url(r^order/edit/(\\d+), views.editorder, name=editorder),
13     url(r^order/delete/(\\d+), views.deleteorder, name=deleteorder),
14  
15     url(r^customer/$, views.customer, name=customer),
16     url(r^customer/add/, views.addcustomer, name=addcustomer),
17     url(r^customer/edit/(\\d+), views.editcustomer, name=editcustomer),
18     url(r^customer/delete/(\\d+), views.deletecustomer, name=deletecustomer),
19  
20 ]
urls.py

form.py(自定义form组件)

技术图片
 1 from app01 import models
 2 from django import forms
 3 from django.core.exceptions import  ValidationError
 4  
 5 #注册form
 6 class RegisterForm(forms.Form):
 7     name = forms.CharField(label=用户名,max_length=12, min_length=8,required=True,
 8         error_messages=
 9             max_length:用户名不能多于12个字符,
10             min_length:用户名不能少于8个字符!,
11             required:用户名不能为空!,
12         ,# widget=forms.TextInput(attrs=‘type‘:‘text‘,‘class‘:‘form-control‘)  )
13  
14     password=forms.CharField(label=密码,max_length=8,min_length=6required=True,
15         error_messages=
16             max_length: 密码不能多于8个字符,
17             min_length: 密码不能少于6个字符!,
18             required: 密码不能为空!,
19         ,
20         widget=forms.PasswordInput(attrs=,render_value=True) )
21     r_password = forms.CharField( label=确认密码, max_length=8, min_length=6, required=True,
22         error_messages=
23             max_length: 密码不能多于8个字符,
24             min_length: 密码不能少于6个字符!,
25             required: 密码不能为空!,
26         , widget=forms.PasswordInput(attrs=,render_value=True) )
27     def clean_name(self):
28         if models.UserInfo.objects.filter(username=self.cleaned_data.get(name)):
29             raise ValidationError(当前用户已存在!)
30         else:
31             return self.cleaned_data.get(name)
32     def clean(self):
33         pwd=self.cleaned_data.get(password)
34         r_ped=self.cleaned_data.get(r_password)
35         if pwd!=r_ped:
36             self.add_error(r_password,两次密码输入不一致!)
37         else:
38             return self.cleaned_data
39     def __init__(self, *args, **kwargs):
40         super().__init__(*args, **kwargs)
41         for field in self.fields.values():
42             field.widget.attrs.update(class: form-control)
43  
44 #登录modelform
45 class LoginModelForm(forms.ModelForm):
46     class Meta:
47         model=models.UserInfo
48         fields=[username,password]
49         labels= username:用户名,password:密码
50         error_messages=username:required:用户名不能为空!,
51             password:required:密码不能为空!,,
52         widgets=password:forms.PasswordInput(),
53     def __init__(self,*args,**kwargs):
54         super().__init__(*args,**kwargs)
55         for field in self.fields:
56             self.fields[field].widget.attrs.update(class: form-control)
form.py

views.py

技术图片
 1 from django.shortcuts import render,HttpResponse
 2 from django.views import View
 3 from app01.form import RegisterForm,LoginModelForm
 4 from django.contrib import auth
 5 from app01.models import UserInfo,Permission
 6  
 7 # Create your views here.
 8  
 9 class Register(View):
10     def get(self,request):
11         register_formobj=RegisterForm()
12         return  render(request,register.html,register_formobj:register_formobj,)
13     def post(self,request):
14         register_obj=RegisterForm(request.POST)
15         if register_obj.is_valid():
16             print(register_obj.cleaned_data)
17             name=register_obj.cleaned_data.get(name)
18             pwd=register_obj.cleaned_data.get(password)
19             user_obj=UserInfo.objects.create_user(username=name,password=pwd)
20             return HttpResponse(ok)
21         else:
22             return render(request,register.html,register_formobj:register_obj,)
23 class Login(View):
24     def get(self,request):
25         login_formobj=LoginModelForm()
26         return render(request,login.html,login_formobj:login_formobj)
27     def post(self,request):
28         print(request.POST)
29         user_obj = auth.authenticate(username=request.POST.get(username),password=request.POST.get(password))
30         if user_obj:
31             auth.login(request, user_obj)
32             permission_url_list=[i.url for i in Permission.objects.filter(role__userinfo__pk=request.user.pk)]
33             request.session[permission]=permission_url_list
34             return HttpResponse(login successed!)
35         else:
36             return HttpResponse(login failed!)
37  
38 def order(request):
39     return HttpResponse(order...)
40 def addorder(request):
41     return HttpResponse(addorder...)
42 def editorder(request,pk):
43     return HttpResponse(editorder...)
44 def deleteorder(request,pk):
45     return HttpResponse(deleteorder...)
46  
47  
48 def customer(request):
49     return HttpResponse(customer...)
50 def addcustomer(request):
51     return HttpResponse(addcustomer...)
52 def editcustomer(request,pk):
53     return HttpResponse(editcustomer...)
54 def deletecustomer(request,pk):
55     return HttpResponse(deletecustomer...)
views.py

Templates

   register.html

技术图片
 1 % load static %
 2 <!DOCTYPE html>
 3 <html lang="en">
 4 <head>
 5     <meta charset="UTF-8">
 6     <link rel="stylesheet" href="% static ‘bootstrap-3.3.7-dist/css/bootstrap.min.css‘ %">
 7     <title>注册</title>
 8 </head>
 9 <body>
10 <div class="container">
11     <div class="row">
12         <div class="col-xs-4 col-xs-offset-4">
13             <form action="" method="post" novalidate>
14             % for field in register_formobj %
15             <div class="form-group">
16                 <label for=" field.id_for_label "> field.label </label>
17                  field 
18             <span class="text-danger"> field.errors.0 </span>
19             </div>
20             % endfor %
21         % csrf_token %
22         <input type="submit" class="btn btn-primary pull-right" value="注册">
23 </form>
24         </div>
25     </div>
26 </div>
27 </body>
28 <script src="% static ‘jquery-3.4.1.js‘ %"></script>
29 <script src="% static ‘jquery-cookie-1.4.1.js‘ %"></script>
30 <script src="% static ‘bootstrap-3.3.7-dist/js/bootstrap.min.js‘ %"></script>
31 </html>
register.html

  login.html

技术图片
 1 % load static %
 2 <!DOCTYPE html>
 3 <html lang="en">
 4 <head>
 5     <meta charset="UTF-8">
 6     <link rel="stylesheet" href="% static ‘bootstrap-3.3.7-dist/css/bootstrap.min.css‘ %">
 7     <title>login</title>
 8 </head>
 9 <body>
10 <div class="container">
11     <div class="row">
12         <div class="col-xs-4 col-xs-offset-4">
13             <form action="" method="post" novalidate>
14             % for field in login_formobj %
15             <div class="form-group">
16                 <label for=" field.id_for_label "> field.label </label>
17                  field 
18             <span class="text-danger"> field.errors.0 </span>
19             </div>
20             % endfor %
21         % csrf_token %
22         <input type="submit" class="btn btn-primary pull-right" value="登录">
23 </form>
24         </div>
25     </div>
26 </div>
27 </body>
28 <script src="% static ‘jquery-3.4.1.js‘ %"></script>
29 <script src="% static ‘bootstrap-3.3.7-dist/js/bootstrap.min.js‘ %"></script>
30 </html>
login.html

 

以上是关于RBAC在Django中基于中间件的AJAX应用案例的主要内容,如果未能解决你的问题,请参考以下文章

基于Django实现RBAC权限管理

RBAC——权限六张表

Django——权限组件(中间件判断用户权限--URL)

Django框架之RBAC+ContentType

django的RBAC介绍1

Django 之AJAX