개발 기록
[Django] DRF - 회원가입 , simple jwt 토큰 발행받기 본문
1. 회원가입
accounts/models.py - 가입시 이메일과 비밀번호만 입력
from django.contrib.auth.base_user import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin
from django.db import models
from accounts.managers import UserManager
class User(AbstractBaseUser,PermissionsMixin):
email = models.EmailField(verbose_name='email id', db_index=True, null=False, blank=False, unique=True,
help_text='EMAIL ID')
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
objects = UserManager()
def __str__(self):
return self.email
accounts/managers.py -커스텀 유저모델 사용시 usermanager 클래스 필요
from django.contrib.auth.base_user import BaseUserManager
class UserManager(BaseUserManager):
# All user
def create_user(self, email, password=None):
if email is None:
raise TypeError('Users must have an email address.')
if password is None:
raise TypeError('Users must have a password.')
user = self.model(
email=self.normalize_email(email)
)
# django 에서 제공하는 password 설정 함수
user.set_password(password)
user.save(using=self.db)
return user
# admin user
def create_superuser(self, email, password=None):
user = self.create_user(
email,
password=password,
)
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
프로젝트 urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('user/', include('accounts.urls')),
]
accounts/urls.py
urlpatterns = [
path('signup/', CreateUserAPIView.as_view()),
]
accounts/serializers.py
class UserCreateSerializer(serializers.ModelSerializer):
password = serializers.CharField(write_only=True)
def create(self, validated_data):
user = User.objects.create_user(
email=validated_data['email'],
password=validated_data['password']
)
return user
class Meta:
model = User
fields = ['id', 'email', 'password']
accounts/views.py
class CreateUserAPIView(APIView):
permission_classes = (AllowAny,)
serializer_class = UserCreateSerializer
def post(self, request):
user = request.data
serializer = self.serializer_class(data=user)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
2. 로그인
그냥 jwt는 import도 안되고 찾아보니 simple-jwt 사용을 권장하고 있다고 하여 사용해봄
settings.py
INSTALLED_APPS = [
# 추가
'rest_framework',
'rest_framework_simplejwt',
]
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
),
}
REST_USE_JWT = True
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(hours=2),
'REFRESH_TOKEN_LIFETIME': timedelta(days=7),
'ROTATE_REFRESH_TOKENS': False,
'TOKEN_USER_CLASS': 'accounts.User',
}
accounts/urls.py
urlpatterns = [
path('', UserViewSet.as_view(actions={
'get': 'list'
}), name='user-list'),
path('signup/', CreateUserAPIView.as_view()),
# 추가
path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), # 난 login/으로 바꿔서 사용함
path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
]
발행된 access토큰을 가지고 다른 api 접근 가능
참고문서
https://django-rest-framework-simplejwt.readthedocs.io/en/latest/getting_started.html
'Python > Django' 카테고리의 다른 글
[Django] soft delete (논리 삭제) 구현 (0) | 2022.04.07 |
---|---|
[Django] simple-jwt 로그아웃 Api + blacklist app (0) | 2022.04.06 |
[Django] admin 계정 관련 오류 (0) | 2022.04.05 |
[Django] Manager isn’t available; ‘auth.User’ has been swapped for ‘accounts.User’ 에러 (0) | 2022.04.05 |
[Django] 태그 설정 (0) | 2022.04.05 |
Comments