김대연
Committed by 서승완

Add Knox Token

from django.contrib import admin
# Register your models here.
from django.apps import AppConfig
class UserConfig(AppConfig):
name = 'user'
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.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
class GroupSerializer (serializers.HyperlinkedModelSerializer):
class Meta
\ No newline at end of file
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.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)