Skip to content

Commit

Permalink
Merge pull request #2 from Team-MailedIt/feature-account
Browse files Browse the repository at this point in the history
Feature account
  • Loading branch information
kynzun authored Nov 26, 2021
2 parents d825dd1 + de8eade commit cff2367
Show file tree
Hide file tree
Showing 16 changed files with 199 additions and 52 deletions.
Empty file added account/__init__.py
Empty file.
5 changes: 5 additions & 0 deletions account/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from django.contrib import admin
from .models import User

# Register your models here.
admin.site.register(User)
5 changes: 5 additions & 0 deletions account/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from django.apps import AppConfig


class AccountConfig(AppConfig):
name = 'account'
45 changes: 45 additions & 0 deletions account/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# Generated by Django 3.0.8 on 2021-11-25 14:25

import django.contrib.auth.models
import django.contrib.auth.validators
from django.db import migrations, models
import django.utils.timezone


class Migration(migrations.Migration):

initial = True

dependencies = [
('auth', '0011_update_proxy_permissions'),
]

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')),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')),
('first_name', models.CharField(blank=True, max_length=30, verbose_name='first name')),
('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')),
('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')),
('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')),
('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),
('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
('part', models.CharField(choices=[('FE', '프론트엔드'), ('BE', '백엔드')], max_length=2)),
('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')),
('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')),
],
options={
'verbose_name': 'user',
'verbose_name_plural': 'users',
'abstract': False,
},
managers=[
('objects', django.contrib.auth.models.UserManager()),
],
),
]
Empty file added account/migrations/__init__.py
Empty file.
11 changes: 11 additions & 0 deletions account/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from django.db import models
from django.contrib.auth.models import AbstractUser, BaseUserManager

PART_CHOICES = [
("FE", "프론트엔드"),
("BE", "백엔드"),
]


class User(AbstractUser):
part = models.CharField(max_length=2, choices=PART_CHOICES)
17 changes: 17 additions & 0 deletions account/serializers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
from rest_framework import serializers
from django.contrib.auth import get_user_model

User = get_user_model()


class RegisterSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ("username", "password", "part")

def create(self, validated_data):
password = validated_data.pop("password")
user = User(**validated_data)
user.set_password(password)
user.save()
return user
3 changes: 3 additions & 0 deletions account/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.test import TestCase

# Create your tests here.
11 changes: 11 additions & 0 deletions account/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from django.urls import path
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView
from .views import RegisterAPIView, TestAPIView

urlpatterns = [
path("signin", TokenObtainPairView.as_view(), name="token_obtain_pair"),
# 세션 연장하고 싶을 때 refresh token 사용
# path("token/refresh", TokenRefreshView.as_view(), name="token_refresh"),
path("signup", RegisterAPIView.as_view()),
path("test", TestAPIView.as_view()),
]
37 changes: 37 additions & 0 deletions account/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status
from django.contrib.auth import get_user_model
from .serializers import RegisterSerializer
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer


User = get_user_model()

# Create your views here.
class RegisterAPIView(APIView):
def post(self, request):
user_serializer = RegisterSerializer(data=request.data)
if user_serializer.is_valid():
user = user_serializer.save()
# access jwt token
token = TokenObtainPairSerializer.get_token(user)
return Response(
{
"user": user_serializer.data,
"message": "Successfully registered user",
"token": {
"refresh": str(token),
"access": str(token.access_token),
},
},
status=status.HTTP_201_CREATED,
)
return Response(user_serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class TestAPIView(APIView):
def get(self, request):
return Response(
{"message": "test API successfully responsed"}, status=status.HTTP_200_OK
)
4 changes: 4 additions & 0 deletions config/docker/entrypoint.prod.sh
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
#!/bin/sh

echo "Collect static files"
python manage.py collectstatic --no-input

echo "Apply database migrations"
python manage.py migrate

exec "$@"
3 changes: 1 addition & 2 deletions docker-compose.prod.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
version: '3.8'
version: "3.8"
services:

web:
container_name: web
build:
Expand Down
3 changes: 3 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,11 @@ cffi==1.15.0
cryptography==35.0.0
Django==3.0.8
django-environ==0.4.5
djangorestframework==3.12.4
djangorestframework-simplejwt==5.0.0
gunicorn==20.1.0
pycparser==2.21
PyJWT==2.3.0
PyMySQL==1.0.2
pytz==2021.3
sqlparse==0.4.2
86 changes: 46 additions & 40 deletions vote_mailedit/settings/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,91 +16,97 @@
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

env = environ.Env(
DEBUG=(bool, False)
)
env = environ.Env(DEBUG=(bool, False))

environ.Env.read_env(os.path.join(BASE_DIR, '.env'))
environ.Env.read_env(os.path.join(BASE_DIR, ".env"))

# 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 = env('DJANGO_SECRET_KEY')
SECRET_KEY = env("DJANGO_SECRET_KEY")

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = env('DEBUG')
DEBUG = env("DEBUG")

ALLOWED_HOSTS = []

AUTH_USER_MODEL = "account.User"

# Application definition

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"account",
]

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]

ROOT_URLCONF = 'vote_mailedit.urls'
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": (
"rest_framework_simplejwt.authentication.JWTAuthentication",
),
}

ROOT_URLCONF = "vote_mailedit.urls"

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
},
},
]

WSGI_APPLICATION = 'vote_mailedit.wsgi.application'
WSGI_APPLICATION = "vote_mailedit.wsgi.application"


# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
},
]


# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/

LANGUAGE_CODE = 'ko-KR'
LANGUAGE_CODE = "ko-KR"

TIME_ZONE = 'Asia/Seoul'
TIME_ZONE = "Asia/Seoul"

USE_I18N = True

Expand All @@ -112,9 +118,9 @@
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = "/static/"
STATIC_ROOT = os.path.join(BASE_DIR, "static")

# Media files
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
16 changes: 8 additions & 8 deletions vote_mailedit/settings/prod.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@

DEBUG = False

ALLOWED_HOSTS = env.list('DJANGO_ALLOWED_HOSTS')
ALLOWED_HOSTS = env.list("DJANGO_ALLOWED_HOSTS")

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': env('DATABASE_NAME'),
'USER': env('DATABASE_USER'),
'PASSWORD': env('DATABASE_PASSWORD'),
'HOST': env('DATABASE_HOST'),
'PORT': env('DATABASE_PORT'),
"default": {
"ENGINE": "django.db.backends.mysql",
"NAME": env("DATABASE_NAME"),
"USER": env("DATABASE_USER"),
"PASSWORD": env("DATABASE_PASSWORD"),
"HOST": env("DATABASE_HOST"),
"PORT": env("DATABASE_PORT"),
}
}
5 changes: 3 additions & 2 deletions vote_mailedit/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,13 @@
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from django.urls import path, include
from django.conf.urls.static import static
from .settings import base

urlpatterns = [
path('admin/', admin.site.urls),
path("admin/", admin.site.urls),
path("api/", include("account.urls")),
]

if base.DEBUG:
Expand Down

0 comments on commit cff2367

Please sign in to comment.