47 lines
		
	
	
		
			1.5 KiB
		
	
	
	
		
			Python
		
	
	
	
			
		
		
	
	
			47 lines
		
	
	
		
			1.5 KiB
		
	
	
	
		
			Python
		
	
	
	
| 
 | |
| from django.shortcuts import render
 | |
| from rest_framework.views import APIView
 | |
| from rest_framework.response import Response
 | |
| from rest_framework import status
 | |
| from django.contrib.auth import authenticate, login, logout
 | |
| from rest_framework.generics import CreateAPIView
 | |
| from rest_framework.permissions import IsAuthenticated
 | |
| 
 | |
| from apps.auth1.serializers import LoginSerializer
 | |
| # Create your views here.
 | |
| 
 | |
| class TokenBlackView(APIView):
 | |
|     permission_classes = [IsAuthenticated]
 | |
| 
 | |
|     def get(self, request, *args, **kwargs):  # 可将token加入黑名单
 | |
|         return Response(status=status.HTTP_200_OK)
 | |
|     
 | |
| class LoginView(CreateAPIView):
 | |
|     authentication_classes = []
 | |
|     permission_classes = []
 | |
|     serializer_class = LoginSerializer
 | |
|     
 | |
|     def create(self, request, *args, **kwargs):
 | |
|         """
 | |
|         账户密码登录
 | |
|         """
 | |
|         serializer = self.get_serializer(data=request.data)
 | |
|         serializer.is_valid(raise_exception=True)
 | |
|         vdata = serializer.validated_data
 | |
|         user = authenticate(username = vdata.get('username'), 
 | |
|                             password = vdata.get('password'))
 | |
|         if user is not None:
 | |
|             login(request, user)
 | |
|             return Response()
 | |
|         return Response('登录失败', status=status.HTTP_400_BAD_REQUEST)
 | |
| 
 | |
| class LogoutView(APIView):
 | |
|     authentication_classes = []
 | |
|     permission_classes = []
 | |
|     
 | |
|     def post(self, request, *args, **kwargs):
 | |
|         """
 | |
|         退出登录
 | |
|         """
 | |
|         logout(request)
 | |
|         return Response() |