::: 현재까지 진행 상황 :::
- 초기 세팅 완료
- Users 앱 생성 완료
- models.py의 User 클래스 작성 완료
- DB에 migrate까지 진행
- 회원가입 기능 구현 (정규표현식, 예외처리 사용)
- 로그인 기능 구현 (계정, 패스워드 필터링 적용)
- 회원가입 비밀번호 암호화 구현 (bcrypt 적용)
유의사항 ::
패키지명은 pyjwt
이지만, import할 때는 jwt
$ pip install pyjwt
import json
import re
import bcrypt
import jwt
from django.http import JsonResponse
from django.views import View
from django.conf import settings
from users.models import User
class SignInView(View):
def post(self, request):
try:
data = json.loads(request.body)
email = data['email']
password = data['password']
user = User.objects.get(email=email)
(***) if not bcrypt.checkpw(password.encode('utf-8'), user.password.encode('utf-8')):
return JsonResponse({"message": "INVALID_PASSWORD"}, status=401)
(***) token = jwt.encode({'id': user.id}, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
return JsonResponse({"message": "SUCCESS", "ACCESS_TOKEN" : token}, status=200)
except KeyError:
return JsonResponse({"message": "KEY_ERROR"}, status=400)
except User.DoesNotExist:
return JsonResponse({"message": "INVALID_USER"}, status=401)
import json
import re
import bcrypt
import jwt
from django.http import JsonResponse
from django.views import View
from django.conf import settings
bcypt
& jwt
importfrom django.conf import settings
를 작성하여 의존성을 줄여준다.user = User.objects.get(email=email)
if not bcrypt.checkpw(password.encode('utf-8'), user.password.encode('utf-8')):
return JsonResponse({"message": "INVALID_PASSWORD"}, status=401)
checkpw(password, hashedPassword)
::
boolean 타입으로 비밀번호와 암호화된 비밀번호를 인자로 받아 같을 경우 ture, 아니면 false.
password 와 hasedPassword 가 동일한지를 비교함
password.encode('utf-8')
& user.password.encode('utf-8')
token = jwt.encode({'id': user.id}, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
return JsonResponse({"message": "SUCCESS", "ACCESS_TOKEN" : token}, status=200)
jwt.encode({'id':}, SECRET_KEY, algorithm)
if not User.objects.filter(email=email).exists():
return JsonResponse({'message':'INVALID_EMAIL'}, stauts=401)
>> 기존에 이메일 필터링을 위해서 작성한 코드를 "DoesNotExist" Error 예외처리로 변경
except User.DoesNotExist:
return JsonResponse({"message": "INVALID_USER"}, status=401)