单点登录前戏(未使用jwt版本)
建表
from django.db import models import jwt # Create your models here. # 角色表 class RoleTable(models.Model): role = models.CharField(max_length=30, verbose_name='角色') creator = models.CharField(max_length=30, verbose_name='创建者') create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True) # 创建者 # 创建时间 def __str__(self): return self.role class Meta: db_table = 'role' # 用户表 class UserTable(models.Model): name = models.CharField(max_length=30, verbose_name='员工姓名') sex = models.CharField(max_length=10, choices=(('0', '女'), ('1', '男')), verbose_name='员工性别') username = models.CharField(max_length=32, verbose_name='用户名') password = models.CharField(max_length=32, verbose_name='密码') create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True) login_time = models.DateTimeField(verbose_name='最近登录时间', auto_now=True) role = models.OneToOneField(RoleTable, on_delete=models.CASCADE) def __str__(self): return self.name class Meta: db_table = 'user'
配置url
from django.urls import path from AccountManager import views app_name = 'account' urlpatterns = [ path('login/', views.Login, name='login'), path('add/', views.addUser, name='add'), ]
配置salt
# 加密字段 SALT = 'haxitaig!@#$%^&*' #根据公司自定制salt
创建日志
首先自己配置settings.py
LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters':{ "generic": { "format": "%(asctime)s [%(process)d] [%(levelname)s] %(message)s", "datefmt": "[%Y-%m-%d %H:%M:%S %z]", "class": "logging.Formatter" }, "access": { "format": "%(message)s", "class": "logging.Formatter" } }, 'loggers': { "AuthCert.error": { "level": "INFO", "handlers": ["error_file"], "propagate": 1, "qualname": "AuthCert.error" }, "AuthCert.access": { "level": "INFO", "handlers": ["access_file"], "propagate": 0, "qualname": "AuthCert.access" } }, 'handlers': { "console": { "class": "logging.StreamHandler", "formatter": "generic", "stream": "sys.stdout" }, "error_file": { "class": "logging.FileHandler", "formatter": "generic", "filename": "./log/error.log" }, "access_file": { "class": "logging.handlers.RotatingFileHandler", "maxBytes": 1024 * 1024, "backupCount": 5, "formatter": "generic", "filename": "./log/acess.log", } }, }
接着,在views.py中生成logging
import logging logger = logging.getLogger('AuthCert.error') #然后使用logger.ingo('')、 logger.error('')
添加数据
def addUser(request): """ 增加用户 """ if request.method == "POST": #添加数据 role = request.POST.get('role') # creator = request.POST.get('creator') name = request.POST.get('name') sex = request.POST.get('sex') username = request.POST.get('username') password = request.POST.get('password') # if not all([role, creator, name, sex, username, password]): if not all([role, name, sex, username, password]): #如果参数没有填写完毕,返回‘参数不全’ logger.error('canshubuquan') return HttpResponse('参数不全') # 对密码进行MD5加密 else: try: pwd_salt = password + SALT #对前端填写的password进行加盐 password = hashlib.md5(pwd_salt.encode()) password = password.hexdigest() print('password= ', password) # 保存角色数据导数据库 Role = RoleTable() Role.role = role # Role.creator = creator Role.save() # 保存用户数据到数据库 User = UserTable() User.role = Role User.name = name User.sex = sex User.username = username User.password = password User.save() logger.info('增加用户成功') return HttpResponse('add user success') except Exception as e: logger.error(e) return HttpResponse(e) else: return render(request, 'add.html')
用户登录
def Login(request): """ 用户登录 """ if request.method == "POST": username = request.POST.get('username') pwd = request.POST.get('password') pwd_salt = pwd + SALT #使用salt加密pwd password = hashlib.md5(pwd_salt.encode()) password = password.hexdigest() user = UserTable.objects.filter(username=username, password=password) #使用前端获取的username,和加密后的pwd,与数据库里的username,pwd进行对比 if len(user): logger.info('success') #打印日志 return HttpResponse('登录成功') else: logger.error('username 、 password Error') return HttpResponse('用户名密码不正确') else: return render(request, 'login.html')