[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. 후기

ㅠㅠ

좋은 웹페이지 즐겨찾기