[Django] 회원가입 및 로그인ver.3.5

제갈창민·2021년 12월 7일
0

learningbook

목록 보기
26/32

1. JWT 추가

class SignInView(View):
    def post(self, request):

        try:
            data          = json.loads(request.body)
            user_email    = data['email']
            user_password = data['password']
            user_id       = User.objects.get(email=user_email)
            access_token  = jwt.encode({'id':user_id.id}, SECRET_KEY, algorithm=ALGORITHM)

            #if not User.objects.filter(email=user_email).exists():
               #return JsonResponse({'message':'INVALID_USER'}, status=401)

            if bcrypt.checkpw(user_password.encode('utf-8'), user_id.password.encode('utf-8')) == False:
                return JsonResponse({'message':'Password is incorrect'}, status=401)
            return JsonResponse({'Access_token':access_token.decode('utf-8')}, status=200)

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

        except User.DoesNotExist:
            return JsonResponse({'message':'Invalid Email Format'}, status=401)
  • 주석 처리한 이메일 존재 여부 조건문은 DoesNotExist 에러를 특정해 주면서 쓸모가 없어졌다.
  • encode가 여러번 들어가는데, 컴퓨터가 읽을 수 있는 byte 형식으로 바꿔준다는 것을 유념하고 있어야, 암호를 불러오고 비교하고, 입력할때마다 encode, decode를 적절히 사용할 수 있겠다.
  • 아래는 좀 더 정제된 로그인 코드이다.
class LogInView(View):
    def post(self, request):
        try:
            data            = json.loads(request.body)
            user            = User.objects.get(email=data["email"])
            hashed_password = user.password.encode("utf-8")

            if not bcrypt.checkpw(data["password"].encode("utf-8"), hashed_password):
                return JsonResponse({"MESSAGE":"INVALID_USER"}, status=401)

            access_token = jwt.encode({"id" : user.id}, SECRET_KEY, algorithm = ALGORITHM).decode('utf-8')

            return JsonResponse({"MESSAGE":"SUCCESS", "ACCESS_TOKEN": access_token}, status=200)
        
        except json.JSONDecodeError:
            return JsonResponse({"MESSAGE": "JSONDecodeError"}, status=404)
        
        except User.DoesNotExist:
            return JsonResponse({"MESSAGE": "INVALID_USER"}, status=404)
        
        except KeyError:
            return JsonResponse({"MESSAGE" : "KEY_ERROR"}, status=400)
  • JSONDecodeError 는 이번 과제동안 한번도 볼 수 없었다. 찾아보니 다음과 같은 상황에서 발생한다고 한다.

    json.loads 를 쓸 때 발생하는데, 받는 값이 없거나 deserialize되고 있는 값이 json 형식이 아닐때 에러가 난다.
    -> json 형식을 통과할 때 읽을 수 없기 때문에 발생하는 error 다(라고 해석가능?)

  • 습관처럼 했던 변수 선언이 줄었고, bcrypt와 jwt로 변환해주는 명령어만 남았다.
  • error 종류를 잘 파악해서 except 로 정확하게 걸러주지 않으면, 내용이 맞지 않는 다른 error 끼리 서로 수렴하는 상황이 발생하기 때문에, 아무렇게나 except 를 남발하는 것은 피해야 한다.
profile
자기계발 중인 신입 개발자

0개의 댓글