目录
templates/login/login.html
templates/login/404.html
views/login.py
utils/pwd_data.py
auth.py
settings.py
登录及权限
登录
views.py
中间件
auth.py
templates/login/login.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="{% static 'css/bootstrap.css'%}">
</head>
<body>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
html {
height: 100%;
}
body {
height: 100%;
}
.container {
height: 100%;
width: 100%;
background-image: linear-gradient(to right, #fbc2eb, #a6c1ee);
}
.login-wrapper {
background-color: #fff;
width: 358px;
height: 588px;
border-radius: 15px;
padding: 0 50px;
position: relative;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
.header {
font-size: 38px;
font-weight: bold;
text-align: center;
line-height: 200px;
}
.input-item {
display: block;
width: 100%;
margin-bottom: 20px;
border: 0;
padding: 10px;
border-bottom: 1px solid rgb(128, 125, 125);
font-size: 15px;
outline: none;
}
.input-item:placeholder {
text-transform: uppercase;
}
.btn {
text-align: center;
padding: 10px;
width: 100%;
margin-top: 40px;
background-image: linear-gradient(to right, #a6c1ee, #fbc2eb);
color: #fff;
}
.msg {
text-align: center;
line-height: 88px;
}
a {
text-decoration-line: none;
color: #abc1ee;
}
</style>
</head>
<body>
<div class="container">
<div class="login-wrapper">
<div class="header">Login</div>
<div class="form-wrapper">
<form method="post" novalidate>
{% csrf_token %}
{{ form.username }}
{{ form.password }}
<span style="color: red">{{ form.password.errors.0 }}</span>
<button class="btn" type="submit">Login</button>
</form>
</div>
</div>
</div>
</body>
</html>
</body>
</html>
templates/login/404.html
--防止越权访问目录及文件...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div style="background-color: red;width: 500px; height: 500px">没权限</div>
</body>
</html>
views/login.py
# -*- coding:utf-8 -*-
import requests
from django.shortcuts import render, redirect, HttpResponse
from demo_one.utils import pwd_data
from django import forms
from demo_one import models
class LoginForm(forms.Form):
username = forms.CharField(label="用户名", widget=forms.TextInput(
attrs={"class": "input-item", "autocomplete": "off", "placeholder": "请输入用户名"}))
password = forms.CharField(label="密码", widget=forms.PasswordInput(
attrs={"class": "input-item", "autocomplete": "off", "placeholder": "请输入密码"}))
def clean_password(self):
pwd = self.cleaned_data.get("password")
# print(self.cleaned_data)
return pwd_data.md5(pwd)
def login(request):
if request.method == "GET":
form = LoginForm()
return render(request, "login/login.html", {"form": form})
form = LoginForm(data=request.POST)
if form.is_valid():
# 去数据库进行校验
# print(form.cleaned_data)
admin_object = models.Adminrole.objects.filter(**form.cleaned_data).first()
if not admin_object:
# 给输入框添加一个错误提示
form.add_error("password", "用户名或密码错误")
return render(request, "login/login.html", {"form": form})
# 登录成功之后
# 将登录信息存储在session当中
request.session["info"] = {"id": admin_object.id, "username": admin_object.username,
"password": admin_object.password, "role": admin_object.role}
# 时效性
request.session.set_expiry(60 * 60 * 24 * 30)
# 登录成功后跳转到首页
return redirect("/")
return render(request, "login/login.html", {"form": form})
def logout(request):
request.session.clear()
return redirect("/login/")
utils/pwd_data.py
--登录密码进行加密传输.
# -*- coding:utf-8 -*-
import hashlib
SECRET_KEY = ''
def md5(data):
# 加盐
obj_md5 = hashlib.md5(SECRET_KEY.encode("utf-8"))
obj_md5.update(data.encode("utf-8"))
return obj_md5.hexdigest()
auth.py
--登录&权限进行校验.(不同权限看到的内容信息量不一样.)
# -*- coding:utf-8 -*-
import requests
from django.shortcuts import redirect,HttpResponse,render
from django.utils.deprecation import MiddlewareMixin
from django.conf import settings
class AuthMiddleware(MiddlewareMixin):
# 登录校验
def process_request(self, request):
# 登录页无需校验
if request.path_info in ["/login/", "/logout/"]:
return
# 读取当前用户的信息,如果读取到了,说明已经登录成功
info_dict = request.session.get("info")
if info_dict:
request.unicom_id = info_dict["id"]
request.unicom_username = info_dict["username"]
request.unicom_role = info_dict["role"]
return
return redirect("/login/")
# 权限校验
def process_view(self, request, view_func, args, kwargs):
if request.path_info in ["/login/", "/logout/"]:
return
# 获取当前用户的角色身份
role = request.unicom_role
# 获取当前角色不具备的权限
user_permission_list = settings.UNICOM_PERMISSION[role]
# 当前身份有哪些权限
if request.resolver_match.url_name not in user_permission_list:
return
return render(request, "login/404.html")
settings.py
(不同权限看到的内容信息量不一样.)
登录及权限
登录
-
views.py
# -*- coding:utf-8 -*- import requests from django.shortcuts import render, redirect, HttpResponse from demo_one.utils import pwd_data from django import forms from demo_one import models class LoginForm(forms.Form): username = forms.CharField(label="用户名", widget=forms.TextInput( attrs={"class": "input-item", "autocomplete": "off", "placeholder": "请输入用户名"})) password = forms.CharField(label="密码", widget=forms.PasswordInput( attrs={"class": "input-item", "autocomplete": "off", "placeholder": "请输入密码"})) def clean_password(self): pwd = self.cleaned_data.get("password") # print(self.cleaned_data) return pwd_data.md5(pwd) def login(request): if request.method == "GET": form = LoginForm() return render(request, "login/login.html", {"form": form}) form = LoginForm(data=request.POST) if form.is_valid(): # 去数据库进行校验 # print(form.cleaned_data) admin_object = models.Adminrole.objects.filter(**form.cleaned_data).first() if not admin_object: # 给输入框添加一个错误提示 form.add_error("password", "用户名或密码错误") return render(request, "login/login.html", {"form": form}) # 登录成功之后 # 将登录信息存储在session当中 request.session["info"] = {"id": admin_object.id, "username": admin_object.username, "password": admin_object.password, "role": admin_object.role} # 时效性 request.session.set_expiry(60 * 60 * 24 * 30) # 登录成功后跳转到首页 return redirect("/") return render(request, "login/login.html", {"form": form}) def logout(request): request.session.clear() return redirect("/login/")
中间件
-
auth.py
# -*- coding:utf-8 -*- import requests from django.shortcuts import redirect,HttpResponse,render from django.utils.deprecation import MiddlewareMixin from django.conf import settings class AuthMiddleware(MiddlewareMixin): # 登录校验 def process_request(self, request): # 登录页无需校验 if request.path_info in ["/login/", "/logout/"]: return # 读取当前用户的信息,如果读取到了,说明已经登录成功 info_dict = request.session.get("info") if info_dict: request.unicom_id = info_dict["id"] request.unicom_username = info_dict["username"] request.unicom_role = info_dict["role"] return return redirect("/login/") # 权限校验 def process_view(self, request, view_func, args, kwargs): if request.path_info in ["/login/", "/logout/"]: return # 获取当前用户的角色身份 role = request.unicom_role # 获取当前角色不具备的权限 user_permission_list = settings.UNICOM_PERMISSION[role] # 当前身份有哪些权限 if request.resolver_match.url_name not in user_permission_list: return return render(request, "login/404.html")
-
settings.py
UNICOM_PERMISSION = { "admin": [], "teacher": ["admin_list", "add_admin", "modify_admin", "del_admin", "reset_admin"], "user": ["admin_list", "add_admin", "modify_admin", "del_admin", "reset_admin", "asset_data", "add_asset", "modify_asset", "delete_asset", "del_data"] }