[Westagram]:JWTへのログインの適用


課題



1.実施前の考え方


認証/承認時にjwtを学習したので適用できます.

2.実施

class LoginView(View) :
    def post(self, request) :
        try :
            data = json.loads(request.body)

            email    = data['email']
            password = data['password']
        
            if not User.objects.filter(email=email).exists() :
                return JsonResponse({'message':'INVALID_USER BY EMAIL'}, status=401)
            
            user = User.objects.get(email=email)

            inputed_password = password.encode('utf-8')
            db_password      = user.password.encode('utf-8')

            if bcrypt.checkpw(inputed_password, db_password) :

                token = jwt.encode({'email':email, 'exp':timezone.now()+timedelta(weeks=3)}, MY_SECRET_KEY, MY_ALGORITMS)
            
                return JsonResponse({'message':'SUCCESS', 'token':token}, status=200)
            
            return JsonResponse({'message':'INVALID USER BY PASSWORD'}, status=401)

        except KeyError :
            return JsonResponse({'message':'KEY_ERROR'}, status=400)

3.メンターからのフィードバック



4.最終

class LoginView(View) :
    def post(self, request) :
        try :
            data = json.loads(request.body)

            email    = data['email']
            password = data['password']

            if not User.objects.filter(email=email).exists() :
                return JsonResponse({'message':'Email is not existed'}, status=401)

            db_password = User.objects.get(email=email).password

            if not bcrypt.checkpw(password.encode('utf-8'), db_password.encode('utf-8')) :
                return JsonResponse({'message':'Password is not existed'}, status=401)
            
            token = jwt.encode({'email':email, 'exp':timezone.now()+timedelta(weeks=3)}, SECRET_KEY, ALGORITHMS)

            return JsonResponse({'token':token}, status=201)

        except KeyError :
            return JsonResponse({'message':'KEY_ERROR'}, status=401)

        except NameError :
            return JsonResponse({'message':'name is not defined'}, status=401)

        except json.decoder.JSONDecodeError :
            return JsonResponse({'message':'값을 하나라도 입력하세요'})

5.後期


ううう