Skip to content

Commit

Permalink
MVP приложение CustomUser
Browse files Browse the repository at this point in the history
  • Loading branch information
Abramov0Alexandr committed Sep 24, 2023
1 parent 242dabe commit e813095
Show file tree
Hide file tree
Showing 11 changed files with 157 additions and 1 deletion.
3 changes: 2 additions & 1 deletion config/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,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 rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView


urlpatterns = [
path('admin/', admin.site.urls),
path('users/', include('custom_user.urls', namespace='custom_user')),

# authorization urls
path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
Expand Down
Empty file added custom_user/__init__.py
Empty file.
9 changes: 9 additions & 0 deletions custom_user/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from django.contrib import admin
from custom_user.models import CustomUser


@admin.register(CustomUser)
class UserAdmin(admin.ModelAdmin):
list_display = ('email', 'phone', 'is_seller', 'is_active', )
list_display_links = ('email', )
list_editable = ('is_seller', 'is_active', )
7 changes: 7 additions & 0 deletions custom_user/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from django.apps import AppConfig


class CustomUserConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'custom_user'
verbose_name = 'Зарегистрированные пользователи'
Empty file.
37 changes: 37 additions & 0 deletions custom_user/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
from django.contrib.auth.models import AbstractUser
from django.db import models
from custom_user.user_manager import CustomUserManager


NULLABLE = {'blank': True, 'null': True}


class CustomUser(AbstractUser):
"""
Расширение стандартной модели пользователя в соответствии с требованиями текущего проекта.
"""

class VisitorStatus(models.IntegerChoices):
"""
Вспомогательный класс для определения статуса посетителя магазина.
По умолчанию, каждый новый пользователь имеет статус 'Посетитель'.
"""

COMMON_USER = 0, "Посетитель"
SELLER = 1, "Продавец"

username = None

email = models.EmailField(unique=True, verbose_name='Email')

phone = models.CharField(max_length=20, verbose_name='Телефон', **NULLABLE)

is_seller = models.BooleanField(choices=VisitorStatus.choices, default=VisitorStatus.COMMON_USER,
verbose_name='Статус посетителя')

is_active = models.BooleanField(default=True, verbose_name='Статус активации')

objects = CustomUserManager()

USERNAME_FIELD = "email"
REQUIRED_FIELDS = []
35 changes: 35 additions & 0 deletions custom_user/serializers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
from rest_framework import serializers
from custom_user.models import CustomUser


class CustomUserListSerializer(serializers.ModelSerializer):
"""
Сериализатор модели CustomUser.
Используется при вызове GET запросов в контроллере CustomUserListView
"""

class Meta:
model = CustomUser
fields = '__all__'


class CustomUserCreateSerializer(serializers.ModelSerializer):
"""
Сериализатор модели CustomUser.
Используется при вызове GET запросов в контроллере CustomUserCreateView
"""

class Meta:
model = CustomUser
fields = ('password', 'email', )

def create(self, validated_data):
"""
:param validated_data: Данные, переданные при создании нового пользователя
Метод переопределен для корректного создания нового пользователя.
Пароль указанный при создании пользователя хэшируется, появляется возможность авторизации по JWT.
:return: Создается новый экземпляр класса CustomUser
"""

new_custom_user = CustomUser.objects.create_user(**validated_data)
return new_custom_user
Empty file added custom_user/tests.py
Empty file.
12 changes: 12 additions & 0 deletions custom_user/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
from django.urls import path
from .apps import CustomUserConfig
from .views import CustomUserListView, CustomUserCreateView


app_name = CustomUserConfig.name


urlpatterns = [
path('', CustomUserListView.as_view(), name='custom_user_list'),
path('create/', CustomUserCreateView.as_view(), name='custom_user_create')
]
38 changes: 38 additions & 0 deletions custom_user/user_manager.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
from django.apps import apps
from django.contrib.auth.hashers import make_password
from django.contrib.auth.models import UserManager


class CustomUserManager(UserManager):
use_in_migrations = True

def _create_user(self, email, password, **extra_fields):
"""
Create and save a user with the given username, email, and password.
"""

email = self.normalize_email(email)

GlobalUserModel = apps.get_model(
self.model._meta.app_label, self.model._meta.object_name
)
user = self.model(email=email, **extra_fields)
user.password = make_password(password)
user.save(using=self._db)
return user

def create_user(self, email=None, password=None, **extra_fields):
extra_fields.setdefault("is_staff", False)
extra_fields.setdefault("is_superuser", False)
return self._create_user(email, password, **extra_fields)

def create_superuser(self, email=None, password=None, **extra_fields):
extra_fields.setdefault("is_staff", True)
extra_fields.setdefault("is_superuser", True)

if extra_fields.get("is_staff") is not True:
raise ValueError("Superuser must have is_staff=True.")
if extra_fields.get("is_superuser") is not True:
raise ValueError("Superuser must have is_superuser=True.")

return self._create_user(email, password, **extra_fields)
17 changes: 17 additions & 0 deletions custom_user/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
from rest_framework import generics
from custom_user.models import CustomUser
from custom_user.serializers import CustomUserListSerializer, CustomUserCreateSerializer


class CustomUserListView(generics.ListAPIView):
"""Контроллер для отображения списка зарегистрированных пользователей"""

serializer_class = CustomUserListSerializer
queryset = CustomUser.objects.all()


class CustomUserCreateView(generics.CreateAPIView):
"""Контроллер для регистрации новых пользователей"""

queryset = CustomUser.objects.all()
serializer_class = CustomUserCreateSerializer

0 comments on commit e813095

Please sign in to comment.