Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

fix(auth): normalize Gmail registration emails (#41249)

林玮 (Jade Lin)f5aaa50a3092
diff --git a/api/commands/account.py b/api/commands/account.py
index c81c9fb4526..dc00f431a77 100644
--- a/api/commands/account.py
+++ b/api/commands/account.py
@@ -8,6 +8,7 @@ from constants.languages import languages
from extensions.ext_database import db
from libs.helper import email as email_validate
from libs.password import hash_password, password_pattern, valid_password
+from services.account_email import normalize_email
from services.account_service import AccountService, RegisterService, TenantService
@@ -82,6 +83,7 @@ def reset_email(email, new_email, email_confirm):
with Session(db.engine) as session:
account = session.merge(account)
account.email = normalized_new_email
+ account.normalized_email = normalize_email(normalized_new_email)
session.commit()
click.echo(click.style("Email updated successfully.", fg="green"))
diff --git a/api/controllers/console/auth/email_register.py b/api/controllers/console/auth/email_register.py
index 8d5244b5312..e81acbed99d 100644
--- a/api/controllers/console/auth/email_register.py
+++ b/api/controllers/console/auth/email_register.py
@@ -13,6 +13,7 @@ from controllers.console.auth.error import (
EmailRegisterLimitError,
InvalidEmailError,
InvalidTokenError,
+ NormalizedEmailAlreadyInUseError,
PasswordMismatchError,
)
from enums import DeploymentEdition
@@ -25,6 +26,7 @@ from models import Account
from services.account_service import AccountService
from services.billing_service import BillingService
from services.errors.account import (
+ AccountNormalizedEmailAlreadyInUseError,
AccountRegisterError,
SeatsLimitExceededError,
)
@@ -221,11 +223,14 @@ class EmailRegisterResetApi(Resource):
interface_language=get_valid_language(language),
timezone=timezone,
ip_address=ip_address,
+ check_normalized_email=True,
session=db.session(),
)
except SeatsLimitExceededError:
raise SeatsLimitExceeded()
except EmailDomainSuspendedRegistrationError as exc:
raise EmailDomainSuspendedError() from exc
+ except AccountNormalizedEmailAlreadyInUseError as exc:
+ raise NormalizedEmailAlreadyInUseError() from exc
except AccountRegisterError as exc:
raise AccountInFreezeError() from exc
diff --git a/api/controllers/console/auth/error.py b/api/controllers/console/auth/error.py
index 4ff9b4d33bc..daf7b344bee 100644
--- a/api/controllers/console/auth/error.py
+++ b/api/controllers/console/auth/error.py
@@ -175,6 +175,11 @@ class EmailAlreadyInUseError(BaseHTTPException):
code = 400
+class NormalizedEmailAlreadyInUseError(EmailAlreadyInUseError):
+ error_code = "normalized_email_already_in_use"
+ description = "An account with an equivalent email address already exists."
+
+
class OwnerTransferLimitError(BaseHTTPException):
error_code = "owner_transfer_limit"
description = "Too many failed owner transfer attempts. Please try again in 24 hours."
diff --git a/api/controllers/console/auth/login.py b/api/controllers/console/auth/login.py
index 4252b4373c3..14b51df7dcc 100644
--- a/api/controllers/console/auth/login.py
+++ b/api/controllers/console/auth/login.py
@@ -27,6 +27,7 @@ from controllers.console.auth.error import (
EmailPasswordLoginLimitError,
InvalidEmailError,
InvalidTokenError,
+ NormalizedEmailAlreadyInUseError,
TurnstileServiceUnavailableError,
TurnstileVerificationFailedError,
)
@@ -70,6 +71,7 @@ from services.email_code_login_challenge import (
)
from services.entities.auth_entities import LoginFailureReason, LoginPayloadBase
from services.errors.account import (
+ AccountNormalizedEmailAlreadyInUseError,
AccountRegisterError,
RefreshTokenAccountNotFoundError,
RefreshTokenNotFoundError,
@@ -412,6 +414,7 @@ class EmailCodeLoginApi(Resource):
interface_language=get_valid_language(language),
timezone=req_data.timezone,
ip_address=ip_address,
+ check_normalized_email=True,
session=db.session(),
)
except WorkSpaceNotAllowedCreateError:
@@ -421,6 +424,8 @@ class EmailCodeLoginApi(Resource):
except EmailDomainSuspendedRegistrationError as exc:
_log_console_login_failure(email=user_email, reason=LoginFailureReason.ACCOUNT_IN_FREEZE)
raise EmailDomainSuspendedError() from exc
+ except AccountNormalizedEmailAlreadyInUseError as exc:
+ raise NormalizedEmailAlreadyInUseError() from exc
except AccountRegisterError as exc:
_log_console_login_failure(email=user_email, reason=LoginFailureReason.ACCOUNT_IN_FREEZE)
raise AccountInFreezeError() from exc
diff --git a/api/migrations/versions/2026_08_25_1200-9b7c6d5e4f3a_add_normalized_email_to_accounts.py b/api/migrations/versions/2026_08_25_1200-9b7c6d5e4f3a_add_normalized_email_to_accounts.py
new file mode 100644
index 00000000000..9f1a629c012
--- /dev/null
+++ b/api/migrations/versions/2026_08_25_1200-9b7c6d5e4f3a_add_normalized_email_to_accounts.py
@@ -0,0 +1,95 @@
+"""add normalized email to accounts
+
+The normalized value is indexed but intentionally not unique. Existing
+installations may already contain equivalent accounts, and registration-time
+validation must preserve those records while preventing new collisions.
+"""
+
+import sqlalchemy as sa
+from alembic import op
+
+# revision identifiers, used by Alembic.
+revision = "9b7c6d5e4f3a"
+down_revision = "a4f8d2c9e1b0"
+branch_labels = None
+depends_on = None
+
+
+def _backfill_normalized_emails() -> None:
+ dialect_name = op.get_context().dialect.name
+ if dialect_name == "postgresql":
+ op.execute(
+ sa.text(
+ r"""
+ UPDATE accounts
+ SET normalized_email = CASE
+ WHEN LOWER(email) LIKE '%@gmail.com'
+ OR LOWER(email) LIKE '%@googlemail.com'
+ THEN regexp_replace(
+ regexp_replace(split_part(LOWER(email), '@', 1), '\+.*$', ''),
+ '\.', '', 'g'
+ ) || '@gmail.com'
+ ELSE LOWER(email)
+ END
+ """
+ )
+ )
+ return
+
+ if dialect_name in {"mysql", "mariadb"}:
+ op.execute(
+ sa.text(
+ """
+ UPDATE accounts
+ SET normalized_email = CASE
+ WHEN LOWER(email) LIKE '%@gmail.com'
+ OR LOWER(email) LIKE '%@googlemail.com'
+ THEN CONCAT(
+ REPLACE(
+ SUBSTRING_INDEX(SUBSTRING_INDEX(LOWER(email), '@', 1), '+', 1),
+ '.', ''
+ ),
+ '@gmail.com'
+ )
+ ELSE LOWER(email)
+ END
+ """
+ )
+ )
+ return
+
+ if dialect_name == "sqlite":
+ local_part = "substr(lower(email), 1, instr(lower(email), '@') - 1)"
+ local_part_without_alias = f"substr({local_part} || '+', 1, instr({local_part} || '+', '+') - 1)"
+ op.execute(
+ sa.text(
+ f"""
+ UPDATE accounts
+ SET normalized_email = CASE
+ WHEN lower(email) LIKE '%@gmail.com'
+ OR lower(email) LIKE '%@googlemail.com'
+ THEN replace({local_part_without_alias}, '.', '') || '@gmail.com'
+ ELSE lower(email)
+ END
+ """
+ )
+ )
+ return
+
+ raise RuntimeError(f"Unsupported database dialect for normalized email migration: {dialect_name}")
+
+
+def upgrade():
+ with op.batch_alter_table("accounts", schema=None) as batch_op:
+ batch_op.add_column(sa.Column("normalized_email", sa.String(length=255), nullable=True))
+
+ _backfill_normalized_emails()
+
+ with op.batch_alter_table("accounts", schema=None) as batch_op:
+ batch_op.create_index("account_normalized_email_idx", ["normalized_email"], unique=False)
+
+
+def downgrade():
+ with op.batch_alter_table("accounts", schema=None) as batch_op:
+ batch_op.drop_index("account_normalized_email_idx")
+ batch_op.drop_column("normalized_email")
diff --git a/api/models/account.py b/api/models/account.py
index 5bf4e3e641e..822b784a2fa 100644
--- a/api/models/account.py
+++ b/api/models/account.py
@@ -88,13 +88,18 @@ class AccountStatus(enum.StrEnum):
class Account(UserMixin, TypeBase):
__tablename__ = "accounts"
- __table_args__ = (sa.PrimaryKeyConstraint("id", name="account_pkey"), sa.Index("account_email_idx", "email"))
+ __table_args__ = (
+ sa.PrimaryKeyConstraint("id", name="account_pkey"),
+ sa.Index("account_email_idx", "email"),
+ sa.Index("account_normalized_email_idx", "normalized_email"),
+ )
id: Mapped[str] = mapped_column(
StringUUID, insert_default=lambda: str(uuid4()), default_factory=lambda: str(uuid4()), init=False
)
name: Mapped[str] = mapped_column(String(255))
email: Mapped[str] = mapped_column(String(255))
+ normalized_email: Mapped[str | None] = mapped_column(String(255), nullable=True, default=None)
password: Mapped[str | None] = mapped_column(String(255), default=None)
password_salt: Mapped[str | None] = mapped_column(String(255), default=None)
avatar: Mapped[str | None] = mapped_column(String(255), nullable=True, default=None)
diff --git a/api/repositories/account_repository.py b/api/repositories/account_repository.py
index 495eee1998d..1e7fb55e0d3 100644
--- a/api/repositories/account_repository.py
+++ b/api/repositories/account_repository.py
@@ -6,6 +6,7 @@ from sqlalchemy import delete, select
from sqlalchemy.orm import Session, sessionmaker
from models.account import Account, AccountIntegrate, AccountStatus, InvitationCode, InvitationCodeStatus
+from services.account_email import normalize_email
from services.account_ports import AccountRepository
from services.entities.account_entities import (
AccountCredentials,
@@ -137,6 +138,7 @@ class SQLAlchemyAccountRepository(AccountRepository):
return AccountEmailResetResult(status=AccountEmailResetStatus.EMAIL_IN_USE)
account.email = new_email
+ account.normalized_email = normalize_email(new_email)
session.execute(delete(AccountIntegrate).where(AccountIntegrate.account_id == account_id))
session.flush()
return AccountEmailResetResult(
diff --git a/api/services/account_email.py b/api/services/account_email.py
new file mode 100644
index 00000000000..58723b8ce2b
--- /dev/null
+++ b/api/services/account_email.py
@@ -0,0 +1,11 @@
+"""Account email normalization rules."""
+
+
+def normalize_email(email: str) -> str:
+ """Normalize an account email for identity comparisons."""
+ normalized_email = email.lower()
+ local_part, separator, domain = normalized_email.rpartition("@")
+ if separator and domain in {"gmail.com", "googlemail.com"}:
+ local_part = local_part.split("+", 1)[0].replace(".", "")
+ return f"{local_part}@gmail.com"
+ return normalized_email
diff --git a/api/services/account_service.py b/api/services/account_service.py
index 61ebc324f23..bd0cecc7b9e 100644
--- a/api/services/account_service.py
+++ b/api/services/account_service.py
@@ -47,6 +47,7 @@ from models.account import (
)
from models.dataset import Dataset
from models.model import App, DifySetup
+from services.account_email import normalize_email
from services.billing_service import BillingService
from services.email_code_login_challenge import (
EmailCodeLoginChallengeResult,
@@ -62,6 +63,7 @@ from services.entities.auth_entities import (
from services.errors.account import (
AccountAlreadyInTenantError,
AccountLoginError,
+ AccountNormalizedEmailAlreadyInUseError,
AccountNotLinkTenantError,
AccountPasswordError,
AccountRegisterError,
@@ -301,6 +303,18 @@ class AccountService:
).scalar_one_or_none()
return row is not None
+ @staticmethod
+ def has_account_with_normalized_email(email: str, *, session: Session) -> bool:
+ """Check the normalized identity through its indexed column."""
+ normalized_email = normalize_email(email)
+ row = session.scalar(select(Account.id).where(Account.normalized_email == normalized_email).limit(1))
+ return row is not None
+
+ @staticmethod
+ def ensure_registration_email_available(email: str, *, session: Session) -> None:
+ if AccountService.has_account_with_normalized_email(email, session=session):
+ raise AccountNormalizedEmailAlreadyInUseError("An account with an equivalent email already exists.")
+
@staticmethod
def get_account_by_id(account_id: str, *, session: Session) -> Account | None:
"""Plain ``Account`` getter — no banned check, no tenant rotation,
@@ -423,6 +437,7 @@ class AccountService:
is_setup: bool | None = False,
timezone: str | None = None,
ip_address: str | None = None,
+ check_normalized_email: bool = False,
*,
session: Session,
) -> Account:
@@ -432,6 +447,9 @@ class AccountService:
raise AccountNotFound()
+ if check_normalized_email:
+ AccountService.ensure_registration_email_available(email, session=session)
+
# A licensed seat is one Account row, deployment-wide; joining an existing
# account into another workspace does not pass through here and costs no seat.
# get_license() carries the full license payload that server-side enforcement needs;
@@ -473,6 +491,7 @@ class AccountService:
account = Account(
name=name,
email=email,
+ normalized_email=normalize_email(email),
password=password_to_set,
password_salt=salt_to_set,
interface_language=interface_language,
@@ -493,6 +512,7 @@ class AccountService:
password: str | None = None,
timezone: str | None = None,
ip_address: str | None = None,
+ check_normalized_email: bool = False,
*,
session: Session,
) -> Account:
@@ -504,6 +524,7 @@ class AccountService:
password=password,
timezone=timezone,
ip_address=ip_address,
+ check_normalized_email=check_normalized_email,
session=session,
)
@@ -551,6 +572,7 @@ class AccountService:
def update_account_email(account: Account, email: str, session: Session) -> Account:
"""Update account email"""
account.email = email
+ account.normalized_email = normalize_email(email)
account_integrate = session.scalar(
select(AccountIntegrate).where(AccountIntegrate.account_id == account.id).limit(1)
)
@@ -1899,6 +1921,7 @@ class RegisterService:
create_workspace_required: bool | None = True,
timezone: str | None = None,
ip_address: str | None = None,
+ check_normalized_email: bool = True,
*,
session: Session,
) -> Account:
@@ -1914,6 +1937,7 @@ class RegisterService:
is_setup=is_setup,
timezone=timezone,
ip_address=ip_address,
+ check_normalized_email=check_normalized_email,
session=session,
)
account.status = status or AccountStatus.ACTIVE
@@ -1991,6 +2015,7 @@ class RegisterService:
language=language,
status=AccountStatus.PENDING,
is_setup=True,
+ check_normalized_email=True,
session=session,
)
TenantService.create_tenant_member(tenant, account, session, tenant_join_role)
diff --git a/api/services/errors/account.py b/api/services/errors/account.py
index 153c3c0674d..3706f9da246 100644
--- a/api/services/errors/account.py
+++ b/api/services/errors/account.py
@@ -9,6 +9,14 @@ class AccountRegisterError(BaseServiceError):
pass
+class AccountEmailAlreadyInUseError(AccountRegisterError):
+ pass
+
+
+class AccountNormalizedEmailAlreadyInUseError(AccountEmailAlreadyInUseError):
+ pass
+
+
class EmailDomainSuspendedError(AccountRegisterError):
def __init__(self, description: str = "This email domain has been suspended."):
super().__init__(description)
diff --git a/api/tests/unit_tests/controllers/console/auth/test_email_register.py b/api/tests/unit_tests/controllers/console/auth/test_email_register.py
index 1bc5c3d5c1f..4f1bec336e5 100644
--- a/api/tests/unit_tests/controllers/console/auth/test_email_register.py
+++ b/api/tests/unit_tests/controllers/console/auth/test_email_register.py
@@ -13,11 +13,13 @@ from controllers.console.auth.email_register import (
EmailRegisterResetApi,
EmailRegisterSendEmailApi,
)
+from controllers.console.auth.error import NormalizedEmailAlreadyInUseError
from controllers.console.error import AccountInFreezeError, EmailDomainSuspendedError
from enums import DeploymentEdition
from models.account import Account
from services.entities.feature_entities import SystemFeatureModel
from services.errors.account import (
+ AccountNormalizedEmailAlreadyInUseError,
AccountRegisterError,
)
from services.errors.account import (
@@ -30,6 +32,14 @@ def _cloud_edition(config_overrides: Callable[..., None]) -> None:
config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)
+def test_normalized_email_conflict_exposes_a_distinct_error_code() -> None:
+ error = NormalizedEmailAlreadyInUseError()
+
+ assert error.code == 400
+ assert error.data is not None
+ assert error.data["code"] == "normalized_email_already_in_use"
+
+
class TestEmailRegisterSendEmailApi:
@patch("controllers.console.auth.email_register.AccountService.get_account_by_email_with_case_fallback")
@patch("controllers.console.auth.email_register.AccountService.send_email_register_email")
@@ -166,6 +176,7 @@ class TestEmailRegisterResetApi:
("service_error", "expected_error"),
[
(EmailDomainSuspendedRegistrationError(), EmailDomainSuspendedError),
+ (AccountNormalizedEmailAlreadyInUseError(), NormalizedEmailAlreadyInUseError),
(AccountRegisterError("frozen"), AccountInFreezeError),
],
)
diff --git a/api/tests/unit_tests/controllers/console/auth/test_email_register_language.py b/api/tests/unit_tests/controllers/console/auth/test_email_register_language.py
index 99d1a5d82b8..e8331bda8cc 100644
--- a/api/tests/unit_tests/controllers/console/auth/test_email_register_language.py
+++ b/api/tests/unit_tests/controllers/console/auth/test_email_register_language.py
@@ -27,6 +27,7 @@ def test_create_new_account_uses_requested_language(mock_create_account):
interface_language="zh-Hans",
timezone="Asia/Shanghai",
ip_address=None,
+ check_normalized_email=True,
session=ANY,
)
diff --git a/api/tests/unit_tests/controllers/console/auth/test_email_verification.py b/api/tests/unit_tests/controllers/console/auth/test_email_verification.py
index d2b46a290e2..75ed9f5b6af 100644
--- a/api/tests/unit_tests/controllers/console/auth/test_email_verification.py
+++ b/api/tests/unit_tests/controllers/console/auth/test_email_verification.py
@@ -676,6 +676,7 @@ class TestEmailCodeLoginApi:
interface_language="en-US",
timezone="Asia/Shanghai",
ip_address="203.0.113.10",
+ check_normalized_email=True,
session=ANY,
)
diff --git a/api/tests/unit_tests/controllers/console/auth/test_login_logout.py b/api/tests/unit_tests/controllers/console/auth/test_login_logout.py
index 4adbe99a34b..bec3305387b 100644
--- a/api/tests/unit_tests/controllers/console/auth/test_login_logout.py
+++ b/api/tests/unit_tests/controllers/console/auth/test_login_logout.py
@@ -22,6 +22,7 @@ from controllers.console.auth.error import (
AuthenticationFailedError,
EmailPasswordLoginLimitError,
InvalidEmailError,
+ NormalizedEmailAlreadyInUseError,
)
from controllers.console.auth.login import EmailCodeLoginApi, LoginApi, LogoutApi, ResetPasswordSendEmailApi
from controllers.console.error import (
@@ -37,6 +38,7 @@ from services.email_code_login_challenge import EmailCodeLoginChallengeResult, E
from services.entities.auth_entities import LoginFailureReason
from services.errors.account import (
AccountLoginError,
+ AccountNormalizedEmailAlreadyInUseError,
AccountPasswordError,
AccountRegisterError,
SeatsLimitExceededError,
@@ -329,6 +331,7 @@ class TestLoginApi:
("service_error", "expected_error"),
[
(EmailDomainSuspendedRegistrationError(), EmailDomainSuspendedError),
+ (AccountNormalizedEmailAlreadyInUseError(), NormalizedEmailAlreadyInUseError),
(AccountRegisterError("frozen"), AccountInFreezeError),
],
)
diff --git a/api/tests/unit_tests/migrations/test_normalized_email_migration.py b/api/tests/unit_tests/migrations/test_normalized_email_migration.py
new file mode 100644
index 00000000000..b40fb6d45fc
--- /dev/null
+++ b/api/tests/unit_tests/migrations/test_normalized_email_migration.py
@@ -0,0 +1,98 @@
+from __future__ import annotations
+
+import importlib.util
+from io import StringIO
+from pathlib import Path
+from types import ModuleType
+
+import pytest
+import sqlalchemy as sa
+from alembic.migration import MigrationContext
+from alembic.operations import Operations
+
+_MIGRATION_PATH = (
+ Path(__file__).resolve().parents[3]
+ / "migrations/versions/2026_08_25_1200-9b7c6d5e4f3a_add_normalized_email_to_accounts.py"
+)
+
+
+def _load_migration_module() -> ModuleType:
+ spec = importlib.util.spec_from_file_location("add_normalized_email_to_accounts", _MIGRATION_PATH)
+ if spec is None or spec.loader is None:
+ raise RuntimeError("failed to load migration module")
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+def test_upgrade_backfills_normalized_emails_without_enforcing_uniqueness() -> None:
+ engine = sa.create_engine("sqlite:///:memory:")
+ metadata = sa.MetaData()
+ sa.Table(
+ "accounts",
+ metadata,
+ sa.Column("id", sa.String(36), primary_key=True),
+ sa.Column("email", sa.String(255), nullable=False),
+ )
+ metadata.create_all(engine)
+
+ with engine.begin() as connection:
+ connection.execute(
+ sa.text("INSERT INTO accounts (id, email) VALUES (:id, :email)"),
+ [
+ {"id": "account-1", "email": "[email protected]"},
+ {"id": "account-2", "email": "[email protected]"},
+ {"id": "account-3", "email": "[email protected]"},
+ ],
+ )
+
+ module = _load_migration_module()
+ with engine.begin() as connection:
+ operations = Operations(MigrationContext.configure(connection))
+ original_op = module.__dict__["op"]
+ module.__dict__["op"] = operations
+ try:
+ module.upgrade()
+ finally:
+ module.__dict__["op"] = original_op
+
+ with engine.begin() as connection:
+ rows = connection.execute(sa.text("SELECT id, normalized_email FROM accounts ORDER BY id")).all()
+ connection.execute(
+ sa.text("INSERT INTO accounts (id, email, normalized_email) VALUES (:id, :email, :normalized_email)"),
+ {
+ "id": "account-4",
+ "email": "[email protected]",
+ "normalized_email": "[email protected]",
+ },
+ )
+
+ assert rows == [
+ ("account-1", "[email protected]"),
+ ("account-2", "[email protected]"),
+ ("account-3", "[email protected]"),
+ ]
+
+
+ ("dialect_name", "dialect_marker"),
+ [("postgresql", "regexp_replace"), ("mysql", "SUBSTRING_INDEX"), ("sqlite", "instr")],
+)
+def test_backfill_emits_dialect_specific_offline_sql(dialect_name: str, dialect_marker: str) -> None:
+ module = _load_migration_module()
+ output = StringIO()
+ migration_context = MigrationContext.configure(
+ dialect_name=dialect_name,
+ opts={"as_sql": True, "output_buffer": output},
+ )
+ operations = Operations(migration_context)
+ original_op = module.__dict__["op"]
+ module.__dict__["op"] = operations
+ try:
+ module._backfill_normalized_emails()
+ finally:
+ module.__dict__["op"] = original_op
+
+ generated_sql = output.getvalue()
+ assert "UPDATE accounts" in generated_sql
+ assert dialect_marker in generated_sql
diff --git a/api/tests/unit_tests/repositories/test_account_repository.py b/api/tests/unit_tests/repositories/test_account_repository.py
index e319e89e194..daab5e6e7c3 100644
--- a/api/tests/unit_tests/repositories/test_account_repository.py
+++ b/api/tests/unit_tests/repositories/test_account_repository.py
@@ -188,4 +188,5 @@ def test_account_repository_updates_email_and_removes_integrations_atomically(
persisted = sqlite_session.get(Account, "account-1")
assert persisted is not None
assert persisted.email == "[email protected]"
+ assert persisted.normalized_email == "[email protected]"
assert sqlite_session.get(AccountIntegrate, integration_id) is None
diff --git a/api/tests/unit_tests/services/test_account_email.py b/api/tests/unit_tests/services/test_account_email.py
new file mode 100644
index 00000000000..b01aaa8085e
--- /dev/null
+++ b/api/tests/unit_tests/services/test_account_email.py
@@ -0,0 +1,19 @@
+import pytest
+
+from services.account_email import normalize_email
+
+
+ ("email", "expected"),
+ [
+ ],
+)
+def test_normalize_email(email: str, expected: str) -> None:
+ assert normalize_email(email) == expected
diff --git a/api/tests/unit_tests/services/test_account_service.py b/api/tests/unit_tests/services/test_account_service.py
index 9b1ff18b4d9..fb0dbdf4952 100644
--- a/api/tests/unit_tests/services/test_account_service.py
+++ b/api/tests/unit_tests/services/test_account_service.py
@@ -25,6 +25,7 @@ from services.account_service import AccountService, RegisterService, TenantServ
from services.enterprise.rbac_service import MembersInRole, Paginated
from services.errors.account import (
AccountAlreadyInTenantError,
+ AccountEmailAlreadyInUseError,
AccountLoginError,
AccountPasswordError,
AccountRegisterError,
@@ -135,6 +136,27 @@ class TestAccountService:
assert result is account
+ def test_authenticate_keeps_using_the_stored_email(
+ self,
+ sqlite_session: Session,
+ mock_password_dependencies: _MockDependencies,
+ ) -> None:
+ account = Account(
+ name="Gmail User",
+ normalized_email="[email protected]",
+ password="hashed_password",
+ password_salt="salt",
+ )
+ sqlite_session.add(account)
+ sqlite_session.commit()
+
+ mock_password_dependencies["compare_password"].return_value = True
+
+ result = AccountService.authenticate("[email protected]", "password", session=sqlite_session)
+
+ assert result is account
+
def test_authenticate_account_not_found(self, sqlite_session: Session) -> None:
"""Test authentication when account does not exist."""
with pytest.raises(AccountPasswordError):
@@ -230,6 +252,7 @@ class TestAccountService:
account_id = result.id
assert result.email == "[email protected]"
+ assert result.normalized_email == "[email protected]"
assert result.name == "Test User"
assert result.interface_language == "en-US"
assert result.interface_theme == "light"
@@ -242,6 +265,7 @@ class TestAccountService:
persisted_account = assertion_session.get(Account, account_id)
assert persisted_account is not None
assert persisted_account.email == "[email protected]"
+ assert persisted_account.normalized_email == "[email protected]"
assert persisted_account.name == "Test User"
assert persisted_account.interface_language == "en-US"
assert persisted_account.interface_theme == "light"
@@ -250,6 +274,40 @@ class TestAccountService:
assert persisted_account.timezone == "America/New_York"
assert persisted_account.last_login_ip == "203.0.113.10"
+ def test_create_account_rejects_normalized_email_only_when_requested(
+ self,
+ sqlite_session: Session,
+ mock_external_service_dependencies: _MockDependencies,
+ ) -> None:
+ mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True
+ mock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False
+
+ sqlite_session.add(
+ Account(
+ name="Existing User",
+ normalized_email="[email protected]",
+ )
+ )
+ sqlite_session.commit()
+
+ with pytest.raises(AccountEmailAlreadyInUseError):
+ AccountService.create_account(
+ name="New User",
+ interface_language="en-US",
+ check_normalized_email=True,
+ session=sqlite_session,
+ )
+
+ duplicate = AccountService.create_account(
+ name="New User",
+ interface_language="en-US",
+ session=sqlite_session,
+ )
+ assert duplicate.normalized_email == "[email protected]"
+
def test_create_account_uses_explicit_timezone(
self,
sqlite_session_factory: sessionmaker[Session],
@@ -1547,6 +1605,7 @@ class TestRegisterService:
password=None,
timezone=None,
ip_address="203.0.113.10",
+ check_normalized_email=False,
session=sqlite_session,
)
mock_create_workspace.assert_called_once_with(account=mock_account, session=sqlite_session)
@@ -1664,10 +1723,35 @@ class TestRegisterService:
is_setup=False,
timezone=None,
ip_address="203.0.113.10",
+ check_normalized_email=True,
session=sqlite_session,
)
mock_create_owner_tenant.assert_called_once_with(mock_account, session=sqlite_session)
+ def test_register_rejects_existing_normalized_email(
+ self,
+ sqlite_session: Session,
+ mock_external_service_dependencies: _MockDependencies,
+ ) -> None:
+ mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True
+ sqlite_session.add(
+ Account(
+ name="Existing User",
+ normalized_email="[email protected]",
+ )
+ )
+ sqlite_session.commit()
+
+ with pytest.raises(AccountEmailAlreadyInUseError):
+ RegisterService.register(
+ name="New User",
+ language="en-US",
+ create_workspace_required=False,
+ session=sqlite_session,
+ )
+
def test_register_calls_default_workspace_join_for_enterprise_edition(
self,
sqlite_session: Session,
@@ -2027,6 +2111,7 @@ class TestRegisterService:
language="en-US",
status=AccountStatus.PENDING,
is_setup=True,
+ check_normalized_email=True,
session=sqlite_session,
)
mock_lookup.assert_called_once_with("[email protected]", session=sqlite_session)
@@ -2073,6 +2158,7 @@ class TestRegisterService:
language="en-US",
status=AccountStatus.PENDING,
is_setup=True,
+ check_normalized_email=True,
session=sqlite_session,
)
mock_lookup.assert_called_once_with(mixed_email, session=sqlite_session)