💻 로그인 구현
# serializers.py
class LoginSerializer(serializers.ModelSerializer):
email = serializers.EmailField(max_length=255, min_length=3)
password = serializers.CharField(max_length=68, min_length=3, write_only=True)
access_token = serializers.CharField(max_length=68, read_only=True)
refresh_token = serializers.CharField(max_length=68, read_only=True)
class Meta:
model = User
fields = ['email', 'password','access_token', 'refresh_token']
# views.py
class LoginAPIView(GenericAPIView):
queryset = User.objects.all()
serializer_class = LoginSerializer
renderer_classes = [JSONRenderer]
def post(self,request):
# CASE1 : serializer_class 사용할 경우
serializer = self.serializer_class(data=request.data)
serializer.is_valid(raise_exception=True) # 값이 잘 들어갔는지 확인.
return Response(serializer.data, status=status.HTTP_200_OK)
# CASE2 : Serializer 사용하지 않을 경우
user_email = request.data['email']
user_password = request.data['password']
check = self.queryset.filter(email=user_email).first()
if check.password != user_password:
return Respone(status=status.HTTP_400_BAD_REQUEST)
user = auth.authenticate(email=user_email, password=user_password)
user_token = user.tokens()
obj = {
"user_email" : user_email,
"user_access_token" : user_token['access token'],
"user_refressh_token" : user_token['refresh token']
}
return Response(obj, status=status.HTTP_200_OK)
💻 회원정보
# serializers.py
class UserDetailSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['username']
# views.py
class UserDetailView(GenericAPIView):
queryset = User.objects.all()
serializer_class = UserDetailSerializer
permission_classes = (permissions.IsAuthenticated,IsOwner)
def get(self, request, *args, **kwargs):
username = request.query_params.get('username')
user_info_query = self.queryset.filter(username=username).first()
if not user_info_query:
return Response(status=status.HTTP_204_NO_CONTENT, data={"result":"No User"})
user_info = {
"username" : user_info_query.username,
"email" : user_info_query.email,
"phone" : user_info_query.phone,
"gender" : user_info_query.gender,
}
return Response(user_info, status=status.HTTP_200_OK)