Backend (Django 4.2 + DRF): - accounts: phone OTP login, JWT, profile, addresses - catalog: categories, products, images, filters, search, hits/new/related - orders: creation with Idempotency-Key, stock reservation, status history, cancel - loyalty: bonus accounts, promo codes, gift certificates - payments: payment records and YooKassa webhook handling - content: static pages, banners, site settings - integration: 1C exchange (catalog sync, order push via outbox, statuses, bonuses) - common: error envelope, pagination, request-id, integration auth, admin dashboard Infrastructure: Dockerfile, docker-compose (Postgres, Redis, Celery worker/beat, Nginx), requirements split by environment, OpenAPI contracts for site and 1C, architecture doc. Tests: 22 pytest cases covering catalog, orders, idempotency, OTP, integration.
82 lines
2.8 KiB
Python
82 lines
2.8 KiB
Python
import logging
|
|
import secrets
|
|
from datetime import timedelta
|
|
|
|
import phonenumbers
|
|
from django.conf import settings
|
|
from django.contrib.auth.hashers import check_password, make_password
|
|
from django.utils import timezone
|
|
from rest_framework.exceptions import ValidationError
|
|
|
|
from .models import OtpCode, User
|
|
from .sms import send_sms
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
def normalize_phone(raw_phone: str) -> str:
|
|
"""Normalizes a Russian phone number to E.164 (+7XXXXXXXXXX)."""
|
|
try:
|
|
parsed = phonenumbers.parse(raw_phone, "RU")
|
|
except phonenumbers.NumberParseException as exc:
|
|
raise ValidationError({"phone": "Некорректный номер телефона"}) from exc
|
|
|
|
if not phonenumbers.is_valid_number(parsed):
|
|
raise ValidationError({"phone": "Некорректный номер телефона"})
|
|
|
|
return phonenumbers.format_number(parsed, phonenumbers.PhoneNumberFormat.E164)
|
|
|
|
|
|
def request_otp(
|
|
raw_phone: str, purpose: str = OtpCode.Purpose.LOGIN
|
|
) -> tuple[OtpCode, str]:
|
|
"""Creates a new OTP and sends it via SMS. Returns (otp, code)."""
|
|
phone = normalize_phone(raw_phone)
|
|
code = settings.OTP_DEBUG_CODE or f"{secrets.randbelow(1_000_000):06d}"
|
|
expires_at = timezone.now() + timedelta(seconds=settings.OTP_TTL_SECONDS)
|
|
|
|
# Invalidate previous unused codes for this phone/purpose.
|
|
OtpCode.objects.filter(
|
|
phone=phone, purpose=purpose, is_used=False
|
|
).update(is_used=True)
|
|
|
|
otp = OtpCode.objects.create(
|
|
phone=phone,
|
|
code_hash=make_password(code),
|
|
purpose=purpose,
|
|
expires_at=expires_at,
|
|
)
|
|
send_sms(phone, f"Код входа HOMM: {code}")
|
|
return otp, code
|
|
|
|
|
|
def verify_otp(
|
|
raw_phone: str, code: str, purpose: str = OtpCode.Purpose.LOGIN
|
|
) -> User:
|
|
"""Verifies an OTP and returns the matching (or newly created) user."""
|
|
phone = normalize_phone(raw_phone)
|
|
otp = (
|
|
OtpCode.objects.filter(phone=phone, purpose=purpose, is_used=False)
|
|
.order_by("-created_at")
|
|
.first()
|
|
)
|
|
if otp is None:
|
|
raise ValidationError({"code": "Код не найден. Запросите новый."})
|
|
if otp.is_expired():
|
|
raise ValidationError({"code": "Срок действия кода истёк."})
|
|
if otp.attempts >= settings.OTP_MAX_ATTEMPTS:
|
|
raise ValidationError({"code": "Превышено число попыток. Запросите новый код."})
|
|
|
|
if not check_password(code, otp.code_hash):
|
|
otp.attempts += 1
|
|
otp.save(update_fields=["attempts", "updated_at"])
|
|
raise ValidationError({"code": "Неверный код."})
|
|
|
|
otp.is_used = True
|
|
otp.save(update_fields=["is_used", "updated_at"])
|
|
|
|
user, created = User.objects.get_or_create(phone=phone)
|
|
if created:
|
|
logger.info("New customer registered by phone: %s", phone)
|
|
return user
|