웹 사이트에서 필수적인 작업인 회원가입과 로그인 기능을 장고에서 구현해보는 간단한 예제를 실습해보자! 👊
먼저, 이전에 포스트 했던 장고 프로젝트 초기설정을 해준다.
먼저 필요한 패키지들을 설치해준다.
pip install bcrypt
pip install pyjwt
from django.db import models
class Account(models.Model):
email = models.CharField(max_length = 100)
password = models.CharField(max_length = 200)
created_at = models.DateTimeField(auto_now_add = True)
class Meta:
db_table = 'accounts'
import json
import bcrypt
import jwt
from django.views import View
from django.http import (
HttpResponse,
JsonResponse
)
from django.core.validators import validate_email
from django.core.exceptions import ValidationError
from westagram.settings import (
SECRET_KEY,
ALGORITHM
)
from .models import Account
class SignUpView(View):
def post(self, request):
data = json.loads(request.body)
try:
validate_email(data['email'])
if Account.objects.filter(email = data['email']).exists():
return JsonResponse({'message' : 'ALREADY_EXISTS'}, status = 200)
hashed_password = bcrypt.hashpw(data['password'].encode('utf-8'), bcrypt.gensalt())
Account.objects.create(
email = data['email'],
password = hashed_password.decode('utf-8')
)
return HttpResponse(status = 200)
except ValidationError:
return JsonResponse({'message' : 'FAILED_VALIDATION'}, status = 422)
except KeyError:
return JsonResponse({'message' : 'INVALID_KEY'}, status = 400)
#account/urls.py
from django.urls import path
from .views import SignUpView
urlpatterns = [
path('/sign-up', SignUpView.as_view()),
]
http -v localhost:8000/account/sign-up email='bmo@example.com' password='p1234!'
class SignInView(View):
def post(self, request):
data = json.loads(request.body)
try:
if Account.objects.filter(email = data['email']).exists():
user = Account.objects.get(email = data['email'])
if bcrypt.checkpw(data['password'].encode('utf-8'), user.password.encode('utf-8')):
access_token = jwt.encode({'id' : user.id}, SECRET_KEY, algorithm = ALGORITHM)
return JsonResponse({'access_token' : access_token.decode('utf-8')}, status = 200)
return JsonResponse({'message' : 'UNAUTHORIZED'}, status = 401)
return JsonResponse({'message' : 'UNAUTHORIZED'}, status = 401)
except KeyError:
return JsonResponse({'message' : 'INVALID_KEY'}, status = 400)
from django.urls import path
from .views import (
SignUpView,
SignInView
)
urlpatterns = [
path('/sign-up', SignUpView.as_view()),
path('/sign-in', SignInView.as_view()),
]
http -v localhost:8000/account/sign-in email='bmo@example.com' password='p1234!'
{
"access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6Mn0.EeZ4LBk-Bqk1wElV-qijnAhbpbdobYFjqJ_21f7OEsk"
}