Chapter 03

Django ログイン 新規登録 機能 作成

hello_yogurt
hello_yogurt
2022.07.23に更新

ログイン機能作成

DjangoとVue.jsで作るWEBアプリ(その2: 認証機能編)

https://nmomos.com/tips/2019/07/18/django-vuejs-2/amp/
settings.py
INSTALLED_APPS = [
'rest_framework.authtoken', # 追加
]

REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASS':'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly',
'rest_framework.pagination.PageNumberPagination',
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
    ),
}

JWT_AUTH = {
    'JWT_VERIFY': True,
    'JWT_VERIFY_EXPIRATION': True,
    'JWT_LEEWAY': 0,
    'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=86400),
    'JWT_ALLOW_REFRESH': True,
    'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7),
}

CORS_ALLOW_ALL_ORIGINS = True

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]


python manage.py migrate

myproject/urls.py
from django.contrib import admin
from django.urls import path, include # 追加

urlpatterns = [
    path('admin/', admin.site.urls),
    path("", include("myapp.urls")) # 追加
]

myapp/urls.py
from django.urls import path, include
from rest_framework_jwt.views import obtain_jwt_token

urlpatterns = [
    path('auth/', obtain_jwt_token),
]


python manage.py runserver

画面確認

http://localhost:8000/auth/


ユーザー名(superuser)とパスワードを入力してPOSTするとTokenが生成される


新規登録作成

myapp/views.py
from django.http import JsonResponse, HttpResponse
from django.views import View
from rest_framework import generics, viewsets
from django.contrib.auth.models import User
from myapp.serializers import UserSerializer
import json
import requests
import sys
import os
import re
import time
import datetime
import pytz
import shutil

class CreateUser(View):
    def get(self, request):

        return HttpResponse('result')

    def post(self, request):

        post = json.loads(request.body.decode("utf-8", "ignore"))

        print("post出力", post)

        username = post["username"]
        email    = None
        password = post["password"]

        User.objects.create_user(username,email,password)

        return HttpResponse('result')
	
class UserListAPIView(generics.ListAPIView):
    queryset = User.objects.all().order_by("-id")
    serializer_class = UserSerializer

class UserDetailAPIview(generics.ListAPIView):
    serializer_class = UserSerializer

    def get_queryset(self):
        username = self.kwargs['username']
        return User.objects.filter(username=username).order_by("-id")


myapp/serializers.py作成

myapp/serializers.py
from rest_framework import serializers
from django.contrib.auth.models import User

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = "__all__"

myapp/urls.py
from django.urls import path, include
from myapp.views import (UserListAPIView, UserDetailAPIview, CreateUser)
from rest_framework_jwt.views import obtain_jwt_token
from . import views

urlpatterns = [
    path("users/", UserListAPIView.as_view(), name="user-list"),
    path('users/<str:username>/', UserDetailAPIview.as_view(), name="user-detail"),
    path('create_user/', CreateUser.as_view(), name='create_user'),
    path('auth/', obtain_jwt_token),
]

csrf_tokenをindex.htmlに発行して、cookieに入れとく

backend/myapp/views.py
from django.views.decorators.csrf import ensure_csrf_cookie, csrf_exempt

@ensure_csrf_cookie
def token_get(request):

    if request.method == 'GET':
        return JsonResponse({})

backend/myapp/urls.py
urlpatterns = [
    path("", views.token_get, name="token_get"),