• Django通过中间件实现登录验证demo


    前提:中间件版的登录验证需要依靠session,所以数据库中要有django_session表。

     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'^login/$', views.login, name='login'),
     8     url(r'^index/$', views.index, name='index'),
     9     url(r'^home/$', views.home, name='home'),
    10 ]
    urls.py
     1 from django.shortcuts import render, HttpResponse, redirect
     2 
     3 
     4 def index(request):
     5     return HttpResponse('this is index')
     6 
     7 
     8 def home(request):
     9     return HttpResponse('this is home')
    10 
    11 
    12 def login(request):
    13     if request.method == "POST":
    14         user = request.POST.get("user")
    15         pwd = request.POST.get("pwd")
    16 
    17         if user == "jason" and pwd == "jason666":
    18             # 设置session
    19             request.session["user"] = user
    20             # 获取跳到登陆页面之前的URL
    21             next_url = request.GET.get("next")
    22             # 如果有,就跳转回登陆之前的URL
    23             if next_url:
    24                 return redirect(next_url)
    25             # 否则默认跳转到index页面
    26             else:
    27                 return redirect("/index/")
    28     return render(request, "login.html")
    views.py
     1 <!DOCTYPE html>
     2 <html lang="en">
     3 <head>
     4     <meta charset="UTF-8">
     5     <title>登录页面</title>
     6 </head>
     7 <body>
     8 <form action="{% url 'login' %}" method="post">
     9     {% csrf_token %}
    10     <p>
    11         <label for="user">用户名:</label>
    12         <input type="text" name="user" id="user">
    13     </p>
    14     <p>
    15         <label for="pwd">密 码:</label>
    16         <input type="text" name="pwd" id="pwd">
    17     </p>
    18     <input type="submit" value="登录">
    19 </form>
    20 </body>
    21 </html>
    login.html
     1 from django.utils.deprecation import MiddlewareMixin
     2 
     3 
     4 class AuthMD(MiddlewareMixin):
     5     white_list = ['/login/', ]  # 白名单
     6     black_list = ['/black/', ]  # 黑名单
     7 
     8     def process_request(self, request):
     9         from django.shortcuts import redirect, HttpResponse
    10 
    11         next_url = request.path_info
    12         print(request.path_info, request.get_full_path())
    13         # 黑名单的网址限制访问
    14         if next_url in self.black_list:
    15             return HttpResponse('This is an illegal URL')
    16         # 白名单的网址或者登陆用户不做限制
    17         elif next_url in self.white_list or request.session.get("user"):
    18             return
    19         else:
    20             return redirect("/login/?next={}".format(next_url))
    mymiddlewares.py
     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.mymiddlewares.AuthMD'
    10 ]
    settings注册中间件

    AuthMD中间件注册后,所有的请求都要走AuthMD的process_request方法。

    如果URL在黑名单中,则返回This is an illegal URL的字符串;

    访问的URL在白名单内或者session中有user用户名,则不做阻拦走正常流程;

    正常的URL但是需要登录后访问,让浏览器跳转到登录页面。

    注:AuthMD中间件中需要session,所以AuthMD注册的位置要在session中间的下方。

  • 相关阅读:
    Android学习第一课
    窗体 dialog 弹出时动画效果
    poj2105 IP Address(简单题)
    #定位系统性能瓶颈# strace &amp; ltrace
    POJ2142——The Balance
    排序算法系列之八大排序算法性能比較-从实验结果分析
    DuFile网赚网盘
    一次dns缓存引发的惨案
    IT大咖说
    HTTPS与SNI扩展,一个IP绑定多个SSL证书 | VeriSign|SSL证书|数字签名证书|服务器证书|微软代码签名证书|Symantec
  • 原文地址:https://www.cnblogs.com/changwentao/p/9669691.html
Copyright © 2020-2023  润新知