From 602bae03a0f6dc204c33316448254fdb4447dbb4 Mon Sep 17 00:00:00 2001 From: anthonyA1214 Date: Fri, 27 Nov 2026 17:46:59 +0800 Subject: [PATCH] fix(users,config): reject duplicate emails and trust CSRF origins - Return 409 from create_user when the email already exists, matching case-insensitively and including soft-deleted users - Read CSRF_TRUSTED_ORIGINS from the environment in base settings - Add CSRF_TRUSTED_ORIGINS to .env.example, allow port 3000 in the CORS example, and point FRONTEND_URL to localhost:3000 --- .env.example | 7 ++++--- apps/users/services.py | 4 ++++ config/settings/base.py | 2 ++ 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/.env.example b/.env.example index f20d0a7..8707775 100644 --- a/.env.example +++ b/.env.example @@ -6,7 +6,7 @@ DJANGO_SECRET_KEY= DJANGO_ALLOWED_HOSTS=localhost,0.0.0.0,127.0.0.1 # Public base URL of the web frontend (used for links in emails, redirects, etc.) -FRONTEND_URL=http://localhost:5173 +FRONTEND_URL=http://localhost:3000 # ============================================================================= # Database (PostgreSQL) @@ -25,10 +25,11 @@ DATABASE_URL=postgres://user:password@localhost:5432/dbname REDIS_URL=redis://localhost:6379/0 # ============================================================================= -# CORS +# CORS / CSRF # ============================================================================= # Comma-separated for multiple origins (e.g. http://localhost:5173,http://localhost:3000) -CORS_ALLOWED_ORIGINS=http://localhost:5173 +CORS_ALLOWED_ORIGINS=http://localhost:5173,http://localhost:3000 +CSRF_TRUSTED_ORIGINS=http://localhost:5173,http://localhost:3000 # ============================================================================= # Email (SMTP) diff --git a/apps/users/services.py b/apps/users/services.py index 054673a..d8d5b46 100644 --- a/apps/users/services.py +++ b/apps/users/services.py @@ -1,5 +1,6 @@ from allauth.account.models import EmailAddress from django.db import transaction +from ninja.errors import HttpError from rolepermissions.roles import assign_role from .filters import UserFilterSchema # noqa: TC001 @@ -17,6 +18,9 @@ def list_users(self, filters: UserFilterSchema | None): @transaction.atomic def create_user(self, payload: UserCreateIn) -> User: + if User.objects.all_with_deleted().filter(email__iexact=payload.email).exists(): # pyright: ignore[reportAttributeAccessIssue] + raise HttpError(409, "User with this email already exists.") + user = User.objects.create_user( username=payload.email, email=payload.email, diff --git a/config/settings/base.py b/config/settings/base.py index dcee7ea..9427cdf 100644 --- a/config/settings/base.py +++ b/config/settings/base.py @@ -65,6 +65,8 @@ CORS_ALLOWED_ORIGINS = env.list("CORS_ALLOWED_ORIGINS") CORS_ALLOW_CREDENTIALS = True +CSRF_TRUSTED_ORIGINS = env.list("CSRF_TRUSTED_ORIGINS") + HEADLESS_ONLY = True HEADLESS_SERVE_SPECIFICATION = True