pip install bcrypt
bcrypt 설치
python을 실행하고 import bcrypt
를 한다.
만약 password '1234'라 하면, password를 해싱하기위해선 문자열 '1234'를 encode해서 bytes타입으로 변환시켜줘야 한다.
** 반대로 bytes타입을 decode하면 문자열로 변환된다.
password = '1234'
encode_password = password.encode('utf-8')
# 문자열 '1234'를 bytes타입으로 변경
** decoded_password = encoded_password.decode('utf-8')
# 인코드된 패스워드를 다시 decode하기
hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt() )
# 인코드된 패스워드를 bcrypt로 해싱하기
class SignInView(View):
def post(self, request):
data = json.loads(request.body)
if Account.objects.filter(email = data['email']).exists():
## 프론트엔드에게 전달받은 아이디 값이 데이터베이스에 존재하는지 확인하는 과정
account = Account.objects.get(email = data['email'])
if bcrypt.checkpw(data['password'].encode('utf-8'), account.password):
## 프론트엔드에게 전달받은 패스워드를 인코딩 한 것과 위에서 이메일이 맞으면 그 이메일과 함께 저장된 해싱패스워드를 확인하는 과정
pip install pyjwt
jwt 설치
python을 실행하고 import jwt
입력
token=jwt.encode({'id':account.id}, SECRET_KEY, algorithm='HS256')
## account의 id를 jwt로 인코드하는 과정
return JsonResponse({'token':token.decode('utf-8')}, status=200)
## 토큰을 프론트엔드에게 보내줄때는 다시 decode해서 보내준다.
** 여기서 인코드할때 id값이 payload에 담기는데 payload에 password를 담으면 안된다. id값은 숫자로만 되어있고 이 id의 담긴 내용을 확인하기 위해서는 DB에 접속해서 내용을 확인해야 하기 때문에 id를 인코드하는 것이다.