서승완

chore: rebase trash, user api

1 -from rest_framework import serializers
2 -from .models import File
3 -
4 -
5 -class FileSerializer(serializers.ModelSerializer):
6 - class Meta:
7 - model = File
8 - fields = ['id', 'parent_id', 'owner_id', 'uploader_id', 'type', 'name', 'size', 'is_public', 'is_shared',
9 - 'is_starred', 'is_trahsed', 'created_at']
...\ No newline at end of file ...\ No newline at end of file
1 -from django.conf.urls import url
2 -from rest_framework.urlpatterns import format_suffix_patterns
3 -from . import views
4 -
5 -# API endpoints
6 -urlpatterns = format_suffix_patterns([
7 - url(r'^folders/(?P<pk>\w+)/$', views.FolderRequest.as_view()),
8 - url(r'^folders/$', views.FolderRequest.as_view()),
9 - url(r'^files/', views.StarredFiles.as_view()),
10 - url(r'^files/starred/(?P<pk>\w+).$', views.StarredFiles.as_view()),
11 - url(r'^trash/(?P<pk>\w+)/$', views.TrashReqeust.as_view()),
12 - url(r'^trash/$', views.FolderRequest.as_view()),
13 -])
...\ No newline at end of file ...\ No newline at end of file
1 -from django.contrib import admin
2 -from khubox.models import *
3 -
4 -# Register your models here.
5 -admin.site.register(File)
...\ No newline at end of file ...\ No newline at end of file
1 -from django.apps import AppConfig
2 -
3 -
4 -class UserConfig(AppConfig):
5 - name = 'user'
1 -# -*- coding: utf-8 -*-
2 -# Generated by Django 1.11.29 on 2020-06-08 16:22
3 -from __future__ import unicode_literals
4 -
5 -import datetime
6 -from django.db import migrations, models
7 -import user.models
8 -
9 -
10 -class Migration(migrations.Migration):
11 -
12 - initial = True
13 -
14 - dependencies = [
15 - ]
16 -
17 - operations = [
18 - migrations.CreateModel(
19 - name='User',
20 - fields=[
21 - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
22 - ('password', models.CharField(max_length=128, verbose_name='password')),
23 - ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
24 - ('email', models.EmailField(max_length=254, unique=True)),
25 - ('name', models.CharField(max_length=100)),
26 - ('date_of_birth', models.DateField(default=datetime.date.today)),
27 - ('storage_usage', models.FloatField(default=0)),
28 - ('is_admin', models.BooleanField(default=False)),
29 - ],
30 - options={
31 - 'abstract': False,
32 - },
33 - managers=[
34 - ('objects', user.models.UserManager()),
35 - ],
36 - ),
37 - ]
1 -from django.db import models
2 -from django.contrib.auth.models import AbstractBaseUser,BaseUserManager
3 -import datetime
4 -
5 -
6 -class UserManager(BaseUserManager):
7 - use_in_migrations = True
8 -
9 - def create_user(self, email, name, date_of_birth, password=None):
10 - user = self.model(
11 - email=self.normalize_email(email),
12 - date_of_birth=date_of_birth,
13 - name=name,
14 - )
15 - user.set_password(password)
16 - user.save(using=self._db)
17 - return user
18 -
19 - def create_staffuser(self, email, name, date_of_birth, password):
20 - user = self.create_user(
21 - email,
22 - password=password,
23 - date_of_birth=date_of_birth,
24 - name=name,
25 - )
26 - user.staff = True
27 - user.save(using=self._db)
28 - return user
29 -
30 - def create_superuser(self, email, name, date_of_birth, password):
31 - user = self.create_user(
32 - email,
33 - password=password,
34 - date_of_birth=date_of_birth,
35 - name= "True",
36 - )
37 - user.is_admin = True
38 - user.save(using=self._db)
39 - return user
40 -
41 -
42 -
43 -
44 -class User(AbstractBaseUser):
45 -
46 - username = None
47 - email = models.EmailField( unique=True)
48 - name = models.CharField(max_length=100)
49 - date_of_birth = models.DateField(default=datetime.date.today)
50 - storage_usage = models.FloatField( default = 0)
51 -
52 - is_admin = models.BooleanField(default=False)
53 -
54 - USERNAME_FIELD = 'email'
55 - REQUIRED_FIELDS = [ 'date_of_birth','name' ]
56 -
57 - objects = UserManager()
58 -
59 - def __str__(self):
60 - return self.email
61 -
62 - @property
63 - def is_staff(self):
64 - return self.is_admin
65 -
66 - def has_perm(self, perm, obj = None):
67 - return True
68 -
69 - def has_module_perms(self, app_label):
70 - return True
71 -
1 -from rest_framework import serializers
2 -from .models import User
3 -from django.contrib.auth.models import Group
4 -from django.contrib.auth import authenticate
5 -
6 -
7 -# 회원가입 시리얼라이저
8 -
9 -class CreateUserSerializer(serializers.ModelSerializer):
10 - class Meta:
11 - model = User
12 - fields = ("email", "name", "date_of_birth", "password")
13 - extra_kwargs = {"password": {"write_only": True}}
14 -
15 - def create(self, validated_data):
16 - user = User.objects.create_user(
17 - validated_data["email"],
18 - validated_data["name"],
19 - validated_data["date_of_birth"],
20 - validated_data["password"]
21 - )
22 - return user
23 -
24 -
25 -# 접속 유지중인지 확인할 시리얼라이저
26 -
27 -class UserSerializer(serializers.ModelSerializer):
28 - class Meta:
29 - model = User
30 - fields = ("id","email", "name","date_of_birth","storage_usage")
31 -
32 -
33 -# 로그인 시리얼라이저
34 -
35 -class LoginUserSerializer(serializers.Serializer):
36 - email = serializers.EmailField()
37 - password = serializers.CharField()
38 -
39 - def validate(self, data):
40 - user = authenticate(**data)
41 - if user and user.is_active:
42 - return user
43 - raise serializers.ValidationError("Unable to log in with provided credentials.")
44 -
45 -
46 -class UpdateUserSerializer(serializers.ModelSerializer):
47 - class Meta:
48 - model = User
49 - fields = ("email", "name", "date_of_birth","storage_usage", "password")
50 - extra_kwargs = {"password": {"write_only": True}}
51 - read_only_fields = ('email',"storage_usage")
52 -
53 - def update(self, instance, validated_data):
54 -
55 - password = validated_data.pop('password', None)
56 -
57 - for (key, value) in validated_data.items():
58 - setattr(instance, key, value)
59 -
60 - if password is not None:
61 - instance.set_password(password)
62 -
63 - instance.save()
64 -
65 - return instance
66 -
1 -from django.test import TestCase
2 -
3 -# Create your tests here.
1 -from django.conf.urls import url, include
2 -from .views import (RegistrationAPI,
3 - LoginAPI,
4 - UserAPI,
5 - RegistrationAPI,
6 - UserListAPI,
7 - UserUpdateAPI,
8 - )
9 -
10 -urlpatterns =[
11 - url("^register/$", RegistrationAPI.as_view()),
12 - url("^login/$", LoginAPI.as_view()),
13 - url("^user/$", UserAPI.as_view()),
14 - url("^update/$", UserUpdateAPI.as_view()),
15 - url("^userlist/$", UserListAPI.as_view()),
16 - url("",include("knox.urls")), #logout/ url접속시 로그아웃
17 -]
18 -
1 -from rest_framework import viewsets, permissions, generics, mixins, status
2 -#from rest_framework.authentication import TokenAuthentication
3 -from rest_framework.response import Response
4 -from .models import User
5 -from .serializers import (
6 - CreateUserSerializer,
7 - UserSerializer,
8 - LoginUserSerializer,
9 - UpdateUserSerializer,
10 -)
11 -from knox.models import AuthToken
12 -
13 -
14 -class RegistrationAPI(generics.GenericAPIView):
15 - serializer_class = CreateUserSerializer
16 -
17 - def post(self, request, *args, **kwargs):
18 - if len(request.data["email"]) < 6 or len(request.data["password"]) < 4:
19 - body = {"message": "short field"}
20 - return Response(body, status=status.HTTP_400_BAD_REQUEST)
21 - serializer = self.get_serializer(data=request.data)
22 - serializer.is_valid(raise_exception=True)
23 - user = serializer.save()
24 - return Response(
25 - {
26 - "user": UserSerializer(
27 - user, context=self.get_serializer_context()
28 - ).data,
29 - "token": AuthToken.objects.create(user)[1],
30 - }
31 - )
32 -
33 -
34 -class LoginAPI(generics.GenericAPIView):
35 - serializer_class = LoginUserSerializer
36 -
37 - def post(self, request, *args, **kwargs):
38 - serializer = self.get_serializer(data=request.data)
39 - serializer.is_valid(raise_exception=True)
40 - user = serializer.validated_data
41 - return Response(
42 - {
43 - "user": UserSerializer(
44 - user, context=self.get_serializer_context()
45 - ).data,
46 - "token": AuthToken.objects.create(user)[1],
47 - }
48 - )
49 -
50 -
51 -class UserAPI(generics.RetrieveAPIView):
52 - permission_classes = [permissions.IsAuthenticated]
53 - serializer_class = UserSerializer
54 -
55 - def get_object(self):
56 - return self.request.user
57 -
58 -
59 -class UserListAPI(generics.ListAPIView):
60 - queryset = User.objects.all()
61 - serializer_class = UserSerializer
62 -
63 -
64 -class UserUpdateAPI(generics.RetrieveUpdateAPIView):
65 - permission_classes = [permissions.IsAuthenticated]
66 - serializer_class = UpdateUserSerializer
67 - def retrieve(self, request, *args, **kwargs):
68 - serializer = self.serializer_class(request.user)
69 - return Response(serializer.data, status=status.HTTP_200_OK)
70 - def update(self, request, *args, **kwargs):
71 - serializer = self.serializer_class(request.user, data=request.data, partial=True)
72 - serializer.is_valid(raise_exception=True)
73 - serializer.save()
74 - return Response(serializer.data, status=status.HTTP_200_OK)