中间件登录验证(白名单,黑名单)
中间件版的登录验证需要依靠session,所以数据库中要有django_session表。
urls.py
from django.conf.urls import url from app01 import views urlpatterns = [ url(r'^index/$', views.index), url(r'^login/$', views.login, name='login'), ] urls.py
views.py
from django.shortcuts import render, HttpResponse, redirect def 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") views.py
login,html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>登录页面</title> </head> <body> <form action="{% url 'login' %}"> <p> <label for="user">用户名:</label> <input type="text" name="user" id="user"> </p> <p> <label for="pwd">密 码:</label> <input type="text" name="pwd" id="pwd"> </p> <input type="submit" value="登录"> </form> </body> </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中间的下方。