Skip to content

Commit

Permalink
Merge pull request #5 from Team-MailedIt/feature-cookie
Browse files Browse the repository at this point in the history
feat: 토큰 쿠키에 저장 및 응답 형식 수정
  • Loading branch information
kynzun authored Dec 3, 2021
2 parents f4e9139 + ba8483c commit 8626f6a
Show file tree
Hide file tree
Showing 4 changed files with 84 additions and 18 deletions.
14 changes: 9 additions & 5 deletions account/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,20 @@ class Meta:
fields = ("username", "password", "part")

def create(self, validated_data):
password = validated_data.pop("password")
user = User(**validated_data)
user.set_password(password)
user = User(
username=validated_data.get("username"),
part=validated_data.get("part"),
)
user.set_password(validated_data.get("password"))
user.save()
return user


class CandidateSerializer(serializers.ModelSerializer):
class Meta:
model = Candidate
fields = ['id', 'name', 'part']
fields = ["id", "name", "part"]


class VoteSerializer(serializers.ModelSerializer):
vote_user = serializers.SerializerMethodField()
Expand All @@ -35,4 +39,4 @@ def get_vote_candidate(self, obj):

class Meta:
model = Vote
fields = ['id', 'vote_user', 'vote_candidate']
fields = ["id", "vote_user", "vote_candidate"]
5 changes: 3 additions & 2 deletions account/urls.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
from django.urls import path
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView
from .views import RegisterAPIView, CandidateListAPIView, CandidateDetailAPIView, VoteAPIView, TestAPIView
from .views import *

urlpatterns = [
path("signin", TokenObtainPairView.as_view(), name="token_obtain_pair"),
# path("signin", TokenObtainPairView.as_view(), name="token_obtain_pair"),
# 세션 연장하고 싶을 때 refresh token 사용
# path("token/refresh", TokenRefreshView.as_view(), name="token_refresh"),
path("signin", AuthView.as_view()),
path("signup", RegisterAPIView.as_view()),
path("candidate", CandidateListAPIView.as_view()),
path("candidate/<int:pk>", CandidateDetailAPIView.as_view()),
Expand Down
76 changes: 65 additions & 11 deletions account/views.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
from django.http.response import Http404
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status
from django.contrib.auth import get_user_model
from rest_framework import status, permissions
from django.contrib.auth import get_user_model, authenticate
from .models import Candidate, Vote
from .serializers import RegisterSerializer, CandidateSerializer, VoteSerializer
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
Expand All @@ -11,28 +11,70 @@

User = get_user_model()

# Create your views here.
# 회원가입
class RegisterAPIView(APIView):
def post(self, request):
user_serializer = RegisterSerializer(data=request.data)
if user_serializer.is_valid():
user = user_serializer.save()
# access jwt token
token = TokenObtainPairSerializer.get_token(user)
return Response(
refresh_token = str(token)
access_token = str(token.access_token)
res = Response(
{
"user": user_serializer.data,
"message": "Successfully registered user",
"token": {
"refresh": str(token),
"access": str(token.access_token),
"refresh": refresh_token,
"access": access_token,
},
},
status=status.HTTP_201_CREATED,
status=status.HTTP_200_OK,
)
res.set_cookie("access", access_token, httponly=True)
res.set_cookie("refresh", refresh_token, httponly=True)
return res
return Response(user_serializer.errors, status=status.HTTP_400_BAD_REQUEST)


# 로그인
class AuthView(APIView):
# 유저정보 확인
def get(self, request):
pass

# 로그인
def post(self, request):
user = authenticate(
username=request.data.get("username"), password=request.data.get("password")
)
if user is not None:
token = TokenObtainPairSerializer.get_token(user)
refresh_token = str(token)
access_token = str(token.access_token)
res = Response(
{
"user": {
"username": user.username,
"password": user.password,
"part": user.part,
},
"message": "Successfully logged in",
"token": {
"refresh": refresh_token,
"access": access_token,
},
},
status=status.HTTP_200_OK,
)
res.set_cookie("access", access_token, httponly=True)
res.set_cookie("refresh", refresh_token, httponly=True)
return res
else:
return Response(status=status.HTTP_400_BAD_REQUEST)


class CandidateListAPIView(APIView):
def get(self, request, format=None):
candidates = Candidate.objects.all()
Expand All @@ -53,17 +95,16 @@ def get(self, request, pk, format=None):
return Response(serializer.data, status.HTTP_200_OK)



class VoteAPIView(APIView):
permission_classes = (IsAuthenticated,)

def post(self, request, format=None):
try:
user_id = request.data.get('user_id')
candidate_id = request.data.get('candidate_id')
user_id = request.data.get("user_id")
candidate_id = request.data.get("candidate_id")
vote = Vote.objects.create(
vote_user=User.objects.get(pk=user_id),
vote_candidate=Candidate.objects.get(pk=candidate_id)
vote_candidate=Candidate.objects.get(pk=candidate_id),
)
serializer = VoteSerializer(vote)
except Exception:
Expand All @@ -76,3 +117,16 @@ def get(self, request):
return Response(
{"message": "test API successfully responsed"}, status=status.HTTP_200_OK
)


# 로그인했을 때만 가능한 요청
class TestAuthAPIView(APIView):
permission_classes = [
permissions.IsAuthenticated,
]

def get(self, request):
return Response(
{"message": "test Auth API successfully responsed"},
status=status.HTTP_200_OK,
)
7 changes: 7 additions & 0 deletions vote_mailedit/settings/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

import os
import environ
from datetime import timedelta

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
Expand Down Expand Up @@ -66,6 +67,12 @@
),
}

SIMPLE_JWT = {
"ACCESS_TOKEN_LIFETIME": timedelta(days=1),
"REFRESH_TOKEN_LIFETIME": timedelta(days=7),
"AUTH_HEADER_TYPES": ("JWT",),
}

ROOT_URLCONF = "vote_mailedit.urls"

TEMPLATES = [
Expand Down

0 comments on commit 8626f6a

Please sign in to comment.