上面是代码目录结构,
# 这是视图文件views.py
from django.http import JsonResponse from rest_framework.views import APIView from .models import User, UserToken from app01 import get_token class UserView(APIView): def post(self, request): response = dict() try: user_name = request.data['username'] password = request.data['password'] user_obj = User.objects.filter(user_name=user_name, password=password).first() if user_obj: access_token = get_token.generate_token() UserToken.objects.update_or_create(user=user_obj, defaults={"token": access_token}) response["status_code"] = 200 response["status_message"] = "登录成功" response["access_token"] = access_token response["user_role"] = user_obj.get_user_type_display() else: response["status_code"] = 201 response["status_message"] = "登录失败,用户名或密码错误" except Exception as e: response["status_code"] = 202 response["status_message"] = str(e) return JsonResponse(response)
# 这是路由分法urls.py
from django.contrib import admin from django.urls import path, re_path from app01 import views urlpatterns = [ path('admin/', admin.site.urls), re_path('user', views.UserView.as_view()) ]
# 这是数据库模型类models.py
class User(models.Model): """ 存储用户信息 """ user_name = models.CharField(max_length=32) password = models.EmailField(max_length=32) user_type_entry = ( (1, 'Delux'), (2, 'SVIP'), (3, "VVIP") ) user_type = models.IntegerField(choices=user_type_entry) def __str__(self): return self.user_name class UserToken(models.Model): """ 存储用户登录的token值 """ user = models.OneToOneField("User", on_delete=models.CASCADE) token = models.CharField(max_length=128)
# 这是验证类文件
from rest_framework.authentication import BaseAuthentication from rest_framework.exceptions import APIException from .models import UserToken # 第一步:定义认证类 class UserAuth(BaseAuthentication): # 所有的认证逻辑都在authenticate def authenticate(self, request): user_token = request.query_params.get("token") try: token = UserToken.objects.get(token=user_token) # 后面权限会用到 return token.user, token.token except Exception: raise APIException("没有认证") # 这个是认证类文件内容