서승완

chore: rebase trash, user api

from rest_framework import serializers
from .models import File
class FileSerializer(serializers.ModelSerializer):
class Meta:
model = File
fields = ['id', 'parent_id', 'owner_id', 'uploader_id', 'type', 'name', 'size', 'is_public', 'is_shared',
'is_starred', 'is_trahsed', 'created_at']
\ No newline at end of file
from django.conf.urls import url
from rest_framework.urlpatterns import format_suffix_patterns
from . import views
# API endpoints
urlpatterns = format_suffix_patterns([
url(r'^folders/(?P<pk>\w+)/$', views.FolderRequest.as_view()),
url(r'^folders/$', views.FolderRequest.as_view()),
url(r'^files/', views.StarredFiles.as_view()),
url(r'^files/starred/(?P<pk>\w+).$', views.StarredFiles.as_view()),
url(r'^trash/(?P<pk>\w+)/$', views.TrashReqeust.as_view()),
url(r'^trash/$', views.FolderRequest.as_view()),
])
\ No newline at end of file
from django.contrib import admin
from khubox.models import *
# Register your models here.
admin.site.register(File)
\ No newline at end of file
from django.apps import AppConfig
class UserConfig(AppConfig):
name = 'user'
# -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2020-06-08 16:22
from __future__ import unicode_literals
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)),
('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_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)
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.models import Group
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")
# 로그인 시리얼라이저
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")), #logout/ url접속시 로그아웃
]
from rest_framework import viewsets, permissions, generics, mixins, status
#from rest_framework.authentication import TokenAuthentication
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)
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)