【django】Django Rest Framework 登录/认证/注册
登录
# login.py
import redis
import traceback
from logging_files import logging_main
from django.contrib.auth.hashers import check_password
# 序列化
from django.http import JsonResponse
from rest_framework.views import APIView # 视图模块导入
from database import models # 数据表导入
from utils import datamd5 # md5加密token
Pool= redis.ConnectionPool(host='localhost',port=6379,decode_responses=True)
import redisfrom utils.redis_cli import Pool
# 创建redis连接池
class UserLogin(APIView):
"""
用户登陆认证与设置权限以及token存入redis
"""
authentication_classes = [] # 登录接口不需要token认证
def post(self, request, *args, **kwargs):
username = str(request.data.get("username"))
password = str(request.data.get("password"))
csrf = {}
if models.UserInfo.objects.filter(username = username ).exists() == False:
csrf['code'] = 1114
csrf['message'] = "账号不存在"
return JsonResponse(csrf)
try:
# 认证密码
md5_password = models.UserInfo.objects.filter(username=username).values('password')[0]['password']
res = check_password(password,md5_password)
if not res:
csrf['code'] = 10003
csrf['message'] = "账号或者密码错误"
return JsonResponse(csrf)
user_obj = models.UserInfo.objects.filter(username=username).first()
# 设置token
t = datamd5.md5(username)
# 格式化token
token = t + ":" + username + ":" + str(user_obj.pk) + ":" + str(user_obj.is_staff)
# 保存登录用户状态信息
request.session["user_id"] = user_obj.pk
# redis录入token
sr = redis.Redis(connection_pool=Pool)
sr.hset(username,"token",token)
sr.expire(username,10800) # 3个小时过期
# 返回状态
csrf['code'] = 200
csrf['message'] = "登录成功"
csrf['token'] = token
csrf['username'] = user_obj.username
return JsonResponse(csrf)
except Exception as e:
print(traceback.format_exc())
data = {}
data['code'] = 10004
data['message'] = "请求异常"
return JsonResponse(data)
认证
# auth.py
from rest_framework import exceptions
from rest_framework.authentication import BaseAuthentication # 继承认证类
from django.http import JsonResponse,HttpResponse
# 导入redis池
import redis
from utils.redis_cli import Pool
# 认证
class Authtication(BaseAuthentication):
def authenticate(self, request):
try:
# 取用户请求头的token,取redis存的token
request_token = request.META.get('HTTP_AUTHENTICATE',"")
token,username,user_id,is_staff = request_token.split(":")
sr = redis.Redis(connection_pool=Pool)
redis_token = sr.hget(username, "token")
redisToken, userName, userId, isStaff = redis_token.split(":")
# 判断登录是否有token
if not request_token or is_staff == False:
raise exceptions.AuthenticationFailed({"code": 10009, "message": "请重新登录"})
# 判断 token 正确或者是否过期
if token != redisToken:
raise exceptions.AuthenticationFailed({"code": 10009, "message": "请重新登录"})
# 刷新token有效时间
auth_token = token + ":" + username + ":" + user_id + ":" + is_staff
sr.hset(username, "token", auth_token)
sr.expire(username, 10800) # 3个小时过期
# 登录后返回给接口用的值:request.user request.auth
return (username,user_id)
except Exception as e:
# print(traceback.format_exc())
raise exceptions.AuthenticationFailed({"code":10009,"message":"请重新登录"})
def authenticate_header(self, request):
pass
注册
# register.py
import datetime
from django.contrib.auth.hashers import make_password # 密码加密
from django.http import JsonResponse
from rest_framework.views import APIView
import time
# 导入redis配置
import redis
from utils.redis_cli import Pool
import traceback
from logging_files import logging_main
from database import models
class Register(APIView):
authentication_classes = [] # 不认证身份
def post(self, request):
message = {}
try:
username = str(request.data.get("username"))
# 判断是否已存在
if models.UserInfo.objects.filter(username=username).exists() == True:
message['code'] = 10006
message['message'] = "该账号已存在"
return JsonResponse(message)
# 获取设置密码
password = str(request.data.get("password"))
# 引入redis
sr = redis.Redis(connection_pool=Pool)
# 一致 注册账号 明文密码加密
models.UserInfo.objects.create(username=username,password=make_password(password))
# 返回状态
message['code'] = 200
message['message'] = "注册成功"
return JsonResponse(message)
except:
print(traceback.format_exc())
data = {}
data['code'] = 444
data['message'] = "请求异常"
return JsonResponse(data)
Python全栈(后端、数据分析、脚本、爬虫、EXE客户端) / 前端(WEB,移动,H5) / Linux / SpringBoot / 机器学习