中间件版的登录验证需要依靠session,所以数据库中要有django_session表。
urls.py
from django.conf.urls import urlfrom app01 import viewsurlpatterns = [ url(r'^index/$', views.index), url(r'^login/$', views.login, name='login'),]
views.py
from django.shortcuts import render, HttpResponse, redirectdef index(request): return HttpResponse('this is index')def home(request): return HttpResponse('this is home')def login(request): if request.method == "POST": user = request.POST.get("user") pwd = request.POST.get("pwd") if user == "Q1mi" and pwd == "123456": # 设置session request.session["user"] = user # 获取跳到登陆页面之前的URL next_url = request.GET.get("next") # 如果有,就跳转回登陆之前的URL if next_url: return redirect(next_url) # 否则默认跳转到index页面 else: return redirect("/index/") return render(request, "login.html")
login.html
登录页面
middlewares.py
class AuthMD(MiddlewareMixin): white_list = ['/login/', ] # 白名单 balck_list = ['/black/', ] # 黑名单 def process_request(self, request): from django.shortcuts import redirect, HttpResponse next_url = request.path_info print(request.path_info, request.get_full_path()) if next_url in self.white_list or request.session.get("user"): return elif next_url in self.balck_list: return HttpResponse('This is an illegal URL') else: return redirect("/login/?next={}".format(next_url))
在settings.py中注册
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', 'middlewares.AuthMD',]
注
AuthMD中间件注册后,所有的请求都要走AuthMD的process_request方法。访问的URL在白名单内或者session中有user用户名,则不做阻拦走正常流程;如果URL在黑名单中,则返回This is an illegal URL的字符串;正常的URL但是需要登录后访问,让浏览器跳转到登录页面。!:AuthMD中间件中需要session,所以AuthMD注册的位置要在session中间的下方。