김대연

모델 업데이트 및 리팩토링

from django.contrib import admin
# Register your models here.
from django.apps import AppConfig
class GroupConfig(AppConfig):
name = 'group'
# Generated by Django 3.0.7 on 2020-06-09 17:57
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='UserGroup',
fields=[
('group_name', models.CharField(max_length=20, primary_key=True, serialize=False, unique=True)),
('owner_email', models.EmailField(max_length=254)),
('group_users', models.ManyToManyField(to=settings.AUTH_USER_MODEL, verbose_name='Group User')),
],
),
]
from django.db import models
from user.models import User
class UserGroup(models.Model):
#group_id = models.AutoField(primary_key = True, blank = True)
group_name = models.CharField(primary_key = True, unique = True, max_length=20)
owner_email = models.EmailField(max_length=254)
#owner = models.ForeignKey(User, verbose_name="Group Owner", on_delete=models.CASCADE)
group_users = models.ManyToManyField(User, verbose_name="Group User")
def user_to_group(self, user):
self.group_users.add(user)
#UserGroup.save(using=self._db)
#return group
# Create your models here.
from rest_framework import serializers
from .models import UserGroup
class CreateUserGroupSerializer(serializers.Serializer):
group_name = serializers.CharField(allow_blank=False, max_length = 100)
class AddUserSerializer(serializers.Serializer):
group_name = serializers.CharField(allow_blank=False, max_length = 100)
user_id = serializers.IntegerField()
class UserGroupSerializer(serializers.ModelSerializer):
class Meta:
model = UserGroup
fields = ("group_name","owner_email","group_users")
from django.test import TestCase
# Create your tests here.
from django.conf.urls import url, include
from .views import (
CreateGroupAPI,
GroupListAPI,
AddUserAPI
)
urlpatterns =[
url("^creategroup/$", CreateGroupAPI.as_view()),
url("^grouplist/$", GroupListAPI.as_view()),
url("^adduser/$", AddUserAPI.as_view()),
]
from rest_framework import viewsets, permissions, generics, mixins, status
from rest_framework.response import Response
from knox.models import AuthToken
from .models import UserGroup
from user.models import User
from .serializers import (UserGroupSerializer, CreateUserGroupSerializer, AddUserSerializer)
from user.serializers import UserSerializer
class CreateGroupAPI(generics.GenericAPIView):
serializer_class = CreateUserGroupSerializer
permission_classes = [permissions.IsAuthenticated]
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
input_name = request.data["group_name"]
input_owner = UserSerializer(self.request.user).data
group, created = UserGroup.objects.get_or_create(group_name = input_name, owner_email = input_owner["email"])
if created:
group.save()
group.user_to_group(request.user)
group.save()
else:
body = {"message": "already exist"}
return Response(body, status=status.HTTP_400_BAD_REQUEST)
return Response(UserGroupSerializer(group).data)
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
class AddUserAPI(generics.GenericAPIView):
serializer_class = AddUserSerializer
permission_classes = [permissions.IsAuthenticated]
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
input_name = request.data["group_name"]
input_user = request.data["user_id"]
input_owner = UserSerializer(self.request.user).data
group, created = UserGroup.objects.get_or_create(group_name = input_name)
if(input_owner["email"]!=UserGroupSerializer(group).data["owner_email"]):
body = {"message": "not group owner"}
return Response(body, status=status.HTTP_401_UNAUTHORIZED)
if created:
body = {"message": "group doesn't exist"}
return Response(body, status=status.HTTP_400_BAD_REQUEST)
else:
try :
user= User.objects.get(id = input_user)
except User.DoesNotExist:
body = {"message": "user doesn't exist"}
return Response(body, status=status.HTTP_400_BAD_REQUEST)
group.user_to_group(user)
group.save()
return Response(UserGroupSerializer(group).data)
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
class GroupListAPI(generics.ListAPIView):
queryset = UserGroup.objects.all()
serializer_class = UserGroupSerializer
#class GroupListAPI(generics.GenericAPIView):
\ No newline at end of file
# -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2020-06-13 17:18
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('khubox', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='user',
name='password',
field=models.CharField(max_length=77),
),
]
......@@ -33,7 +33,7 @@ class GroupUser(models.Model):
class User(models.Model):
email = models.CharField(max_length=255)
password = models.CharField(max_length=60)
password = models.CharField(max_length=77)
name = models.CharField(max_length=50)
root_folder = models.CharField(max_length=36)
created_at = models.DateTimeField()
......
......@@ -37,6 +37,3 @@ Werkzeug==0.16.1
wsgi-request-logger==0.4.6
zappa==0.51.0
zipp==3.1.0
djangorestframework == 3.11.0
django-rest-knox == 1.1.0
......
from django.contrib import admin
# Register your models here.
from django.apps import AppConfig
class UserConfig(AppConfig):
name = 'user'
# Generated by Django 3.0.7 on 2020-06-09 17:57
import datetime
from django.db import migrations, models
import user.models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='User',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('email', models.EmailField(max_length=254, unique=True)),
('name', models.CharField(max_length=100)),
('date_of_birth', models.DateField(default=datetime.date.today)),
('storage_usage', models.FloatField(default=0)),
('profile', models.ImageField(upload_to=None)),
('is_admin', models.BooleanField(default=False)),
],
options={
'abstract': False,
},
managers=[
('objects', user.models.UserManager()),
],
),
]
from django.db import models
from django.contrib.auth.models import AbstractBaseUser,BaseUserManager
import datetime
class UserManager(BaseUserManager):
use_in_migrations = True
def create_user(self, email, name, date_of_birth, password=None):
user = self.model(
email=self.normalize_email(email),
date_of_birth=date_of_birth,
name=name,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_staffuser(self, email, name, date_of_birth, password):
user = self.create_user(
email,
password=password,
date_of_birth=date_of_birth,
name=name,
)
user.staff = True
user.save(using=self._db)
return user
def create_superuser(self, email, name, date_of_birth, password):
user = self.create_user(
email,
password=password,
date_of_birth=date_of_birth,
name= "True",
)
#user.is_staff = True
user.is_admin = True
user.save(using=self._db)
return user
class User(AbstractBaseUser):
username = None
email = models.EmailField( unique=True)
name = models.CharField(max_length=100)
date_of_birth = models.DateField(default=datetime.date.today)
storage_usage = models.FloatField( default = 0)
profile = models.ImageField(upload_to=None, height_field=None, width_field=None, max_length=None)
is_admin = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = [ 'date_of_birth','name' ]
objects = UserManager()
def __str__(self):
return self.email
@property
def is_staff(self):
return self.is_admin
def has_perm(self, perm, obj = None):
return True
def has_module_perms(self, app_label):
return True
from rest_framework import serializers
from .models import User
from django.contrib.auth import authenticate
# 회원가입 시리얼라이저
class CreateUserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ("email", "name", "date_of_birth", "password")
extra_kwargs = {"password": {"write_only": True}}
def create(self, validated_data):
user = User.objects.create_user(
validated_data["email"],
validated_data["name"],
validated_data["date_of_birth"],
validated_data["password"]
)
return user
# 접속 유지중인지 확인할 시리얼라이저
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ("id","email", "name","date_of_birth","storage_usage","usergroup_set")
# 로그인 시리얼라이저
class LoginUserSerializer(serializers.Serializer):
email = serializers.EmailField()
password = serializers.CharField()
def validate(self, data):
user = authenticate(**data)
if user and user.is_active:
return user
raise serializers.ValidationError("Unable to log in with provided credentials.")
class UpdateUserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ("email", "name", "date_of_birth","storage_usage", "password")
extra_kwargs = {"password": {"write_only": True}}
read_only_fields = ('email',"storage_usage")
def update(self, instance, validated_data):
password = validated_data.pop('password', None)
for (key, value) in validated_data.items():
setattr(instance, key, value)
if password is not None:
instance.set_password(password)
instance.save()
return instance
from django.test import TestCase
# Create your tests here.
from django.conf.urls import url, include
from .views import (RegistrationAPI,
LoginAPI,
UserAPI,
RegistrationAPI,
UserListAPI,
UserUpdateAPI,
)
urlpatterns =[
url("^register/$", RegistrationAPI.as_view()),
url("^login/$", LoginAPI.as_view()),
url("^user/$", UserAPI.as_view()),
url("^update/$", UserUpdateAPI.as_view()),
url("^userlist/$", UserListAPI.as_view()),
url("",include("knox.urls")),
]
from rest_framework import viewsets, permissions, generics, mixins, status
from rest_framework.response import Response
from .models import User
from .serializers import (
CreateUserSerializer,
UserSerializer,
LoginUserSerializer,
UpdateUserSerializer,
)
from knox.models import AuthToken
class RegistrationAPI(generics.GenericAPIView):
serializer_class = CreateUserSerializer
def post(self, request, *args, **kwargs):
if len(request.data["email"]) < 6 or len(request.data["password"]) < 4:
body = {"message": "short field"}
return Response(body, status=status.HTTP_400_BAD_REQUEST)
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
#return Response(serializer.name)
user = serializer.save()
return Response(
{
"user": UserSerializer(
user, context=self.get_serializer_context()
).data,
"token": AuthToken.objects.create(user)[1],
}
)
class LoginAPI(generics.GenericAPIView):
serializer_class = LoginUserSerializer
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.validated_data
return Response(
{
"user": UserSerializer(
user, context=self.get_serializer_context()
).data,
"token": AuthToken.objects.create(user)[1],
}
)
class UserAPI(generics.RetrieveAPIView):
permission_classes = [permissions.IsAuthenticated]
serializer_class = UserSerializer
def get_object(self):
return self.request.user
class UserListAPI(generics.ListAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
class UserUpdateAPI(generics.RetrieveUpdateAPIView):
permission_classes = [permissions.IsAuthenticated]
serializer_class = UpdateUserSerializer
def retrieve(self, request, *args, **kwargs):
serializer = self.serializer_class(request.user)
return Response(serializer.data, status=status.HTTP_200_OK)
def update(self, request, *args, **kwargs):
serializer = self.serializer_class(request.user, data=request.data, partial=True)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data, status=status.HTTP_200_OK)