Skip to content

Commit

Permalink
Check the user's age (from 6 to 110 years old is acceptable) at the A…
Browse files Browse the repository at this point in the history
…PI level, update this check at the model level
  • Loading branch information
earlinn committed Feb 3, 2024
1 parent 7cd9214 commit 1c7ed51
Show file tree
Hide file tree
Showing 4 changed files with 65 additions and 8 deletions.
18 changes: 17 additions & 1 deletion backend/api/users_serializers.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,20 @@
from dateutil.relativedelta import relativedelta
from django.contrib.auth import get_user_model
from django.db import transaction
from django.utils import timezone
from djoser.serializers import UserCreateSerializer as DjoserUserCreateSerializer
from djoser.serializers import UserDeleteSerializer as DjoserUserDeleteSerializer
from djoser.serializers import UserSerializer as DjoserUserSerializer
from rest_framework import serializers
from rest_framework.validators import UniqueValidator

from users.models import Address
from users.models import (
BIRTH_DATE_TOO_OLD_ERROR_MESSAGE,
BIRTH_DATE_TOO_YOUNG_ERROR_MESSAGE,
MAX_USER_AGE,
MIN_USER_AGE,
Address,
)
from users.utils import city_choices

User = get_user_model()
Expand Down Expand Up @@ -69,6 +77,14 @@ class Meta:
"photo",
)

def validate_birth_date(self, value):
now = timezone.now()
if value + relativedelta(years=MIN_USER_AGE) > now.date():
raise serializers.ValidationError(BIRTH_DATE_TOO_YOUNG_ERROR_MESSAGE)
if value + relativedelta(years=MAX_USER_AGE) < now.date():
raise serializers.ValidationError(BIRTH_DATE_TOO_OLD_ERROR_MESSAGE)
return value

def get_address_quantity(self, obj) -> int:
return obj.addresses.count()

Expand Down
27 changes: 21 additions & 6 deletions backend/users/models.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from dateutil.relativedelta import relativedelta
from django.contrib.auth.models import AbstractUser
from django.contrib.auth.validators import UnicodeUsernameValidator
from django.core.exceptions import ValidationError
Expand All @@ -13,6 +14,16 @@
"форматах '+7XXXXXXXXXX', '7XXXXXXXXXX' или '8XXXXXXXXXX'."
)
PHONE_NUMBER_REGEX = r"^(\+7|7|8)\d{10}$"
MIN_USER_AGE = 6
MAX_USER_AGE = 110
BIRTH_DATE_TOO_YOUNG_ERROR_MESSAGE = (
"Указана неверная дата рождения, "
f"пользователю должно быть не менее {MIN_USER_AGE} лет."
)
BIRTH_DATE_TOO_OLD_ERROR_MESSAGE = (
"Указана неверная дата рождения, "
f"пользователю должно быть не более {MAX_USER_AGE} лет."
)


@cleanup.select
Expand Down Expand Up @@ -59,12 +70,16 @@ def clean_fields(self, exclude=None):
"""Checks the user's birth date."""
super().clean_fields(exclude=exclude)
now = timezone.now()
if self.birth_date:
if (
self.birth_date.year > now.year
or (now.year - self.birth_date.year) > 120
):
raise ValidationError("Указана неверная дата рождения.")
if (
self.birth_date
and self.birth_date + relativedelta(years=MIN_USER_AGE) > now.date()
):
raise ValidationError(BIRTH_DATE_TOO_YOUNG_ERROR_MESSAGE)
if (
self.birth_date
and self.birth_date + relativedelta(years=MAX_USER_AGE) < now.date()
):
raise ValidationError(BIRTH_DATE_TOO_OLD_ERROR_MESSAGE)


class Address(models.Model):
Expand Down
27 changes: 26 additions & 1 deletion poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ pytest = "^7.4.3"
pytest-django = "^4.7.0"
django-phonenumber-field = {extras = ["phonenumberslite"], version = "^7.2.0"}
stripe = "^7.8.2"
python-dateutil = "^2.8.2"


[tool.poetry.group.dev.dependencies]
Expand Down

0 comments on commit 1c7ed51

Please sign in to comment.