DRF之認證
阿新 • • 發佈:2022-04-08
登入功能
models.py
from django.db import models # Create your models here. class User(models.Model): username = models.CharField(max_length=32) password = models.CharField(max_length=32) user_type = models.IntegerField(choices=((1, '超級管理員'), (2, '普通管理員',), (3, '普通使用者'))) class UserToken(models.Model): userView Code= models.OneToOneField(to=User, on_delete=models.CASCADE) token = models.CharField(max_length=32)
views.py
from django.shortcuts import render # Create your views here. from rest_framework.viewsets import ViewSet from rest_framework.decorators import action from .models import User, UserTokenView Codefrom rest_framework.response import Response import uuid class UserView(ViewSet): @action(methods=['POST'], detail=False) def login(self, request): username = request.data.get('username') password = request.data.get('password') user = User.objects.filter(username=username, password=password).first()if user: # 登入成功--生成一個隨機字串--存在token表中(如果之前有記錄,更新,如果沒有新增) token = str(uuid.uuid4()) UserToken.objects.update_or_create(user=user, defaults={'token': token}) # 如果存在就更新,如果不存在就新增 return Response({'code': 100, 'msg': '登陸成功', 'token': token}) else: return Response({'code': 101, 'msg': '使用者名稱或者密碼錯誤'})
urls.py
from django.contrib import admin from django.urls import path,include from app01 import views from rest_framework.routers import SimpleRouter router = SimpleRouter() router.register('user', views.UserView, 'user') urlpatterns = [ path('admin/', admin.site.urls), path('', include(router.urls)), ]View Code
認證類
認證類:用來校驗使用者是否登入,如果登入了,繼續往下走,如果沒有登陸,直接返回
編寫步驟
第一步
寫一個類,繼承BaseAuthentication,重寫authenticate,在方法中做校驗,校驗是否登入,返回兩個值,沒有登入拋異常
第二步
全域性配置,在配置檔案中
REST_FRAMEWORK={ "DEFAULT_AUTHENTICATION_CLASSES":["app01.auth.LoginAuth",] }
區域性配置,在檢視類中
class UserView(ViewSet): authentication_classes = [LoginAuth]
區域性禁用
class UserView(ViewSet): authentication_classes = []
具體程式碼
auth.py(自己寫的)
from rest_framework.authentication import BaseAuthentication from .models import UserToken from rest_framework.exceptions import AuthenticationFailed class LoginAuth(BaseAuthentication): def authenticate(self, request): token = request.query_params.get('token') user_token = UserToken.objects.filter(token=token).first() if user_token: # 登入了 # 返回兩個值,第一個當前登入使用者,第二個token返回 return user_token.user, token else: # 丟擲認證失敗的異常 raise AuthenticationFailed('你沒有登入')View Code
models.py
class Book(models.Model): name = models.CharField(max_length=32) price = models.IntegerField() author = models.CharField(max_length=32)View Code
views.py
from rest_framework.viewsets import ModelViewSet from .models import Book from .serializer import BookSerializer from .auth import LoginAuth class BookView(ModelViewSet): # authentication_classes = [LoginAuth, ] queryset = Book.objects.all() serializer_class = BookSerializerView Code
認證類中返回的兩個變數
返回的第一個,給了request.user,就是當前登入使用者
返回的第二個,給了request.auth,就是token串