diff --git a/rememB/balanceapp/admin.py b/rememB/balanceapp/admin.py deleted file mode 100644 index 8c38f3f..0000000 --- a/rememB/balanceapp/admin.py +++ /dev/null @@ -1,3 +0,0 @@ -from django.contrib import admin - -# Register your models here. diff --git a/rememB/balanceapp/apps.py b/rememB/balanceapp/apps.py deleted file mode 100644 index d308fb9..0000000 --- a/rememB/balanceapp/apps.py +++ /dev/null @@ -1,6 +0,0 @@ -from django.apps import AppConfig - - -class BalanceappConfig(AppConfig): - default_auto_field = 'django.db.models.BigAutoField' - name = 'balanceapp' diff --git a/rememB/balanceapp/models.py b/rememB/balanceapp/models.py deleted file mode 100644 index adc73d9..0000000 --- a/rememB/balanceapp/models.py +++ /dev/null @@ -1,15 +0,0 @@ -from django.db import models -from userapp.models import User - -# Create your models here. -class Question(models.Model): - question_content = models.CharField(max_length=200) - -class Answer(models.Model): - answer_content = models.CharField(max_length=200) - -class Balance(models.Model): - user = models.ForeignKey(User, on_delete=models.CASCADE) # 모델과 연동 - question = models.ForeignKey(Question, on_delete=models.CASCADE) - answer = models.ForeignKey(Answer, on_delete=models.CASCADE) - diff --git a/rememB/balanceapp/tests.py b/rememB/balanceapp/tests.py deleted file mode 100644 index 7ce503c..0000000 --- a/rememB/balanceapp/tests.py +++ /dev/null @@ -1,3 +0,0 @@ -from django.test import TestCase - -# Create your tests here. diff --git a/rememB/balanceapp/urls.py b/rememB/balanceapp/urls.py deleted file mode 100644 index 6147f3a..0000000 --- a/rememB/balanceapp/urls.py +++ /dev/null @@ -1,6 +0,0 @@ -from django.urls import path -from . import views - -urlpatterns=[ - -] diff --git a/rememB/balanceapp/views.py b/rememB/balanceapp/views.py deleted file mode 100644 index 91ea44a..0000000 --- a/rememB/balanceapp/views.py +++ /dev/null @@ -1,3 +0,0 @@ -from django.shortcuts import render - -# Create your views here. diff --git a/rememB/letterapp/admin.py b/rememB/letterapp/admin.py index 8c38f3f..d11d956 100644 --- a/rememB/letterapp/admin.py +++ b/rememB/letterapp/admin.py @@ -1,3 +1,4 @@ from django.contrib import admin +from .models import Letter -# Register your models here. +admin.site.register(Letter) \ No newline at end of file diff --git a/rememB/letterapp/migrations/0001_initial.py b/rememB/letterapp/migrations/0001_initial.py new file mode 100644 index 0000000..3dbfbdb --- /dev/null +++ b/rememB/letterapp/migrations/0001_initial.py @@ -0,0 +1,25 @@ +# Generated by Django 4.1 on 2022-08-11 00:57 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='Letter', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('content', models.TextField()), + ('imgfolder_no', models.IntegerField()), + ('img_no', models.IntegerField()), + ('position_x', models.IntegerField()), + ('position_y', models.IntegerField()), + ], + ), + ] diff --git a/rememB/letterapp/migrations/0002_letter_created_at.py b/rememB/letterapp/migrations/0002_letter_created_at.py new file mode 100644 index 0000000..6419dc9 --- /dev/null +++ b/rememB/letterapp/migrations/0002_letter_created_at.py @@ -0,0 +1,18 @@ +# Generated by Django 4.1 on 2022-08-11 01:54 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('letterapp', '0001_initial'), + ] + + operations = [ + migrations.AddField( + model_name='letter', + name='created_at', + field=models.DateTimeField(auto_now=True), + ), + ] diff --git a/rememB/letterapp/migrations/0003_alter_letter_imgfolder_no.py b/rememB/letterapp/migrations/0003_alter_letter_imgfolder_no.py new file mode 100644 index 0000000..a590f25 --- /dev/null +++ b/rememB/letterapp/migrations/0003_alter_letter_imgfolder_no.py @@ -0,0 +1,18 @@ +# Generated by Django 4.1 on 2022-08-11 01:56 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('letterapp', '0002_letter_created_at'), + ] + + operations = [ + migrations.AlterField( + model_name='letter', + name='imgfolder_no', + field=models.IntegerField(null=True), + ), + ] diff --git a/rememB/letterapp/migrations/0004_alter_letter_img_no_alter_letter_position_x_and_more.py b/rememB/letterapp/migrations/0004_alter_letter_img_no_alter_letter_position_x_and_more.py new file mode 100644 index 0000000..fbe6cbf --- /dev/null +++ b/rememB/letterapp/migrations/0004_alter_letter_img_no_alter_letter_position_x_and_more.py @@ -0,0 +1,28 @@ +# Generated by Django 4.1 on 2022-08-11 01:56 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('letterapp', '0003_alter_letter_imgfolder_no'), + ] + + operations = [ + migrations.AlterField( + model_name='letter', + name='img_no', + field=models.IntegerField(null=True), + ), + migrations.AlterField( + model_name='letter', + name='position_x', + field=models.IntegerField(null=True), + ), + migrations.AlterField( + model_name='letter', + name='position_y', + field=models.IntegerField(null=True), + ), + ] diff --git a/rememB/letterapp/migrations/0005_letter_user_alter_letter_id.py b/rememB/letterapp/migrations/0005_letter_user_alter_letter_id.py new file mode 100644 index 0000000..afb3ac4 --- /dev/null +++ b/rememB/letterapp/migrations/0005_letter_user_alter_letter_id.py @@ -0,0 +1,25 @@ +# Generated by Django 4.1 on 2022-08-11 02:53 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ('userapp', '0004_alter_user_refreshtoken'), + ('letterapp', '0004_alter_letter_img_no_alter_letter_position_x_and_more'), + ] + + operations = [ + migrations.AddField( + model_name='letter', + name='user', + field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='userapp.user'), + ), + migrations.AlterField( + model_name='letter', + name='id', + field=models.AutoField(primary_key=True, serialize=False), + ), + ] diff --git a/rememB/balanceapp/__init__.py b/rememB/letterapp/migrations/__init__.py similarity index 100% rename from rememB/balanceapp/__init__.py rename to rememB/letterapp/migrations/__init__.py diff --git a/rememB/letterapp/models.py b/rememB/letterapp/models.py index 7037200..0001286 100644 --- a/rememB/letterapp/models.py +++ b/rememB/letterapp/models.py @@ -1,13 +1,16 @@ from django.db import models - from userapp.models import User class Letter(models.Model): - user = models.ForeignKey(User, on_delete=models.CASCADE) # 유저와 연동 - letter_content = models.CharField(max_length=300) - img_no = models.IntegerField() + id = models.AutoField(primary_key=True, null=False, blank=False) + user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) + content = models.TextField() + imgfolder_no=models.IntegerField(null=True) + img_no = models.IntegerField(null=True) created_at = models.DateTimeField(auto_now=True) - position_x = models.IntegerField() - position_y = models.IntegerField() - + position_x = models.IntegerField(null=True) + position_y = models.IntegerField(null=True) + def __str__(self): + return self.content[:7] + diff --git a/rememB/letterapp/serializers.py b/rememB/letterapp/serializers.py index e69de29..c74945f 100644 --- a/rememB/letterapp/serializers.py +++ b/rememB/letterapp/serializers.py @@ -0,0 +1,19 @@ +from rest_framework import serializers +from .models import * + +class LetterSerializer(serializers.ModelSerializer): + #user=serializers.ReadOnlyField(source='user.uuid') + class Meta: + model=Letter + fields=('id','user','content','imgfolder_no','img_no','position_x','position_y','created_at') + + +class LetterDetailSerializer(serializers.ModelSerializer): + class Meta: + model=Letter + fields=('id','user','get_img','content') + +class LetterSumSerializer(serializers.ModelSerializer): + class Meta: + model=Letter + fields=['id','user','content','created_at'] \ No newline at end of file diff --git a/rememB/letterapp/urls.py b/rememB/letterapp/urls.py index 6147f3a..4a85391 100644 --- a/rememB/letterapp/urls.py +++ b/rememB/letterapp/urls.py @@ -2,5 +2,8 @@ from . import views urlpatterns=[ - + path('admin/',views.LetterList.as_view()), #전체 편지 조회 + path('/send/',views.LetterSend.as_view()), #userpk에게 편지 작성 + path('/',views.LetterDetail.as_view()), #letterpk의 편지 디테일 + path('/list/',views.LetterUserList.as_view()), #userpk의 편지만 조회 ] diff --git a/rememB/letterapp/views.py b/rememB/letterapp/views.py index 91ea44a..046ccd7 100644 --- a/rememB/letterapp/views.py +++ b/rememB/letterapp/views.py @@ -1,3 +1,61 @@ -from django.shortcuts import render +from .serializers import * +from .models import Letter, User +from rest_framework import viewsets +from rest_framework.views import APIView +from rest_framework.response import Response +from rest_framework import status +from django.http import Http404 +from django.shortcuts import get_object_or_404 -# Create your views here. + +class LetterSend(APIView): + #userpk에게 편지 작성 + def post(self, request, userpk): + user=get_object_or_404(User,pk=userpk) + serializer=LetterSerializer(data=request.data) + if serializer.is_valid(): + serializer.save(user=user) + return Response(serializer.data, status=status.HTTP_201_CREATED) + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) + +class LetterList(APIView): + #전체 편지 조회 + def get(self, request): + letters=Letter.objects.all() + serializer=LetterSerializer(letters, many=True) + return Response(serializer.data) + +class LetterUserList(APIView): + #userpk의 편지만 조회 + def get(self,request,userpk): + user_letters=Letter.objects.filter(user=userpk) + serializer=LetterSerializer(user_letters, many=True) + return Response(serializer.data) + + +class LetterDetail(APIView): + def get_object(self, letterpk): + try: + return Letter.objects.get(pk=letterpk) + except Letter.DoesNotExist: + raise Http404 + + def get(self, request, letterpk): + letter=self.get_object(letterpk) + serializer=LetterSerializer(letter) + return Response(serializer.data) + + #기능 구현 필요없음 + def put(self, request, letterpk): + letter=self.get_object(letterpk) + serializer=LetterSerializer(letter,data=request.data) + if serializer.is_valid(): + serializer.save() + return Response(serializer.data, status=status.HTTP_200_OK) + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) + + #기능 구현 필요없음 + def delete(self, request, letterpk): + letter=self.get_object(letterpk) + letter.delete() + return Response(status=status.HTTP_204_NO_CONTENT) diff --git a/rememB/mainapp/admin.py b/rememB/mainapp/admin.py deleted file mode 100644 index 694323f..0000000 --- a/rememB/mainapp/admin.py +++ /dev/null @@ -1 +0,0 @@ -from django.contrib import admin diff --git a/rememB/mainapp/apps.py b/rememB/mainapp/apps.py deleted file mode 100644 index 8aa89a8..0000000 --- a/rememB/mainapp/apps.py +++ /dev/null @@ -1,6 +0,0 @@ -from django.apps import AppConfig - - -class MainappConfig(AppConfig): - default_auto_field = 'django.db.models.BigAutoField' - name = 'mainapp' diff --git a/rememB/mainapp/models.py b/rememB/mainapp/models.py deleted file mode 100644 index 4167352..0000000 --- a/rememB/mainapp/models.py +++ /dev/null @@ -1,3 +0,0 @@ -from django.db import models - - diff --git a/rememB/mainapp/tests.py b/rememB/mainapp/tests.py deleted file mode 100644 index 7ce503c..0000000 --- a/rememB/mainapp/tests.py +++ /dev/null @@ -1,3 +0,0 @@ -from django.test import TestCase - -# Create your tests here. diff --git a/rememB/mainapp/urls.py b/rememB/mainapp/urls.py deleted file mode 100644 index 52a7106..0000000 --- a/rememB/mainapp/urls.py +++ /dev/null @@ -1,6 +0,0 @@ -from django.urls import path -from . import views - -urlpatterns=[ - -] \ No newline at end of file diff --git a/rememB/mainapp/views.py b/rememB/mainapp/views.py deleted file mode 100644 index 2536b37..0000000 --- a/rememB/mainapp/views.py +++ /dev/null @@ -1 +0,0 @@ -from django.shortcuts import render diff --git a/rememB/rememB/settings.py b/rememB/rememB/settings.py index 0e2e2b7..8852ffb 100644 --- a/rememB/rememB/settings.py +++ b/rememB/rememB/settings.py @@ -10,8 +10,11 @@ https://docs.djangoproject.com/en/4.0/ref/settings/ """ +from operator import truediv from pathlib import Path +from pickle import TRUE from decouple import config +import datetime # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent @@ -26,8 +29,10 @@ # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True -ALLOWED_HOSTS = [] - +ALLOWED_HOSTS = [ + '1.0.0.127.in-addr.arpa', + '127.0.0.1' +] # Application definition @@ -38,25 +43,37 @@ 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', - 'mainapp', + #'mainapp', 'letterapp', - 'balanceapp', + #'balanceapp', 'userapp', - - #allauth - 'allauth', - 'allauth.account', - 'allauth.socialaccount', - - #provider - 'allauth.socialaccount.providers.google', - 'allauth.socialaccount.providers.naver', - 'allauth.socialaccount.providers.kakao', #restframework 'rest_framework', + 'rest_framework_simplejwt', ] +REST_FRAMEWORK = { + # 헤더에 access token을 포함하여 유효한 유저만이 접근이 가능하는 것을 Default로 설정 + # 'DEFAULT_PERMISSION_CLASSES': ( + # 'rest_framework.permissions.IsAuthenticated', + # ), + # 권한 설정 + 'DEFAULT_AUTHENTICATION_CLASSES': [ + 'rest_framework_simplejwt.authentication.JWTAuthentication', + ] +} + +REST_USE_JWT=TRUE + +SIMPLE_JWT={ + 'ACCESS_TOKEN_LIFETIME':datetime.timedelta(minutes=2), + 'REFRESH_TOKEN_LIFETIME':datetime.timedelta(days=1), + 'ROTATE_REFRESH_TOKENS':False, + 'TOKEN_USER_CLASS':'userapp.User', + #'USER_ID_FIELD':'email', +} + MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', @@ -137,15 +154,3 @@ # Default primary key field type # https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field - -DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' - -AUTHENTICATION_BACKENDS=( - 'django.contrib.auth.backends.ModelBackend', - 'allauth.account.auth_backends.AuthenticationBackend' -) - -SITE_ID = 1 -LOGIN_REDIRECT_URL = '/' #로그인 후 리디렉션할 페이지 -ACCOUNT_LOGOUT_REDIRECT_URL ='/' #로그아웃 후 리디렉션 할 페이지 -ACCOUNT_LOGOUT_ON_GET = True #로그아웃 버튼 클릭 시 자동 로그아웃 diff --git a/rememB/rememB/urls.py b/rememB/rememB/urls.py index 41eaf47..0934f24 100644 --- a/rememB/rememB/urls.py +++ b/rememB/rememB/urls.py @@ -1,11 +1,11 @@ from django.contrib import admin from django.urls import path, include + urlpatterns = [ path('admin/', admin.site.urls), - path('balanceapp/',include('balanceapp.urls')), - path('letterapp/',include('letterapp.urls')), - path('mainapp/',include('mainapp.urls')), - path('accounts/',include('allauth.urls')), + #path('balance/',include('balanceapp.urls')), + path('letter/',include('letterapp.urls')), + #path('main/',include('mainapp.urls')), path('user/',include('userapp.urls')), ] diff --git a/rememB/userapp/admin.py b/rememB/userapp/admin.py index 764e605..0ec9e97 100644 --- a/rememB/userapp/admin.py +++ b/rememB/userapp/admin.py @@ -1,4 +1,5 @@ from django.contrib import admin from .models import User +# Register your models here. admin.site.register(User) \ No newline at end of file diff --git a/rememB/userapp/migrations/0001_initial.py b/rememB/userapp/migrations/0001_initial.py new file mode 100644 index 0000000..ad7c96b --- /dev/null +++ b/rememB/userapp/migrations/0001_initial.py @@ -0,0 +1,27 @@ +# Generated by Django 4.1 on 2022-08-11 00:57 + +from django.db import migrations, models +import uuid + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='User', + fields=[ + ('id', models.AutoField(primary_key=True, serialize=False)), + ('uuid', models.UUIDField(db_index=True, default=uuid.uuid4, unique=True)), + ('email', models.EmailField(max_length=64, unique=True, verbose_name='email')), + ('username', models.CharField(max_length=30)), + ('provider', models.CharField(max_length=20)), + ('birth', models.DateField(blank=True)), + ('refreshToken', models.CharField(default='', max_length=200, null=True)), + ], + ), + ] diff --git a/rememB/userapp/migrations/0002_remove_user_uuid.py b/rememB/userapp/migrations/0002_remove_user_uuid.py new file mode 100644 index 0000000..7fa20e8 --- /dev/null +++ b/rememB/userapp/migrations/0002_remove_user_uuid.py @@ -0,0 +1,17 @@ +# Generated by Django 4.1 on 2022-08-11 01:54 + +from django.db import migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('userapp', '0001_initial'), + ] + + operations = [ + migrations.RemoveField( + model_name='user', + name='uuid', + ), + ] diff --git a/rememB/userapp/migrations/0003_user_is_active_user_is_admin.py b/rememB/userapp/migrations/0003_user_is_active_user_is_admin.py new file mode 100644 index 0000000..8c08eb5 --- /dev/null +++ b/rememB/userapp/migrations/0003_user_is_active_user_is_admin.py @@ -0,0 +1,23 @@ +# Generated by Django 4.1 on 2022-08-11 02:37 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('userapp', '0002_remove_user_uuid'), + ] + + operations = [ + migrations.AddField( + model_name='user', + name='is_active', + field=models.BooleanField(default=True), + ), + migrations.AddField( + model_name='user', + name='is_admin', + field=models.BooleanField(default=False), + ), + ] diff --git a/rememB/userapp/migrations/0004_alter_user_refreshtoken.py b/rememB/userapp/migrations/0004_alter_user_refreshtoken.py new file mode 100644 index 0000000..09e1520 --- /dev/null +++ b/rememB/userapp/migrations/0004_alter_user_refreshtoken.py @@ -0,0 +1,18 @@ +# Generated by Django 4.1 on 2022-08-11 02:53 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('userapp', '0003_user_is_active_user_is_admin'), + ] + + operations = [ + migrations.AlterField( + model_name='user', + name='refreshToken', + field=models.CharField(default='', max_length=2000, null=True), + ), + ] diff --git a/rememB/mainapp/__init__.py b/rememB/userapp/migrations/__init__.py similarity index 100% rename from rememB/mainapp/__init__.py rename to rememB/userapp/migrations/__init__.py diff --git a/rememB/userapp/models.py b/rememB/userapp/models.py index 6e2a83e..89f2928 100644 --- a/rememB/userapp/models.py +++ b/rememB/userapp/models.py @@ -1,11 +1,30 @@ +from os import access from django.db import models +import uuid + -# 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) + id = models.AutoField(primary_key=True,) + email=models.EmailField(verbose_name=('email'), max_length=64, unique=True, null=False, blank=False,) + username=models.CharField(max_length=30, null=False, blank=False,) + provider=models.CharField(max_length=20, null=False, blank=False,) + birth=models.DateField(blank=True,) + refreshToken=models.CharField(max_length=2000, null=True, default='',) + + # User 모델의 필수 field + is_active = models.BooleanField(default=True) + is_admin = models.BooleanField(default=False) + + def __str__(self): + return str(self.email) + + def get_id(self): + return str(self.id) + + def validate(self,data): + search_email=data.get('email',None) + + if User.objects.filter(email=search_email).exists(): + print('이미 있는 아이디입니다.') + + return data diff --git a/rememB/userapp/serializers.py b/rememB/userapp/serializers.py index 92901dd..6839f88 100644 --- a/rememB/userapp/serializers.py +++ b/rememB/userapp/serializers.py @@ -1,12 +1,18 @@ from rest_framework import serializers from .models import User -class UserSerializer(serializers.ModelSerializer): # 유저 추가 +class UserSerializer(serializers.ModelSerializer): class Meta: - model = User - fields = ('id', 'email', 'provider', 'user_name', 'birthday') + model=User + fields='__all__' + + +class JWTSigninSerializer(serializers.ModelSerializer): + email=serializers.EmailField() + username=serializers.CharField() + provider=serializers.CharField(max_length=20) + birth=serializers.DateField() -class UserFindSerializer(serializers.ModelSerializer): # 유저 추가 class Meta: - model = User - fields = ('email', 'provider') + model=User + fields='__all__' diff --git a/rememB/userapp/templates/userapp/login.html b/rememB/userapp/templates/userapp/login.html deleted file mode 100644 index c632825..0000000 --- a/rememB/userapp/templates/userapp/login.html +++ /dev/null @@ -1,19 +0,0 @@ -{% load socialaccount %} -{% providers_media_js %} - - -
- -{% if user.is_authenticated %} - 로그아웃 -
- {{ user.username }}님이 환영합니다! -{% else %} - - 구글 로그인 -
- 네이버 로그인 -
- 카카오 로그인 - -{% endif %} \ No newline at end of file diff --git a/rememB/userapp/tokens.py b/rememB/userapp/tokens.py deleted file mode 100644 index 7aed3ce..0000000 --- a/rememB/userapp/tokens.py +++ /dev/null @@ -1,21 +0,0 @@ -# 토큰 발급, 복호화하기 위한 함수 관리를 위한 페이지 - -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 \ No newline at end of file diff --git a/rememB/userapp/urls.py b/rememB/userapp/urls.py index 0c45842..002061a 100644 --- a/rememB/userapp/urls.py +++ b/rememB/userapp/urls.py @@ -1,12 +1,14 @@ -from django.urls import path, include -from .views import * -from rest_framework.routers import DefaultRouter +from django.urls import path,include +from . import views +from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView, TokenVerifyView -routers = DefaultRouter() -routers.register('auth', AuthViewSet, basename='auth') urlpatterns = [ - path('', include(routers.urls)), - path('signin/', UserList.as_view()), - path('find/', UserFind.as_view()), -] \ No newline at end of file + path('admin/',views.user_list.as_view()), #유저 계정 전체 조회 + path('mypage//',views.user_detail.as_view()), #pk 계정 상세조회, 수정, 삭제 + path('signin/',views.JWTSigninView.as_view()), #jwt 로그인 + path('auth/',views.AuthUserView.as_view()), + + #jwt token + path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), #post: access_token 재발급 +] diff --git a/rememB/userapp/views.py b/rememB/userapp/views.py index a8cb3a2..dd0c4de 100644 --- a/rememB/userapp/views.py +++ b/rememB/userapp/views.py @@ -1,124 +1,97 @@ -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 django.http import HttpResponse, JsonResponse +from django.views.decorators.csrf import csrf_exempt from .models import User -from .tokens import * - -# Create your views here. -class UserList(APIView): - def post(self, request): # 회원 등록하는 경우 - serializer = UserSerializer(data = request.data) +from .serializers import JWTSigninSerializer, UserSerializer +from rest_framework.parsers import JSONParser +from rest_framework.views import APIView +from .serializers import * +from rest_framework.response import Response +from rest_framework import generics, status +from rest_framework.views import APIView +from rest_framework.response import Response +from rest_framework.permissions import IsAuthenticated +from rest_framework_simplejwt.authentication import JWTAuthentication +from rest_framework_simplejwt.tokens import RefreshToken + +class user_list(APIView): + def get(self, request): + #get: 계정 전체 조회 + users=User.objects.all() + serializers=UserSerializer(users,many=True) + return Response(serializers.data) + + +class user_detail(APIView): + def get(self,request, pk): + obj=User.objects.get(id=pk) + serializers=UserSerializer(obj) + return Response(serializers.data) + + def put(self, request, pk): + #put: pk의 계정 정보 수정 + obj=User.objects.get(id=pk) + serializer=UserSerializer(obj, data=request.data) if serializer.is_valid(): serializer.save() - return Response(serializer.data, status=status.HTTP_201_CREATED) + return Response(serializer.data, status=status.HTTP_200_OK) 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, - } + def delete(self, request, pk): + #delete: pk의 계정 정보 삭제 + obj=self.get_object(pk) + obj.delete() + return Response(status=status.HTTP_204_NO_CONTENT) - access_token = generate_token(payload, "access") - data = { - "results": { - "access_token": access_token - } - } +class JWTSigninView(generics.CreateAPIView): + serializer_class=JWTSigninSerializer - 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 = { + def post(self,request): + try: + user = User.objects.get_or_create( + email=request.data['email'], + provider=request.data['provider'], + birth=request.data['birth'], + username=request.data['username'] + ) + except: + data = { "results": { - "msg": "정상적인 접근이 아닙니다.", - "code": "E5000" + "msg": "social provider error", + "code": "E500" } } - return Response(data=data, status=status.HTTP_500_INTERNAL_SERVER_ERROR) - + return Response(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: + serializer=self.get_serializer(data=request.data) + if serializer.is_valid(): user = User.objects.get( - email=email, - provider=provider + email=request.data['email'], + provider=request.data['provider'], ) - - # payload에 넣을 값 커스텀 가능 - payload_value = user.id - payload = { - "subject": payload_value, - } - - access_token = generate_token(payload, "access") - - data = { + token = RefreshToken.for_user(user) + user.refreshToken = str(token) + user.save() + data = { "results": { - "access_token": access_token + "id" : user.id, + "refreshToken" : user.refreshToken, + "accessToken" : str(token.access_token), } } + return Response(data, status=status.HTTP_200_OK) - 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 AuthUserView(APIView): + #커스텀한 user모델에 권한 설정을 안해서 그런 것 같다 + #첫번째 계정을 admin계정으로 인식 -> 토큰 인식 됨 + #permission_classes=[IsAuthenticated] + authentication_classes=[JWTAuthentication] -def login(request): - return render(request,'userapp/login.html') \ No newline at end of file + def get(self, request): + user=request.user.username + print(f"user정보: {user}") #첫번째 계정으로 로그인했을 때: admin으로 출력 / username 삭제: AnonymousUser으로 출력 + if not user: + return Response({"error": "접근 권한이 없습니다."}, status=status.HTTP_401_UNAUTHORIZED) + return Response({"message": "Accepted"})