하재연

auth modified

# Generated by Django 3.0.7 on 2020-06-10 17:40
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0008_item_file_type'),
]
operations = [
migrations.RemoveField(
model_name='user',
name='id',
),
migrations.AlterField(
model_name='user',
name='int_id',
field=models.AutoField(primary_key=True, serialize=False),
),
]
# Generated by Django 3.0.7 on 2020-06-10 17:42
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0009_auto_20200611_0240'),
]
operations = [
migrations.AlterField(
model_name='user',
name='current_size',
field=models.BigIntegerField(blank=True, default=0),
),
migrations.AlterField(
model_name='user',
name='total_size',
field=models.BigIntegerField(blank=True, default=1099511627776),
),
]
......@@ -17,7 +17,7 @@ class Item(models.Model):
status = models.BooleanField()
#file = models.FileField(upload_to = \path)
class Meta:
ordering = ['item_id']
......@@ -33,12 +33,13 @@ class SharedItem(models.Model):
class User(models.Model):
int_id = models.IntegerField()
user_id = models.CharField(max_length = 50)
name = models.CharField(max_length = 50)
password = models.CharField(max_length = 20)
total_size = models.IntegerField()
current_size = models.IntegerField()
int_id = models.AutoField(primary_key=True)
user_id = models.CharField(max_length=50)
name = models.CharField(max_length=50)
password = models.CharField(max_length=20)
total_size = models.BigIntegerField(blank=True, default=1099511627776)
current_size = models.BigIntegerField(blank=True, default=0)
created_time = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['int_id']
......
from django.contrib.auth.models import User, Group
from rest_framework import serializers
from api.models import Item, SharedItem
from api.models import User
class UserSerializer(serializers.HyperlinkedModelSerializer):
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['url', 'username', 'email', 'groups']
fields = '__all__'
class SignUpSerializer(serializers.ModelSerializer):
password2 = serializers.CharField(style={"input_type": "password"})
class GroupSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Group
fields = ['url', 'name']
model = User
fields = ['user_id', 'name', 'password', 'password2']
class ItemSerializer(serializers.ModelSerializer):
def create(self, data):
user_id = data['user_id']
name = data['name']
password = self.data['password']
password2 = self.data['password2']
if user_id and User.objects.filter(user_id=user_id).exclude(name=name).exists():
raise serializers.ValidationError({"user_id": "User_id must be unique."})
elif password != password2:
raise serializers.ValidationError({'password': "Passwords must match."})
user = User.objects.create(
user_id=data['user_id'],
name=data['name'],
password=data['password'],
)
user.save()
return user
class UserInfoSerializer(serializers.ModelSerializer):
class Meta:
model = Item
fields = '__all__'
model = User
fields = ['user_id', 'name', 'total_size', 'current_size', 'created_time']
......
import jwt
import json
from rest_framework import status
from django.http import JsonResponse
from django.core.exceptions import ObjectDoesNotExist
from django.conf import settings
from api.models import User
def login_decorator(func):
def wrapper(self, request, *args, **kwargs):
if 'Authorization' not in request.headers:
return JsonResponse({'Error': 'INVALID_LOGIN'}, status=status.HTTP_401_UNAUTHORIZED)
encode_token = request.headers['Authorization']
try:
payload = jwt.decode(encode_token, settings.SECRET_KEY, algorithm='HS256')
user = User.objects.get(int_id=payload['int_id'])
request.user = user
except jwt.exceptions.DecodeError:
return JsonResponse({'Error': 'INVALID_TOKEN'}, status=status.HTTP_400)
except User.DoesNotExist:
return JsonResponse({'Error': 'UNKNOWN_USER'}, status=status.HTTP_400)
return func(self, request, *args, **kwargs)
return wrapper
\ No newline at end of file
This diff is collapsed. Click to expand it.
"""
Django settings for khudrive project.
Generated by 'django-admin startproject' using Django 3.0.7.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ')i0_(*4t7k3=rcqp*_i0u((9zbk8q(2(3tk(%$woji-e-37=o*'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
......@@ -40,7 +27,6 @@ INSTALLED_APPS = [
'rest_framework',
'api.apps.ApiConfig',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
......@@ -50,9 +36,7 @@ MIDDLEWARE = [
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'khudrive.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
......@@ -68,10 +52,7 @@ TEMPLATES = [
},
},
]
WSGI_APPLICATION = 'khudrive.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
......@@ -82,17 +63,14 @@ DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'khuDrive',
'USER': 'jooheekwon',
'PASSWORD': '',
'USER': 'hjy',
'PASSWORD': '2521',
'HOST': 'localhost',
'PORT': '',
'PORT': '5432',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
......@@ -107,23 +85,13 @@ AUTH_PASSWORD_VALIDATORS = [
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
STATIC_URL = '/static/'
\ No newline at end of file
......
"""khudrive URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.urls import include, path
from rest_framework import routers
from django.contrib import admin
from api import views
from django.conf.urls import url
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'items', views.ItemViewSet)
router.register(r'items', views.SharedItemViewSet)
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
path('admin/', admin.site.urls),
path('', include(router.urls)),
url(r'^search/$', views.ItemViewSet.search, name='search'),
url(r'^<int:pk>/share/$', views.SharedItemViewSet.share, name='share'),
url(r'^<int:pk>/move/$', views.ItemViewSet.move, name='move'),
url(r'^<int:pk>/copy/$', views.ItemViewSet.copy, name='copy'),
]
url(r'^signup/$', views.UserViewSet.signup, name='signup'),
url(r'^login/$', views.UserViewSet.login, name='login'),
url(r'^renew/$', views.UserViewSet.renew, name='renew'),
url(r'^<int:pk>/info/$', views.UserViewSet.info, name='info'),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]
\ No newline at end of file
......