Django-React 로그인 연결하기(1. Django 설정)

KHoney·2022년 7월 24일
0

futqualizer

목록 보기
6/8

Django

필요한 라이브러리를 설치한다.

pip install django-cors-headers==3.13.0
pip install django-rest-auth==0.9.5
pip install djangorestframework==3.13.1
pip install django-allauth==0.51.0

Django 의 Setting.py 에 설정 변수들을 추가한다.

#setting.py
INSTALLED_APPS = [
    'corsheaders',
		...
    'rest_framework.authtoken',
    'rest_auth',
    'rest_auth.registration',
    'allauth',
    'account' # User 계정을 정의할때 쓰일 app
]
...
MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
		...
]
...
CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = (
    'http://localhost:3000', # react의 포트번호
    'http://127.0.0.1:3000',
    'http://localhost:8000', # django의 포트번호
    'http://127.0.0.1:8000'
)
...
#CSRF token Header 이름 설정
CORS_ALLOW_HEADERS = list(default_headers) + [
    'X-CSRFTOKEN',
]
...
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
				# react Template 경로
        'DIRS': [
             os.path.join(BASE_DIR, 'react-ui', 'build'),
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
...
# react template 경로
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'react-ui', 'build', 'static')
]

# 기본으로 제공하는 것 말고 새로운 유저 정보를 이용할 것이다.
# Custom Auth User
AUTH_USER_MODEL = 'account.User'

# rest_framework 세팅
REST_FRAMEWORK = {
    'DATETIME_FORMAT': "%m/%d/%Y %I:%M%P",
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
    ],
}
#authentication 세팅
AUTHENTICATION_BACKENDS = (    
	"django.contrib.auth.backends.ModelBackend",    
    "allauth.account.auth_backends.AuthenticationBackend",
)

account App 에 CustomUser 를 선언한다.

#/account/models.py
from djongo import models
from django.contrib.auth.models import (BaseUserManager, AbstractBaseUser)
from player.models import Player

class UserManager(BaseUserManager):
		# register 실행시
    def create_user(self, username, password=None):
        user = self.model(
            username=username,       
        )
        user.set_password(password)
        user.save(using=self._db)
        return user
		# createsuperuser 실행시
    def create_superuser(self, username, password):
        user = self.create_user(
            username,          
            password=password,            
        )
        user.is_admin = True
        user.save(using=self._db)
        return user

#Custom User
class User(AbstractBaseUser):
    username = models.CharField(        
        max_length=20,
        null=False,
        unique=True,
        default=''
    )     
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)
    team = models.ManyToManyField(Player,related_name='team_user')

    objects = UserManager()

		#PK 를 변경할수도 있다.
    USERNAME_FIELD = 'username'

    def __str__(self):
        return self.username

    def has_perm(self, perm, obj=None):
        return True

    def has_module_perms(self, app_label):
        return True

    @property
    def is_staff(self):
        return self.is_admin

serializer 설정

#/account/serializers.py
from .models import User

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('username', 'last_login', 'date_joined', 'is_staff')

forms.py

#/account/forms.py
from django import forms
from django.contrib.auth.forms import ReadOnlyPasswordHashField, AuthenticationForm
from .models import User

class UserCreationForm(forms.ModelForm):
    password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
    password2 = forms.CharField(
        label='Password confirmation', widget=forms.PasswordInput)
    class Meta:
        model = User
        fields = ('username',)
    def clean_password2(self):
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("Passwords don't match")
        return password2
    def save(self, commit=True):
        user = super().save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user

class UserChangeForm(forms.ModelForm):
    password = ReadOnlyPasswordHashField()
    class Meta:
        model = User
        fields = ('username','password','is_active', 'is_admin')
    def clean_password(self):
        return self.initial["password"]

account/url 설정

#/account/urls.py
from django.urls import path, include
from . import views
from django.contrib.auth import views as auth_views

app_name= 'account'
urlpatterns = [
    path('', include('rest_auth.urls')), # auth 기본 url
    path('register/', include('rest_auth.registration.urls')) # 회원가입 url
]

기본 url 설정

#futQualizer/urls.py
from django.contrib import admin
from django.urls import path, include, re_path
from account.views import index
urlpatterns = [    
		...
    path('auth/',include('account.urls')), # 추가
		...
]

위 사항들로

Django 에서 설정해 줄 것은 모두 끝났다.

login 시 계정별 Token 을 사용 할것이기 때문에, 기본적으로 makemigraiton, migrate를 하고, 추가로 authtoken 도 migrate 해준다.

python .\manage.py migrate authtoken
profile
좋은 개발자가 되고싶은

0개의 댓글