Skip to content

Commit

Permalink
Merge pull request #10 from Likelion-at-SMWU-10th/feat/#9-jwt
Browse files Browse the repository at this point in the history
[feat] jwt accesstoken 생성
  • Loading branch information
summit45 authored Jul 27, 2022
2 parents c750491 + 7cea4ba commit 053b882
Show file tree
Hide file tree
Showing 20 changed files with 180 additions and 133 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -305,4 +305,5 @@ cython_debug/
Myvenv/
.DS_Store

myvenv/
myvenv/
.env
39 changes: 0 additions & 39 deletions rememB/balanceapp/migrations/0001_initial.py

This file was deleted.

Empty file.
2 changes: 1 addition & 1 deletion rememB/balanceapp/models.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from django.db import models
from mainapp.models import User
from userapp.models import User

# Create your models here.
class Question(models.Model):
Expand Down
28 changes: 0 additions & 28 deletions rememB/letterapp/migrations/0001_initial.py

This file was deleted.

Empty file.
2 changes: 1 addition & 1 deletion rememB/letterapp/models.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from django.db import models

from mainapp.models import User
from userapp.models import User

class Letter(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE) # 유저와 연동
Expand Down
3 changes: 0 additions & 3 deletions rememB/mainapp/admin.py
Original file line number Diff line number Diff line change
@@ -1,4 +1 @@
from django.contrib import admin
from .models import User

admin.site.register(User)
21 changes: 0 additions & 21 deletions rememB/mainapp/migrations/0001_initial.py

This file was deleted.

27 changes: 0 additions & 27 deletions rememB/mainapp/migrations/0002_user_delete_blog.py

This file was deleted.

Empty file.
6 changes: 0 additions & 6 deletions rememB/mainapp/models.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,3 @@
from django.db import models

class User(models.Model):
uuid = models.CharField(max_length=100)
name = models.CharField(max_length=100)
birthyear = models.CharField(max_length=100)
birthday = models.CharField(max_length=100)
email = models.CharField(max_length=100)

3 changes: 2 additions & 1 deletion rememB/rememB/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"""

from pathlib import Path
from decouple import config

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
Expand All @@ -20,7 +21,7 @@
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-xmbee_n!(mzgjc6!po*ut&7a2g7mq%^u0h-yl*ya=f61@de@6-'
SECRET_KEY = config("SECRET_KEY")

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
Expand Down
2 changes: 2 additions & 0 deletions rememB/userapp/admin.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
from django.contrib import admin
from .models import User

admin.site.register(User)
Empty file.
8 changes: 8 additions & 0 deletions rememB/userapp/models.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
from django.db import models

# Create your models here.
class User(models.Model):
email = models.CharField(max_length=100)
provider = models.CharField(max_length=100)
user_name = models.CharField(max_length=100)
birthday = models.DateField()
access_token = models.CharField(max_length=200)
refresh_token = models.CharField(max_length=200)
expire = models.CharField(max_length=100)
12 changes: 12 additions & 0 deletions rememB/userapp/serializers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
from rest_framework import serializers
from .models import User

class UserSerializer(serializers.ModelSerializer): # 유저 추가
class Meta:
model = User
fields = ('id', 'email', 'provider', 'user_name', 'birthday')

class UserFindSerializer(serializers.ModelSerializer): # 유저 추가
class Meta:
model = User
fields = ('email', 'provider')
21 changes: 21 additions & 0 deletions rememB/userapp/tokens.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# 토큰 발급, 복호화하기 위한 함수 관리를 위한 페이지

import jwt
import datetime
from decouple import config

def generate_token(payload, type): # payload 값과 토큰의 종류
if type == "access":
# 2시간
exp = datetime.datetime.utcnow() + datetime.timedelta(hours=2)
elif type == "refresh":
# 2주
exp = datetime.datetime.utcnow() + datetime.timedelta(weeks=2)
else:
raise Exception("Invalid tokenType")

payload['exp'] = exp
payload['iat'] = datetime.datetime.utcnow() # 발급 시간
encoded = jwt.encode(payload, config("JWT_SECRET_KEY"), algorithm="HS256")

return encoded
14 changes: 10 additions & 4 deletions rememB/userapp/urls.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
from django.urls import path
from . import views
from django.urls import path, include
from .views import *
from rest_framework.routers import DefaultRouter

urlpatterns=[
path('login/',views.login, name='login'),
routers = DefaultRouter()
routers.register('auth', AuthViewSet, basename='auth')

urlpatterns = [
path('', include(routers.urls)),
path('signin/', UserList.as_view()),
path('find/', UserFind.as_view()),
]
122 changes: 121 additions & 1 deletion rememB/userapp/views.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,124 @@
from django.shortcuts import render

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.decorators import action
from rest_framework import viewsets

from .serializers import UserFindSerializer, UserSerializer
from .models import User
from .tokens import *

# Create your views here.
class UserList(APIView):
def post(self, request): # 회원 등록하는 경우
serializer = UserSerializer(data = request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

def get(self, request): # 회원 조회하는 경우
users = User.objects.all()
serializer = UserSerializer(users, many=True) # 다수의 쿼리셋 전달 위해서 many = True
return Response(serializer.data)

class UserFind(APIView):
def post(self, request):
serializer = UserFindSerializer(data = request.data)
if serializer.is_valid():
email = request.data['email']
provider = request.data['provider']
try:
user = User.objects.get(
email=email,
provider=provider
)
print(user.id)
# payload에 넣을 값 커스텀 가능
payload_value = user.id
payload = {
"subject": payload_value,
}

access_token = generate_token(payload, "access")

data = {
"results": {
"access_token": access_token
}
}

return Response(data=data, status=status.HTTP_200_OK)

except User.DoesNotExist:
data = {
"results": {
"msg": "유저 정보가 올바르지 않습니다.",
"code": "E4010"
}
}
return Response(data=data, status=status.HTTP_401_UNAUTHORIZED)

except Exception as e:
print(e)
data = {
"results": {
"msg": "정상적인 접근이 아닙니다.",
"code": "E5000"
}
}
return Response(data=data, status=status.HTTP_500_INTERNAL_SERVER_ERROR)



class AuthViewSet(viewsets.GenericViewSet):
@action(methods=['POST'], detail=False)
def signin(self, request):
email = request.data['email']
provider = request.data['provider']
print(email, provider)
try:
user = User.objects.get(
email=email,
provider=provider
)

# payload에 넣을 값 커스텀 가능
payload_value = user.id
payload = {
"subject": payload_value,
}

access_token = generate_token(payload, "access")

data = {
"results": {
"access_token": access_token
}
}

return Response(data=data, status=status.HTTP_200_OK)

except User.DoesNotExist:
data = {
"results": {
"msg": "유저 정보가 올바르지 않습니다.",
"code": "E4010"
}
}
return Response(data=data, status=status.HTTP_401_UNAUTHORIZED)

except Exception as e:
print(e)
data = {
"results": {
"msg": "정상적인 접근이 아닙니다.",
"code": "E5000"
}
}
return Response(data=data, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

def login(request):
return render(request,'userapp/login.html')
return render(request,'userapp/login.html')

0 comments on commit 053b882

Please sign in to comment.