๊ฐ์ธ์ ๋ณด ๋ณดํธ๋ฅผ ์ํด ์ํธ๋ฅผ ๋จ๋ฐฉํฅ ํด์ฌํ ํ๋ค ๋์์ ๋ก๊ทธ์ธํ๋ฉด ํ ํฐ์ ๋ฐ๊ธํด์ฃผ๋ ๋จ๊ณ์ด๋ค.
ํด๋น ๋ด์ฉ์ ๋ํ ์์ธํ๋ด์ฉ์ ์ฌ๊ธฐ๋ฅผ ์ฐธ์กฐ!
#my_settings.py
ALGORITHM = 'HS256'
b
๋ก ์์๋๋๋จ์ด๋ค์ด decode๋ฅผ ํ์ง ์์ byteํ์
์ผ๋ก ์ ์ฅ๋ ๋น๋ฐ๋ฒํธ๋ค์ด๋ค.password = bcrypt.hashpw(data['password']. encode('utf-8'),bcrypt.gensalt()).decode())
bcrypt
๊ณผ์ ์์ ํด์ฌํ๋ ๋น๋ฐ๋ฒํธ๋ฅผ db์ ์ ์ฅํ ๋ ๋ฐ๋์ decode๋ฅผ ๋ถ์ฌ strํ์
์ธ ์ฑ๋ก ์ ์ฅ๋๊ฒ ํด์ฃผ์!(์๊ทธ๋ฌ๋ฉด ๋์ค์ decodeํด์ค์ผํ๋ ๋์ค์์ํด..)
import json, bcrypt, jwt, re
from django.http import JsonResponse
from django.views import View
from user.models import Account
from my_settings import SECRET,ALGORITHM
class AccountView(View):
def post(self, request):
data = json.loads(request.body)
REGAX_EMAIL = '^[a-zA-Z0-9+-_.]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-. ]+$'
REGEX_PASSWORD = '^[A-Za-z0-9@#$%^&+=]{8,}$'
try:
if not re.match(email_validation, data['email']):
return JsonResponse(
{"message":"INVALID_MAIL"},status=401
)
if not re.match(pw_validation, data['password']):
return JsonResponse(
{"message":"INVALID_PW"},status=401
)
if Account.objects.filter(email=data['email']).exists():
return JsonResponse(
{"message":"USER_EXIST"},status=400
)
else:
Account.objects.create(
email = data['email'],
password = bcrypt.hashpw(data['password']. encode('utf-8'),bcrypt.gensalt()).decode()
)
return JsonResponse({"message":"SUCCESS"},status=200)
except:
return JsonResponse({"message":"KEY_ERROR"},status=401)
bcrypt, jwt๋ฅผ importํด์ ์ธ์ฆ&์ธ๊ฐ์ ์ฌ์ฉํ๋ค.
class LoginView(View):
def post(self, request):
data = json.loads(request.body)
user_pw = Account.objects.get(email=data['email']).password
user_id = Account.objects.get(email=data['email']).id
password_check = bcrypt.checkpw(data['password'].encode('utf- 8'),user_pw.encode('utf-8'))
try:
if Account.objects.all().filter(email=data['email']). exists():
if bcrypt.checkpw(data['password'].encode('utf-8'). user_pw.encode('utf-8')):
access_token = jwt.encode({'id' : user_id}, SECRET,ALGORITHM).decode('utf-8')
return JsonResponse({"message":"SUCCESS", "TOKEN" : access_token},status=200)
return JsonResponse({"message":"INVALID_PASSWORD"}, status=402)
except KeyError:
return JsonResponse({"message":"KEY_ERROR"},status=401)
except ValueError:
return JsonResponse({"message":"INVALID_USER"}, status=401)
์น๊ณ ๋ณด๋ฉด ๊ฐ๋จํ๋ฐ ์ด๊ฑธ ์ดํดํ๊ณ ๋ฉ๋ํ๋๋ฐ ํ์ฃผ๋ฅผ ๋ณด๋๋ค.
ํ์ฌ ํ๋ก์ ํธ ์งํ์ค์ธ๋ฐ ๋ชจ๋ ์ฌ์ดํธ๋ ์ผ๋จ ๋ก๊ทธ์ธ๊ณผ ํ์๊ฐ์ ์ด ํ์์ ์ผ๋ก ์์ด์, ํ๋ฒ ์ ๋ฆฌํด๋ณด์๋ค! ํ๋ก์ ํธ ํ์ดํ !!!