Commit ·
38bb724
1
Parent(s): 9d24174
login options added
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- backend/alembic/versions/add_email_password_auth.py +79 -0
- backend/alembic/versions/add_user_token_version.py +40 -0
- backend/alembic/versions/drop_apple_microsoft_auth.py +91 -0
- backend/app/auth.py +43 -6
- backend/app/config.py +0 -11
- backend/app/database.py +5 -0
- backend/app/models/__init__.py +2 -0
- backend/app/models/email_verification.py +71 -0
- backend/app/models/user.py +39 -12
- backend/app/routers/auth.py +416 -81
- backend/app/routers/collab_ws.py +7 -2
- backend/app/routers/mcp_transport.py +5 -0
- backend/app/services/apple_auth.py +0 -168
- backend/app/services/auth_identity.py +132 -15
- backend/app/services/email.py +117 -0
- backend/app/services/email_verification.py +226 -0
- backend/app/services/mcp_provider.py +27 -4
- backend/app/services/microsoft_auth.py +0 -172
- backend/app/services/password.py +127 -0
- backend/app/services/rate_limit.py +164 -0
- backend/app/support/identity.py +9 -0
- backend/requirements.txt +8 -1
- backend/templates/newspaper/meta.json +6 -6
- backend/tests/conftest.py +2 -0
- backend/tests/test_auth_providers.py +99 -381
- backend/tests/test_email_password_auth.py +714 -0
- backend/tests/test_token_revocation.py +275 -0
- frontend/package-lock.json +0 -22
- frontend/package.json +0 -1
- frontend/src/App.tsx +5 -0
- frontend/src/api/client.ts +57 -24
- frontend/src/api/types.ts +36 -4
- frontend/src/components/auth/AuthFlow.tsx +1173 -0
- frontend/src/components/auth/LoginModal.tsx +28 -239
- frontend/src/components/public/AppleAuthButton.tsx +0 -50
- frontend/src/components/public/MicrosoftAuthButton.tsx +0 -45
- frontend/src/components/remotion/imageBoxConfig.ts +4 -2
- frontend/src/components/remotion/newspaper/layouts/NewsHeadline.tsx +96 -18
- frontend/src/components/remotion/newspaper/layouts/NewsHeadlineV2.tsx +2 -2
- frontend/src/components/remotion/newspaper/layouts/NewsHeadlineV3.tsx +2 -2
- frontend/src/components/remotion/nightfall/layouts/SplitGlass.tsx +10 -4
- frontend/src/hooks/useEmailAuth.ts +411 -0
- frontend/src/hooks/useSocialLogin.ts +153 -114
- frontend/src/lib/appleSignIn.ts +0 -116
- frontend/src/lib/microsoftSignIn.ts +0 -93
- frontend/src/pages/AuthPage.tsx +54 -0
- frontend/src/pages/FreeTemplatesPage.tsx +2 -3
- frontend/src/pages/Landing.tsx +6 -8
- frontend/src/pages/PdfLanding.tsx +2 -4
- frontend/src/pages/Pricing.tsx +5 -7
backend/alembic/versions/add_email_password_auth.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Add built-in email/password sign-in: users.password_hash + verification codes
|
| 2 |
+
|
| 3 |
+
Our own provider alongside Google/Apple/Microsoft. Accounts stay bound to exactly
|
| 4 |
+
one provider for life (no linking), so an email account needs no id column — the
|
| 5 |
+
credential is the password hash added here, and mailbox control is proven by a
|
| 6 |
+
one-time code before the users row is created at all.
|
| 7 |
+
|
| 8 |
+
`email_verification_codes` holds pending signups (email + the hashed password the
|
| 9 |
+
user typed) and password-reset codes. Pending signups deliberately do NOT live in
|
| 10 |
+
`users`: is_active=False already means soft-deleted, and users.email is UNIQUE, so
|
| 11 |
+
an abandoned signup parked there would squat the address permanently.
|
| 12 |
+
|
| 13 |
+
Purely additive: one nullable column plus a new table, no backfill and no
|
| 14 |
+
constraint changes, so it takes no disruptive lock on `users`.
|
| 15 |
+
|
| 16 |
+
Revision ID: add_email_password_auth
|
| 17 |
+
Revises: add_microsoft_auth_provider
|
| 18 |
+
Create Date: 2026-09-15
|
| 19 |
+
|
| 20 |
+
"""
|
| 21 |
+
from alembic import op
|
| 22 |
+
import sqlalchemy as sa
|
| 23 |
+
|
| 24 |
+
revision = "add_email_password_auth"
|
| 25 |
+
down_revision = "add_microsoft_auth_provider"
|
| 26 |
+
branch_labels = None
|
| 27 |
+
depends_on = None
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def upgrade() -> None:
|
| 31 |
+
op.add_column("users", sa.Column("password_hash", sa.String(length=255), nullable=True))
|
| 32 |
+
|
| 33 |
+
op.create_table(
|
| 34 |
+
"email_verification_codes",
|
| 35 |
+
sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True),
|
| 36 |
+
sa.Column("email", sa.String(length=320), nullable=False),
|
| 37 |
+
sa.Column("purpose", sa.String(length=20), nullable=False),
|
| 38 |
+
sa.Column("code_hash", sa.String(length=64), nullable=False),
|
| 39 |
+
sa.Column("pending_password_hash", sa.String(length=255), nullable=True),
|
| 40 |
+
sa.Column("pending_name", sa.String(length=255), nullable=True),
|
| 41 |
+
sa.Column("attempts", sa.Integer(), nullable=False, server_default="0"),
|
| 42 |
+
sa.Column("expires_at", sa.DateTime(), nullable=False),
|
| 43 |
+
sa.Column("used", sa.Boolean(), nullable=False, server_default=sa.text("false")),
|
| 44 |
+
sa.Column("last_sent_at", sa.DateTime(), nullable=False, server_default=sa.func.now()),
|
| 45 |
+
sa.Column("created_at", sa.DateTime(), nullable=False, server_default=sa.func.now()),
|
| 46 |
+
)
|
| 47 |
+
op.create_index(
|
| 48 |
+
"ix_email_verification_codes_email", "email_verification_codes", ["email"]
|
| 49 |
+
)
|
| 50 |
+
# Every lookup is by (email, purpose) — codes are scoped to one purpose so a
|
| 51 |
+
# signup code can never be replayed as a password reset.
|
| 52 |
+
op.create_index(
|
| 53 |
+
"ix_email_verification_codes_email_purpose",
|
| 54 |
+
"email_verification_codes",
|
| 55 |
+
["email", "purpose"],
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def downgrade() -> None:
|
| 60 |
+
# An email/password account's ONLY credential is password_hash — there is no
|
| 61 |
+
# external identity provider to fall back on, so dropping it would lock these
|
| 62 |
+
# users out permanently. Refuse rather than silently orphan real accounts; an
|
| 63 |
+
# operator must migrate or remove them first.
|
| 64 |
+
conn = op.get_bind()
|
| 65 |
+
orphans = conn.execute(
|
| 66 |
+
sa.text("SELECT COUNT(*) FROM users WHERE auth_provider = 'email'")
|
| 67 |
+
).scalar()
|
| 68 |
+
if orphans:
|
| 69 |
+
raise RuntimeError(
|
| 70 |
+
f"Cannot downgrade: {orphans} email/password user(s) would lose their only "
|
| 71 |
+
"credential. Migrate or remove these accounts first."
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
op.drop_index(
|
| 75 |
+
"ix_email_verification_codes_email_purpose", table_name="email_verification_codes"
|
| 76 |
+
)
|
| 77 |
+
op.drop_index("ix_email_verification_codes_email", table_name="email_verification_codes")
|
| 78 |
+
op.drop_table("email_verification_codes")
|
| 79 |
+
op.drop_column("users", "password_hash")
|
backend/alembic/versions/add_user_token_version.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Add users.token_version for JWT revocation
|
| 2 |
+
|
| 3 |
+
Our access tokens are stateless, so until now nothing could invalidate one
|
| 4 |
+
before it expired: logging out only cleared the browser's copy, and changing a
|
| 5 |
+
password left any already-issued token working for the rest of its 72 hours (30
|
| 6 |
+
days for an MCP refresh token). Every token now carries the account's counter as
|
| 7 |
+
a "tv" claim, and get_current_user rejects any token whose claim no longer
|
| 8 |
+
matches — so bumping this column revokes them all at once.
|
| 9 |
+
|
| 10 |
+
Defaults to 0, which is also how a token minted before the claim existed is read,
|
| 11 |
+
so deploying this signs nobody out.
|
| 12 |
+
|
| 13 |
+
Purely additive: one NOT NULL column with a server default, no backfill.
|
| 14 |
+
|
| 15 |
+
Revision ID: add_user_token_version
|
| 16 |
+
Revises: add_email_password_auth
|
| 17 |
+
Create Date: 2026-09-15
|
| 18 |
+
|
| 19 |
+
"""
|
| 20 |
+
from alembic import op
|
| 21 |
+
import sqlalchemy as sa
|
| 22 |
+
|
| 23 |
+
revision = "add_user_token_version"
|
| 24 |
+
down_revision = "add_email_password_auth"
|
| 25 |
+
branch_labels = None
|
| 26 |
+
depends_on = None
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def upgrade() -> None:
|
| 30 |
+
op.add_column(
|
| 31 |
+
"users",
|
| 32 |
+
sa.Column("token_version", sa.Integer(), nullable=False, server_default="0"),
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def downgrade() -> None:
|
| 37 |
+
# Safe to drop: losing the column means tokens stop being checked against it,
|
| 38 |
+
# which restores the previous (weaker) behaviour rather than locking anyone
|
| 39 |
+
# out. Tokens already issued keep working until they expire.
|
| 40 |
+
op.drop_column("users", "token_version")
|
backend/alembic/versions/drop_apple_microsoft_auth.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Remove Apple and Microsoft sign-in: drop users.apple_id and users.microsoft_id
|
| 2 |
+
|
| 3 |
+
Undoes add_apple_auth_provider and add_microsoft_auth_provider. It has to be a
|
| 4 |
+
new forward revision rather than an alembic downgrade of those two: both sit
|
| 5 |
+
upstream of add_email_password_auth and add_user_token_version, so reverting
|
| 6 |
+
them would take the built-in email/password provider down with them.
|
| 7 |
+
|
| 8 |
+
google_id deliberately stays NULLABLE. add_apple_auth_provider made it nullable
|
| 9 |
+
because an Apple-only account has none, but email/password accounts have none
|
| 10 |
+
either — restoring NOT NULL here would break every account created by our own
|
| 11 |
+
provider. Nullability is now owned by add_email_password_auth's world, not by
|
| 12 |
+
Apple's.
|
| 13 |
+
|
| 14 |
+
auth_provider stays: it still distinguishes 'google' from 'email'. Only the two
|
| 15 |
+
removed providers' id columns go.
|
| 16 |
+
|
| 17 |
+
Revision ID: drop_apple_microsoft_auth
|
| 18 |
+
Revises: add_user_token_version
|
| 19 |
+
Create Date: 2026-09-16
|
| 20 |
+
|
| 21 |
+
"""
|
| 22 |
+
from alembic import op
|
| 23 |
+
import sqlalchemy as sa
|
| 24 |
+
|
| 25 |
+
revision = "drop_apple_microsoft_auth"
|
| 26 |
+
down_revision = "add_user_token_version"
|
| 27 |
+
branch_labels = None
|
| 28 |
+
depends_on = None
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _index_names(conn, table: str) -> set[str]:
|
| 32 |
+
"""Indexes actually present, so a re-run or a drifted DB doesn't hard-fail."""
|
| 33 |
+
return {ix["name"] for ix in sa.inspect(conn).get_indexes(table)}
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _column_names(conn, table: str) -> set[str]:
|
| 37 |
+
return {c["name"] for c in sa.inspect(conn).get_columns(table)}
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def upgrade() -> None:
|
| 41 |
+
conn = op.get_bind()
|
| 42 |
+
|
| 43 |
+
# An Apple/Microsoft account's ONLY credential is the id column dropped
|
| 44 |
+
# below: no password_hash, no google_id. Dropping it would strand real
|
| 45 |
+
# accounts with an auth_provider the code no longer understands, unable to
|
| 46 |
+
# sign in and unable to recover. Refuse and let an operator decide — the
|
| 47 |
+
# same guard the two original migrations' downgrades use.
|
| 48 |
+
stranded = conn.execute(
|
| 49 |
+
sa.text(
|
| 50 |
+
"SELECT COUNT(*) FROM users WHERE auth_provider IN ('apple', 'microsoft')"
|
| 51 |
+
)
|
| 52 |
+
).scalar()
|
| 53 |
+
if stranded:
|
| 54 |
+
raise RuntimeError(
|
| 55 |
+
f"Cannot drop Apple/Microsoft sign-in: {stranded} account(s) still use it "
|
| 56 |
+
"and would lose their only credential. Migrate or remove these accounts "
|
| 57 |
+
"first (e.g. move them to email/password, or soft-delete them)."
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
indexes = _index_names(conn, "users")
|
| 61 |
+
columns = _column_names(conn, "users")
|
| 62 |
+
|
| 63 |
+
if "ix_users_apple_id" in indexes:
|
| 64 |
+
op.drop_index("ix_users_apple_id", table_name="users")
|
| 65 |
+
if "apple_id" in columns:
|
| 66 |
+
op.drop_column("users", "apple_id")
|
| 67 |
+
|
| 68 |
+
if "ix_users_microsoft_id" in indexes:
|
| 69 |
+
op.drop_index("ix_users_microsoft_id", table_name="users")
|
| 70 |
+
if "microsoft_id" in columns:
|
| 71 |
+
op.drop_column("users", "microsoft_id")
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def downgrade() -> None:
|
| 75 |
+
"""Restore both columns, empty.
|
| 76 |
+
|
| 77 |
+
The ids themselves are gone — this brings back the shape, not the data, so
|
| 78 |
+
re-enabling either provider means every affected user signs in afresh.
|
| 79 |
+
"""
|
| 80 |
+
conn = op.get_bind()
|
| 81 |
+
columns = _column_names(conn, "users")
|
| 82 |
+
|
| 83 |
+
if "apple_id" not in columns:
|
| 84 |
+
op.add_column("users", sa.Column("apple_id", sa.String(length=255), nullable=True))
|
| 85 |
+
op.create_index("ix_users_apple_id", "users", ["apple_id"], unique=True)
|
| 86 |
+
|
| 87 |
+
if "microsoft_id" not in columns:
|
| 88 |
+
op.add_column(
|
| 89 |
+
"users", sa.Column("microsoft_id", sa.String(length=255), nullable=True)
|
| 90 |
+
)
|
| 91 |
+
op.create_index("ix_users_microsoft_id", "users", ["microsoft_id"], unique=True)
|
backend/app/auth.py
CHANGED
|
@@ -19,32 +19,56 @@ security = HTTPBearer()
|
|
| 19 |
REFRESH_TOKEN_EXPIRATION_DAYS = 30
|
| 20 |
|
| 21 |
|
| 22 |
-
def create_access_token(user_id: int) -> str:
|
| 23 |
-
"""Create a JWT access token for a user.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
payload = {
|
| 25 |
"sub": str(user_id),
|
| 26 |
"exp": datetime.utcnow() + timedelta(hours=settings.JWT_EXPIRATION_HOURS),
|
| 27 |
"iat": datetime.utcnow(),
|
| 28 |
"typ": "access",
|
|
|
|
| 29 |
}
|
| 30 |
return jwt.encode(payload, settings.JWT_SECRET, algorithm=settings.JWT_ALGORITHM)
|
| 31 |
|
| 32 |
|
| 33 |
-
def create_refresh_token(user_id: int) -> str:
|
| 34 |
"""Create a JWT refresh token for a user (30-day TTL).
|
| 35 |
|
| 36 |
Used by the MCP OAuth provider so claude.ai can refresh access tokens
|
| 37 |
-
without redoing the Google login.
|
|
|
|
|
|
|
| 38 |
"""
|
| 39 |
payload = {
|
| 40 |
"sub": str(user_id),
|
| 41 |
"exp": datetime.utcnow() + timedelta(days=REFRESH_TOKEN_EXPIRATION_DAYS),
|
| 42 |
"iat": datetime.utcnow(),
|
| 43 |
"typ": "refresh",
|
|
|
|
| 44 |
}
|
| 45 |
return jwt.encode(payload, settings.JWT_SECRET, algorithm=settings.JWT_ALGORITHM)
|
| 46 |
|
| 47 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
def decode_access_token(token: str) -> Optional[int]:
|
| 49 |
"""Decode and validate a JWT token. Returns user_id or None.
|
| 50 |
|
|
@@ -75,8 +99,12 @@ def get_current_user(
|
|
| 75 |
db: Session = Depends(get_db),
|
| 76 |
) -> User:
|
| 77 |
"""FastAPI dependency: extract and validate the current user from JWT."""
|
| 78 |
-
|
| 79 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
raise HTTPException(
|
| 81 |
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 82 |
detail="Invalid or expired token",
|
|
@@ -88,4 +116,13 @@ def get_current_user(
|
|
| 88 |
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 89 |
detail="User not found or inactive",
|
| 90 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
return user
|
|
|
|
| 19 |
REFRESH_TOKEN_EXPIRATION_DAYS = 30
|
| 20 |
|
| 21 |
|
| 22 |
+
def create_access_token(user_id: int, token_version: int = 0) -> str:
|
| 23 |
+
"""Create a JWT access token for a user.
|
| 24 |
+
|
| 25 |
+
``token_version`` stamps the account's current revocation counter into the
|
| 26 |
+
token; see ``token_version_is_current``. It defaults to 0 so callers that
|
| 27 |
+
only hold a user id still mint a working token for an account that has never
|
| 28 |
+
revoked anything — but any path that CAN pass the real value should, or a
|
| 29 |
+
later bump will not invalidate the token it issued.
|
| 30 |
+
"""
|
| 31 |
payload = {
|
| 32 |
"sub": str(user_id),
|
| 33 |
"exp": datetime.utcnow() + timedelta(hours=settings.JWT_EXPIRATION_HOURS),
|
| 34 |
"iat": datetime.utcnow(),
|
| 35 |
"typ": "access",
|
| 36 |
+
"tv": token_version,
|
| 37 |
}
|
| 38 |
return jwt.encode(payload, settings.JWT_SECRET, algorithm=settings.JWT_ALGORITHM)
|
| 39 |
|
| 40 |
|
| 41 |
+
def create_refresh_token(user_id: int, token_version: int = 0) -> str:
|
| 42 |
"""Create a JWT refresh token for a user (30-day TTL).
|
| 43 |
|
| 44 |
Used by the MCP OAuth provider so claude.ai can refresh access tokens
|
| 45 |
+
without redoing the Google login. Carries the same ``tv`` claim, so a
|
| 46 |
+
password reset disconnects the integration rather than leaving a 30-day
|
| 47 |
+
credential alive behind a changed password.
|
| 48 |
"""
|
| 49 |
payload = {
|
| 50 |
"sub": str(user_id),
|
| 51 |
"exp": datetime.utcnow() + timedelta(days=REFRESH_TOKEN_EXPIRATION_DAYS),
|
| 52 |
"iat": datetime.utcnow(),
|
| 53 |
"typ": "refresh",
|
| 54 |
+
"tv": token_version,
|
| 55 |
}
|
| 56 |
return jwt.encode(payload, settings.JWT_SECRET, algorithm=settings.JWT_ALGORITHM)
|
| 57 |
|
| 58 |
|
| 59 |
+
def token_version_is_current(payload: dict | None, user: "User") -> bool:
|
| 60 |
+
"""Whether a decoded token is still valid for ``user``'s revocation counter.
|
| 61 |
+
|
| 62 |
+
Tokens minted before the ``tv`` claim existed are treated as version 0, which
|
| 63 |
+
is every account's starting value — so deploying this does not sign anyone
|
| 64 |
+
out. Once an account revokes for the first time its counter moves to 1 and
|
| 65 |
+
those legacy tokens stop validating along with everything else.
|
| 66 |
+
"""
|
| 67 |
+
if payload is None:
|
| 68 |
+
return False
|
| 69 |
+
return int(payload.get("tv", 0)) == int(user.token_version or 0)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
def decode_access_token(token: str) -> Optional[int]:
|
| 73 |
"""Decode and validate a JWT token. Returns user_id or None.
|
| 74 |
|
|
|
|
| 99 |
db: Session = Depends(get_db),
|
| 100 |
) -> User:
|
| 101 |
"""FastAPI dependency: extract and validate the current user from JWT."""
|
| 102 |
+
payload = decode_token_full(credentials.credentials)
|
| 103 |
+
try:
|
| 104 |
+
user_id = int(payload["sub"]) if payload else 0
|
| 105 |
+
except (KeyError, TypeError, ValueError):
|
| 106 |
+
user_id = 0
|
| 107 |
+
if not user_id:
|
| 108 |
raise HTTPException(
|
| 109 |
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 110 |
detail="Invalid or expired token",
|
|
|
|
| 116 |
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 117 |
detail="User not found or inactive",
|
| 118 |
)
|
| 119 |
+
# Revoked: the account's counter has moved on since this token was issued.
|
| 120 |
+
# Same 401 as an expired token, because to the client it means the same
|
| 121 |
+
# thing — sign in again — and distinguishing them tells an attacker holding
|
| 122 |
+
# a stale token that the account exists and was deliberately cut off.
|
| 123 |
+
if not token_version_is_current(payload, user):
|
| 124 |
+
raise HTTPException(
|
| 125 |
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 126 |
+
detail="Invalid or expired token",
|
| 127 |
+
)
|
| 128 |
return user
|
backend/app/config.py
CHANGED
|
@@ -96,17 +96,6 @@ class Settings(BaseSettings):
|
|
| 96 |
GOOGLE_CLIENT_ID: str = ""
|
| 97 |
GOOGLE_CLIENT_SECRET: str = ""
|
| 98 |
|
| 99 |
-
# Sign in with Apple. APPLE_CLIENT_ID is the *Services ID* (e.g.
|
| 100 |
-
# "com.firebird.blog2video.web"), which is the `aud` claim of the identity
|
| 101 |
-
# token the browser hands us. We verify that token directly rather than
|
| 102 |
-
# exchanging an auth code, so no Apple private key is needed server-side.
|
| 103 |
-
APPLE_CLIENT_ID: str = ""
|
| 104 |
-
|
| 105 |
-
# Sign in with Microsoft. MICROSOFT_CLIENT_ID is the Entra ID app
|
| 106 |
-
# registration's *Application (client) ID*, matched against the ID token's
|
| 107 |
-
# `aud`. No client secret: the SPA hands us an ID token we verify directly.
|
| 108 |
-
MICROSOFT_CLIENT_ID: str = ""
|
| 109 |
-
|
| 110 |
# Stripe
|
| 111 |
STRIPE_SECRET_KEY: str = ""
|
| 112 |
STRIPE_PUBLISHABLE_KEY: str = ""
|
|
|
|
| 96 |
GOOGLE_CLIENT_ID: str = ""
|
| 97 |
GOOGLE_CLIENT_SECRET: str = ""
|
| 98 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
# Stripe
|
| 100 |
STRIPE_SECRET_KEY: str = ""
|
| 101 |
STRIPE_PUBLISHABLE_KEY: str = ""
|
backend/app/database.py
CHANGED
|
@@ -175,6 +175,10 @@ def _migrate_sqlite(eng) -> None:
|
|
| 175 |
"get_started_email_sent_at": "DATETIME",
|
| 176 |
"referrals_given": "INTEGER DEFAULT 0",
|
| 177 |
"referral_video_bonus": "INTEGER DEFAULT 0",
|
|
|
|
|
|
|
|
|
|
|
|
|
| 178 |
}
|
| 179 |
with eng.begin() as conn:
|
| 180 |
for col_name, col_def in user_migrations.items():
|
|
@@ -716,6 +720,7 @@ def init_db():
|
|
| 716 |
SupportConversation,
|
| 717 |
SupportMessage,
|
| 718 |
ProjectMember,
|
|
|
|
| 719 |
)
|
| 720 |
from app.models.subscription import seed_plans
|
| 721 |
|
|
|
|
| 175 |
"get_started_email_sent_at": "DATETIME",
|
| 176 |
"referrals_given": "INTEGER DEFAULT 0",
|
| 177 |
"referral_video_bonus": "INTEGER DEFAULT 0",
|
| 178 |
+
# Built-in email/password auth. NULL for social accounts.
|
| 179 |
+
"password_hash": "VARCHAR(255)",
|
| 180 |
+
# JWT revocation counter; see app/auth.py.
|
| 181 |
+
"token_version": "INTEGER DEFAULT 0",
|
| 182 |
}
|
| 183 |
with eng.begin() as conn:
|
| 184 |
for col_name, col_def in user_migrations.items():
|
|
|
|
| 720 |
SupportConversation,
|
| 721 |
SupportMessage,
|
| 722 |
ProjectMember,
|
| 723 |
+
EmailVerificationCode,
|
| 724 |
)
|
| 725 |
from app.models.subscription import seed_plans
|
| 726 |
|
backend/app/models/__init__.py
CHANGED
|
@@ -40,6 +40,7 @@ from app.models.support_conversation import (
|
|
| 40 |
SupportMessageRole,
|
| 41 |
)
|
| 42 |
from app.models.mcp_oauth import MCPClient, MCPAuthCode
|
|
|
|
| 43 |
|
| 44 |
__all__ = [
|
| 45 |
|
|
@@ -54,4 +55,5 @@ __all__ = [
|
|
| 54 |
"SupportConversation", "SupportMessage", "SupportMessageRole",
|
| 55 |
"SupportConversation", "SupportMessage", "SupportMessageRole",
|
| 56 |
"MCPClient", "MCPAuthCode",
|
|
|
|
| 57 |
]
|
|
|
|
| 40 |
SupportMessageRole,
|
| 41 |
)
|
| 42 |
from app.models.mcp_oauth import MCPClient, MCPAuthCode
|
| 43 |
+
from app.models.email_verification import EmailVerificationCode, VerificationPurpose
|
| 44 |
|
| 45 |
__all__ = [
|
| 46 |
|
|
|
|
| 55 |
"SupportConversation", "SupportMessage", "SupportMessageRole",
|
| 56 |
"SupportConversation", "SupportMessage", "SupportMessageRole",
|
| 57 |
"MCPClient", "MCPAuthCode",
|
| 58 |
+
"EmailVerificationCode", "VerificationPurpose",
|
| 59 |
]
|
backend/app/models/email_verification.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Short-lived email verification codes for built-in email/password auth.
|
| 2 |
+
|
| 3 |
+
Two purposes share one table:
|
| 4 |
+
|
| 5 |
+
- SIGNUP — issued by ``/api/auth/email/register/start``. Holds the password the
|
| 6 |
+
user typed, ALREADY HASHED, until the code is verified. This is why a pending
|
| 7 |
+
registration lives here and not as an inactive ``users`` row: ``is_active=False``
|
| 8 |
+
already means "soft-deleted, offer reactivation", and ``users.email`` is UNIQUE,
|
| 9 |
+
so an abandoned signup parked there would squat the address forever and would be
|
| 10 |
+
reported to other providers as a deleted account. The invariant this preserves is
|
| 11 |
+
worth stating plainly: **a row in ``users`` always means a real, verified account.**
|
| 12 |
+
- PASSWORD_RESET — issued by ``/api/auth/password/forgot/start`` against an account
|
| 13 |
+
that already exists, so it carries no pending password.
|
| 14 |
+
|
| 15 |
+
Modelled on ``MCPAuthCode`` (app/models/mcp_oauth.py): a code row with an expiry and
|
| 16 |
+
a used flag, deleted once spent.
|
| 17 |
+
"""
|
| 18 |
+
import enum
|
| 19 |
+
from datetime import datetime
|
| 20 |
+
|
| 21 |
+
from sqlalchemy import Boolean, DateTime, Index, Integer, String, func
|
| 22 |
+
from sqlalchemy.orm import Mapped, mapped_column
|
| 23 |
+
|
| 24 |
+
from app.database import Base
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class VerificationPurpose(str, enum.Enum):
|
| 28 |
+
"""What a code authorizes. Codes are scoped to one purpose so a signup code
|
| 29 |
+
can never be replayed as a password reset (or vice versa)."""
|
| 30 |
+
|
| 31 |
+
SIGNUP = "signup"
|
| 32 |
+
PASSWORD_RESET = "password_reset"
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class EmailVerificationCode(Base):
|
| 36 |
+
__tablename__ = "email_verification_codes"
|
| 37 |
+
|
| 38 |
+
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
|
| 39 |
+
# Not a foreign key: for SIGNUP no user exists yet, by design.
|
| 40 |
+
email: Mapped[str] = mapped_column(String(320), nullable=False, index=True)
|
| 41 |
+
purpose: Mapped[str] = mapped_column(String(20), nullable=False)
|
| 42 |
+
|
| 43 |
+
# sha256 hex of the 6-digit code — NOT a password hash. A 6-digit code has
|
| 44 |
+
# only 10^6 possible values, so a slow KDF would cost real CPU on every
|
| 45 |
+
# verify while an attacker holding the table brute-forces it offline
|
| 46 |
+
# regardless. The defences that actually matter are the 5-attempt burn and
|
| 47 |
+
# the 10-minute expiry below.
|
| 48 |
+
code_hash: Mapped[str] = mapped_column(String(64), nullable=False)
|
| 49 |
+
|
| 50 |
+
# SIGNUP only: what becomes User.password_hash / User.name on verification.
|
| 51 |
+
pending_password_hash: Mapped[str | None] = mapped_column(String(255), nullable=True)
|
| 52 |
+
pending_name: Mapped[str | None] = mapped_column(String(255), nullable=True)
|
| 53 |
+
|
| 54 |
+
attempts: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default="0")
|
| 55 |
+
expires_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)
|
| 56 |
+
used: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default="0")
|
| 57 |
+
# Drives the resend cooldown. Stored here rather than in the in-process rate
|
| 58 |
+
# limiter because this one must hold across workers and restarts.
|
| 59 |
+
last_sent_at: Mapped[datetime] = mapped_column(
|
| 60 |
+
DateTime, nullable=False, server_default=func.now()
|
| 61 |
+
)
|
| 62 |
+
created_at: Mapped[datetime] = mapped_column(
|
| 63 |
+
DateTime, nullable=False, server_default=func.now()
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
# Deliberately NOT unique: issuing a code deletes prior rows for the same
|
| 67 |
+
# (email, purpose) and inserts a fresh one, so at most one is live anyway.
|
| 68 |
+
# A unique constraint would turn a benign double-submit into a 500.
|
| 69 |
+
__table_args__ = (
|
| 70 |
+
Index("ix_email_verification_codes_email_purpose", "email", "purpose"),
|
| 71 |
+
)
|
backend/app/models/user.py
CHANGED
|
@@ -18,14 +18,24 @@ class AuthProvider(str, enum.Enum):
|
|
| 18 |
|
| 19 |
An account is created by exactly one provider and stays bound to it for
|
| 20 |
life — we deliberately do not link providers, so an email registered with
|
| 21 |
-
Google can never be signed into with
|
| 22 |
-
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
"""
|
| 25 |
|
| 26 |
GOOGLE = "google"
|
| 27 |
-
|
| 28 |
-
MICROSOFT = "microsoft"
|
| 29 |
|
| 30 |
@property
|
| 31 |
def label(self) -> str:
|
|
@@ -41,8 +51,7 @@ class AuthProvider(str, enum.Enum):
|
|
| 41 |
|
| 42 |
_PROVIDER_LABELS: dict[AuthProvider, str] = {
|
| 43 |
AuthProvider.GOOGLE: "Google",
|
| 44 |
-
AuthProvider.
|
| 45 |
-
AuthProvider.MICROSOFT: "Microsoft",
|
| 46 |
}
|
| 47 |
|
| 48 |
|
|
@@ -177,18 +186,36 @@ class User(Base):
|
|
| 177 |
picture: Mapped[str | None] = mapped_column(String(2048), nullable=True)
|
| 178 |
|
| 179 |
# ─── Identity ────────────────────────────────────────────────────────────
|
| 180 |
-
#
|
| 181 |
-
#
|
| 182 |
-
# by Postgres or SQLite, so any number of
|
|
|
|
| 183 |
google_id: Mapped[str | None] = mapped_column(String(255), unique=True, nullable=True, index=True)
|
| 184 |
-
apple_id: Mapped[str | None] = mapped_column(String(255), unique=True, nullable=True, index=True)
|
| 185 |
-
microsoft_id: Mapped[str | None] = mapped_column(String(255), unique=True, nullable=True, index=True)
|
| 186 |
auth_provider: Mapped[AuthProvider] = mapped_column(
|
| 187 |
AuthProviderType(),
|
| 188 |
default=AuthProvider.GOOGLE,
|
| 189 |
server_default=AuthProvider.GOOGLE.value,
|
| 190 |
nullable=False,
|
| 191 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 192 |
|
| 193 |
# Subscription
|
| 194 |
plan: Mapped[PlanTier] = mapped_column(Enum(PlanTier), default=PlanTier.FREE)
|
|
|
|
| 18 |
|
| 19 |
An account is created by exactly one provider and stays bound to it for
|
| 20 |
life — we deliberately do not link providers, so an email registered with
|
| 21 |
+
Google can never be signed into with a password (and vice versa). Stored as
|
| 22 |
+
a plain VARCHAR rather than a DB enum so adding a provider is a code change,
|
| 23 |
+
not a Postgres type migration.
|
| 24 |
+
|
| 25 |
+
EMAIL is our own built-in provider: no external identity provider, no
|
| 26 |
+
subject id — the credential is ``User.password_hash`` and mailbox control
|
| 27 |
+
is proven by a one-time code before the account is created at all. It is
|
| 28 |
+
therefore the one provider with no id column, and is deliberately absent
|
| 29 |
+
from ``_PROVIDER_ID_COLUMN`` in services/auth_identity.py.
|
| 30 |
+
|
| 31 |
+
Apple and Microsoft were removed in ``drop_apple_microsoft_auth``; that
|
| 32 |
+
migration refuses to run while any row still carries those values, so the
|
| 33 |
+
enum can safely omit them — a stray legacy row would now raise on load
|
| 34 |
+
(see AuthProviderType) rather than silently degrade to a string.
|
| 35 |
"""
|
| 36 |
|
| 37 |
GOOGLE = "google"
|
| 38 |
+
EMAIL = "email"
|
|
|
|
| 39 |
|
| 40 |
@property
|
| 41 |
def label(self) -> str:
|
|
|
|
| 51 |
|
| 52 |
_PROVIDER_LABELS: dict[AuthProvider, str] = {
|
| 53 |
AuthProvider.GOOGLE: "Google",
|
| 54 |
+
AuthProvider.EMAIL: "Email",
|
|
|
|
| 55 |
}
|
| 56 |
|
| 57 |
|
|
|
|
| 186 |
picture: Mapped[str | None] = mapped_column(String(2048), nullable=True)
|
| 187 |
|
| 188 |
# ─── Identity ────────────────────────────────────────────────────────────
|
| 189 |
+
# google_id is set iff auth_provider is GOOGLE; an EMAIL account has none
|
| 190 |
+
# (its credential is password_hash below). It keeps a UNIQUE index, and
|
| 191 |
+
# NULLs are not considered equal by Postgres or SQLite, so any number of
|
| 192 |
+
# email accounts may leave it empty.
|
| 193 |
google_id: Mapped[str | None] = mapped_column(String(255), unique=True, nullable=True, index=True)
|
|
|
|
|
|
|
| 194 |
auth_provider: Mapped[AuthProvider] = mapped_column(
|
| 195 |
AuthProviderType(),
|
| 196 |
default=AuthProvider.GOOGLE,
|
| 197 |
server_default=AuthProvider.GOOGLE.value,
|
| 198 |
nullable=False,
|
| 199 |
)
|
| 200 |
+
# Argon2id encoded hash, set only for AuthProvider.EMAIL accounts — the
|
| 201 |
+
# social providers hold the credential themselves, so this stays NULL for
|
| 202 |
+
# them and verify_password() treats NULL as "never matches". A row only
|
| 203 |
+
# ever gets one once a one-time code has proven the mailbox (see
|
| 204 |
+
# services/email_verification.py), so an unverified email never puts a
|
| 205 |
+
# credential in this table.
|
| 206 |
+
password_hash: Mapped[str | None] = mapped_column(String(255), nullable=True)
|
| 207 |
+
|
| 208 |
+
# Bumped to invalidate every JWT already issued for this account. Our tokens
|
| 209 |
+
# are stateless, so without this there is no way to revoke one before it
|
| 210 |
+
# expires: signing out only clears the browser's copy, and changing a
|
| 211 |
+
# password would leave a thief's token working for the rest of its 72 hours.
|
| 212 |
+
# Every token carries the value current at issue (the "tv" claim) and
|
| 213 |
+
# get_current_user rejects any that no longer matches. Tokens minted before
|
| 214 |
+
# this column existed have no claim and are read as 0, which is the default,
|
| 215 |
+
# so adding it logs nobody out.
|
| 216 |
+
token_version: Mapped[int] = mapped_column(
|
| 217 |
+
Integer, nullable=False, default=0, server_default="0"
|
| 218 |
+
)
|
| 219 |
|
| 220 |
# Subscription
|
| 221 |
plan: Mapped[PlanTier] = mapped_column(Enum(PlanTier), default=PlanTier.FREE)
|
backend/app/routers/auth.py
CHANGED
|
@@ -1,11 +1,19 @@
|
|
| 1 |
"""
|
| 2 |
-
|
| 3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
"""
|
| 5 |
import os
|
|
|
|
| 6 |
import shutil
|
| 7 |
-
from fastapi import APIRouter, Depends, HTTPException, Query
|
| 8 |
-
from pydantic import BaseModel
|
| 9 |
from sqlalchemy.orm import Session
|
| 10 |
from google.oauth2 import id_token
|
| 11 |
from google.auth.transport import requests as google_requests
|
|
@@ -13,18 +21,23 @@ from google.auth.transport import requests as google_requests
|
|
| 13 |
from app.config import settings
|
| 14 |
from app.database import get_db
|
| 15 |
from app.models.user import User, AuthProvider, PlanTier, PAID_TIERS, FREE_TIER_INCLUDED_VIDEOS, FREE_TIER_CUSTOM_TEMPLATES, FREE_AI_EDIT_CREDITS
|
| 16 |
-
from app.services.auth_identity import
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
)
|
| 23 |
-
from app.
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
)
|
|
|
|
| 28 |
from app.models.project import Project
|
| 29 |
from app.models.subscription import Subscription
|
| 30 |
from app.auth import create_access_token, get_current_user
|
|
@@ -42,16 +55,64 @@ class GoogleLoginRequest(BaseModel):
|
|
| 42 |
credential: str # Google ID token from frontend
|
| 43 |
|
| 44 |
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
|
|
|
|
|
|
|
| 52 |
|
| 53 |
-
|
| 54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
|
| 57 |
class AuthResponse(BaseModel):
|
|
@@ -210,7 +271,10 @@ def _finalize_login(
|
|
| 210 |
|
| 211 |
ensure_free_voices_for_user(db, user.id)
|
| 212 |
|
| 213 |
-
return AuthResponse(
|
|
|
|
|
|
|
|
|
|
| 214 |
|
| 215 |
|
| 216 |
@router.post("/google", response_model=AuthResponse)
|
|
@@ -223,7 +287,7 @@ def google_login(
|
|
| 223 |
"""
|
| 224 |
Verify Google ID token and create/login user.
|
| 225 |
Returns a JWT access token.
|
| 226 |
-
If the email belongs to an
|
| 227 |
If user was soft-deleted (is_active=False), returns 403 with account_deleted
|
| 228 |
unless reactivate=true, in which case the account is reactivated as a free user.
|
| 229 |
"""
|
|
@@ -254,85 +318,339 @@ def google_login(
|
|
| 254 |
return _finalize_login(db, user, created_new_user=created_new_user, ref_code=ref_code)
|
| 255 |
|
| 256 |
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 262 |
db: Session = Depends(get_db),
|
| 263 |
):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 264 |
"""
|
| 265 |
-
|
| 266 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 267 |
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
"""
|
| 272 |
-
|
| 273 |
-
identity = verify_apple_identity_token(body.identity_token)
|
| 274 |
-
except AppleAuthError as e:
|
| 275 |
-
raise HTTPException(status_code=401, detail=str(e))
|
| 276 |
|
| 277 |
-
|
| 278 |
-
|
|
|
|
|
|
|
| 279 |
|
| 280 |
-
|
|
|
|
|
|
|
| 281 |
|
| 282 |
-
user,
|
| 283 |
db,
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
name=apple_name or identity.email.split("@")[0],
|
| 288 |
-
picture=None, # Apple provides no profile picture
|
| 289 |
-
# Only overwrite an existing account's name when Apple actually sent one
|
| 290 |
-
# (first authorization only) — never with the email-derived fallback.
|
| 291 |
-
refresh_name=apple_name is not None,
|
| 292 |
-
reactivate=reactivate,
|
| 293 |
)
|
|
|
|
| 294 |
|
| 295 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 296 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 297 |
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 301 |
reactivate: bool = Query(False, description="Confirm reactivation of a previously deleted account"),
|
| 302 |
-
ref_code: str | None = Query(None, description="Referral code from an invite link"),
|
| 303 |
db: Session = Depends(get_db),
|
| 304 |
):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 305 |
"""
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 310 |
|
| 311 |
-
|
| 312 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 313 |
"""
|
| 314 |
-
|
| 315 |
-
identity = verify_microsoft_id_token(body.id_token)
|
| 316 |
-
except MicrosoftNoEmailError:
|
| 317 |
-
# Valid token, but the account shares no email — a fixable settings
|
| 318 |
-
# problem rather than an untrusted token, so 400 with specific copy.
|
| 319 |
-
raise HTTPException(status_code=400, detail="microsoft_no_email")
|
| 320 |
-
except MicrosoftAuthError as e:
|
| 321 |
-
raise HTTPException(status_code=401, detail=str(e))
|
| 322 |
|
| 323 |
-
|
| 324 |
-
db,
|
| 325 |
-
provider=AuthProvider.MICROSOFT,
|
| 326 |
-
provider_user_id=identity.microsoft_id,
|
| 327 |
-
email=identity.email,
|
| 328 |
-
# Unlike Apple, Microsoft sends `name` on every sign-in, so the stored
|
| 329 |
-
# name can be refreshed normally.
|
| 330 |
-
name=identity.name or identity.email.split("@")[0],
|
| 331 |
-
picture=None, # Graph photo needs a separate authenticated call
|
| 332 |
-
reactivate=reactivate,
|
| 333 |
)
|
|
|
|
| 334 |
|
| 335 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 336 |
|
| 337 |
|
| 338 |
@router.get("/me", response_model=UserOut)
|
|
@@ -349,7 +667,20 @@ def logout_cleanup(
|
|
| 349 |
"""
|
| 350 |
Handle logout. Data is NOT deleted here — the periodic cleanup task
|
| 351 |
handles deletion after 24 hours for free-tier users.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 352 |
"""
|
|
|
|
|
|
|
| 353 |
return {"detail": "Logged out"}
|
| 354 |
|
| 355 |
|
|
@@ -425,6 +756,10 @@ def delete_account(
|
|
| 425 |
if used > FREE_TIER_INCLUDED_VIDEOS:
|
| 426 |
user.videos_used_this_period = FREE_TIER_INCLUDED_VIDEOS
|
| 427 |
user.is_active = False
|
|
|
|
|
|
|
|
|
|
|
|
|
| 428 |
user.stripe_customer_id = None
|
| 429 |
user.stripe_subscription_id = None
|
| 430 |
user.plan = PlanTier.FREE
|
|
|
|
| 1 |
"""
|
| 2 |
+
Authentication router.
|
| 3 |
+
|
| 4 |
+
Social (Google): the frontend sends the provider's ID token, the backend
|
| 5 |
+
verifies it and returns a JWT.
|
| 6 |
+
|
| 7 |
+
Built-in email + password: registration proves mailbox control with a one-time
|
| 8 |
+
code BEFORE any account exists, then every later sign-in is password-only. Both
|
| 9 |
+
providers share ``_finalize_login`` and the identity rules in
|
| 10 |
+
``app.services.auth_identity``, so one-account-per-email holds across them.
|
| 11 |
"""
|
| 12 |
import os
|
| 13 |
+
import re
|
| 14 |
import shutil
|
| 15 |
+
from fastapi import APIRouter, Depends, HTTPException, Query, Request
|
| 16 |
+
from pydantic import BaseModel, Field, field_validator
|
| 17 |
from sqlalchemy.orm import Session
|
| 18 |
from google.oauth2 import id_token
|
| 19 |
from google.auth.transport import requests as google_requests
|
|
|
|
| 21 |
from app.config import settings
|
| 22 |
from app.database import get_db
|
| 23 |
from app.models.user import User, AuthProvider, PlanTier, PAID_TIERS, FREE_TIER_INCLUDED_VIDEOS, FREE_TIER_CUSTOM_TEMPLATES, FREE_AI_EDIT_CREDITS
|
| 24 |
+
from app.services.auth_identity import (
|
| 25 |
+
assert_email_available_for_password,
|
| 26 |
+
create_password_user,
|
| 27 |
+
resolve_or_create_user,
|
| 28 |
+
resolve_password_user,
|
| 29 |
+
_handle_soft_deleted,
|
| 30 |
)
|
| 31 |
+
from app.models.email_verification import EmailVerificationCode, VerificationPurpose
|
| 32 |
+
from app.services.email import email_service, EmailServiceError
|
| 33 |
+
from app.services import email_verification as verification
|
| 34 |
+
from app.services.password import (
|
| 35 |
+
hash_password,
|
| 36 |
+
needs_rehash,
|
| 37 |
+
validate_password,
|
| 38 |
+
verify_password,
|
| 39 |
)
|
| 40 |
+
from app.services import rate_limit
|
| 41 |
from app.models.project import Project
|
| 42 |
from app.models.subscription import Subscription
|
| 43 |
from app.auth import create_access_token, get_current_user
|
|
|
|
| 55 |
credential: str # Google ID token from frontend
|
| 56 |
|
| 57 |
|
| 58 |
+
# ─── Email + password request models ─────────────────────────────────────────
|
| 59 |
+
# Addresses are validated with a deliberately permissive regex rather than
|
| 60 |
+
# pydantic's EmailStr: EmailStr needs the `email-validator` package, and a
|
| 61 |
+
# missing optional dependency there is an import-time crash of the entire API.
|
| 62 |
+
# Real validation is the one-time code — an address that cannot receive mail
|
| 63 |
+
# never becomes an account, whatever its shape.
|
| 64 |
+
_EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
|
| 65 |
+
|
| 66 |
+
# Passwords are accepted at min_length=1 here and checked by validate_password()
|
| 67 |
+
# in the handler, so a too-short password returns our `password_too_short` code
|
| 68 |
+
# rather than pydantic's 422 envelope, which the frontend's error parser can't read.
|
| 69 |
+
_PasswordField = Field(min_length=1, max_length=512)
|
| 70 |
+
_CodeField = Field(min_length=6, max_length=6, pattern=r"^\d{6}$")
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class _EmailBody(BaseModel):
|
| 74 |
+
email: str = Field(min_length=3, max_length=320)
|
| 75 |
+
|
| 76 |
+
@field_validator("email")
|
| 77 |
+
@classmethod
|
| 78 |
+
def _normalize_email(cls, v: str) -> str:
|
| 79 |
+
v = v.strip().lower()
|
| 80 |
+
if not _EMAIL_RE.match(v):
|
| 81 |
+
raise ValueError("invalid_email")
|
| 82 |
+
return v
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class EmailLoginRequest(_EmailBody):
|
| 86 |
+
password: str = _PasswordField
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
class EmailRegisterStartRequest(_EmailBody):
|
| 90 |
+
password: str = _PasswordField
|
| 91 |
+
name: str | None = Field(default=None, max_length=255)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
class EmailCodeRequest(_EmailBody):
|
| 95 |
+
code: str = _CodeField
|
| 96 |
+
|
| 97 |
|
| 98 |
+
class EmailResendRequest(_EmailBody):
|
| 99 |
+
pass
|
| 100 |
|
| 101 |
+
|
| 102 |
+
class ForgotPasswordStartRequest(_EmailBody):
|
| 103 |
+
pass
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
class ForgotPasswordCompleteRequest(_EmailBody):
|
| 107 |
+
code: str = _CodeField
|
| 108 |
+
new_password: str = _PasswordField
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
class CodeSentResponse(BaseModel):
|
| 112 |
+
"""Acknowledges that a code was issued. Carries no account information."""
|
| 113 |
+
status: str = "code_sent"
|
| 114 |
+
expires_in: int = verification.CODE_TTL_SECONDS
|
| 115 |
+
resend_in: int = verification.RESEND_COOLDOWN_SECONDS
|
| 116 |
|
| 117 |
|
| 118 |
class AuthResponse(BaseModel):
|
|
|
|
| 271 |
|
| 272 |
ensure_free_voices_for_user(db, user.id)
|
| 273 |
|
| 274 |
+
return AuthResponse(
|
| 275 |
+
access_token=create_access_token(user.id, user.token_version or 0),
|
| 276 |
+
user=_serialize_user(user),
|
| 277 |
+
)
|
| 278 |
|
| 279 |
|
| 280 |
@router.post("/google", response_model=AuthResponse)
|
|
|
|
| 287 |
"""
|
| 288 |
Verify Google ID token and create/login user.
|
| 289 |
Returns a JWT access token.
|
| 290 |
+
If the email belongs to an email/password account, returns 409 wrong_auth_provider.
|
| 291 |
If user was soft-deleted (is_active=False), returns 403 with account_deleted
|
| 292 |
unless reactivate=true, in which case the account is reactivated as a free user.
|
| 293 |
"""
|
|
|
|
| 318 |
return _finalize_login(db, user, created_new_user=created_new_user, ref_code=ref_code)
|
| 319 |
|
| 320 |
|
| 321 |
+
# ─── Built-in email + password ───────────────────────────────────────────────
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
def _send_code_or_502(send, to_email: str, code: str, *, kind: str) -> None:
|
| 325 |
+
"""Deliver a one-time code, converting provider failure into 502.
|
| 326 |
+
|
| 327 |
+
The caller must have COMMITTED the code row first: if the send fails we want
|
| 328 |
+
a durable, resendable code rather than a rolled-back one, so the user can
|
| 329 |
+
simply press "Resend" instead of starting over.
|
| 330 |
+
"""
|
| 331 |
+
try:
|
| 332 |
+
send(to_email, code)
|
| 333 |
+
except EmailServiceError as e:
|
| 334 |
+
logger.error("[AUTH] Failed to send %s code to %s: %s", kind, to_email, e)
|
| 335 |
+
raise HTTPException(status_code=502, detail="email_send_failed")
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
@router.post("/email/register/start", response_model=CodeSentResponse)
|
| 339 |
+
def email_register_start(
|
| 340 |
+
body: EmailRegisterStartRequest,
|
| 341 |
+
request: Request,
|
| 342 |
db: Session = Depends(get_db),
|
| 343 |
):
|
| 344 |
+
"""Begin email/password registration by emailing a one-time code.
|
| 345 |
+
|
| 346 |
+
No account is created here. The password is hashed and parked on the code row
|
| 347 |
+
until the address is verified, so an unverified email never puts a credential
|
| 348 |
+
in the users table and never squats a unique email address.
|
| 349 |
+
|
| 350 |
+
Errors, all raised BEFORE any code is issued or sent, and in this order —
|
| 351 |
+
the address outranks the password, so someone who already has an account is
|
| 352 |
+
told so rather than being asked to fix a password they will never use:
|
| 353 |
+
409 wrong_auth_provider — the address belongs to a social account.
|
| 354 |
+
409 email_already_registered — the address is already an email/password
|
| 355 |
+
account, whether live OR soft-deleted.
|
| 356 |
+
422 password_too_short / password_too_long /
|
| 357 |
+
password_needs_uppercase / password_needs_special — policy violation,
|
| 358 |
+
raised only once the address is known to be free.
|
| 359 |
+
|
| 360 |
+
A soft-deleted account deliberately answers the SAME 409 as a live one and
|
| 361 |
+
never 403 account_deleted. Reactivation is a decision about an account you
|
| 362 |
+
are signing in to, so it belongs to the login and password-reset flows, which
|
| 363 |
+
authenticate first; offering it here would put a "Reactivate your account?"
|
| 364 |
+
prompt on a form that says "Create your account" and hand it to anyone who
|
| 365 |
+
guessed the address. Collapsing the two also stops this endpoint from
|
| 366 |
+
reporting, unauthenticated, whether a known address is deleted or live.
|
| 367 |
"""
|
| 368 |
+
rate_limit.register_limiter.check(rate_limit.client_key(request))
|
| 369 |
+
|
| 370 |
+
email = body.email
|
| 371 |
+
|
| 372 |
+
# The address is checked BEFORE the password policy, deliberately. These two
|
| 373 |
+
# orderings answer different questions, and for an address that already has
|
| 374 |
+
# an account the policy answer is noise: the user is being told to fix a
|
| 375 |
+
# password they are not going to use, on a form they should not be on. The
|
| 376 |
+
# only useful reply is "this account exists — sign in", whatever they typed.
|
| 377 |
+
existing = assert_email_available_for_password(db, email)
|
| 378 |
+
if existing is not None:
|
| 379 |
+
# Identical response for live and soft-deleted; see the docstring. The
|
| 380 |
+
# frontend routes both to the sign-in form, where a deleted account then
|
| 381 |
+
# gets the reactivation prompt once the password is proven.
|
| 382 |
+
rate_limit.register_limiter.record_failure(rate_limit.client_key(request))
|
| 383 |
+
raise HTTPException(status_code=409, detail={"code": "email_already_registered"})
|
| 384 |
+
|
| 385 |
+
# Only now does the password matter — this address is actually going to
|
| 386 |
+
# become an account.
|
| 387 |
+
validate_password(body.password)
|
| 388 |
+
|
| 389 |
+
_row, code = verification.issue_code(
|
| 390 |
+
db,
|
| 391 |
+
email=email,
|
| 392 |
+
purpose=VerificationPurpose.SIGNUP,
|
| 393 |
+
pending_password_hash=hash_password(body.password),
|
| 394 |
+
pending_name=(body.name or "").strip() or email.split("@")[0],
|
| 395 |
+
)
|
| 396 |
+
db.commit()
|
| 397 |
+
|
| 398 |
+
_send_code_or_502(
|
| 399 |
+
email_service.send_verification_code_email, email, code, kind="signup"
|
| 400 |
+
)
|
| 401 |
+
return CodeSentResponse()
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
@router.post("/email/register/verify", response_model=AuthResponse)
|
| 405 |
+
def email_register_verify(
|
| 406 |
+
body: EmailCodeRequest,
|
| 407 |
+
request: Request,
|
| 408 |
+
ref_code: str | None = Query(None, description="Referral code from an invite link"),
|
| 409 |
+
db: Session = Depends(get_db),
|
| 410 |
+
):
|
| 411 |
+
"""Verify the signup code and create the account.
|
| 412 |
|
| 413 |
+
The provider check is repeated here, not just at start: a Google signup for
|
| 414 |
+
the same address can land in the window between the two calls, and that must
|
| 415 |
+
lose to the account that already exists rather than 500 on the unique index.
|
| 416 |
"""
|
| 417 |
+
rate_limit.verify_limiter.check(rate_limit.client_key(request))
|
|
|
|
|
|
|
|
|
|
| 418 |
|
| 419 |
+
email = body.email
|
| 420 |
+
row = verification.consume_code(
|
| 421 |
+
db, email=email, purpose=VerificationPurpose.SIGNUP, code=body.code
|
| 422 |
+
)
|
| 423 |
|
| 424 |
+
existing = assert_email_available_for_password(db, email)
|
| 425 |
+
if existing is not None:
|
| 426 |
+
raise HTTPException(status_code=409, detail={"code": "email_already_registered"})
|
| 427 |
|
| 428 |
+
user, created = create_password_user(
|
| 429 |
db,
|
| 430 |
+
email=email,
|
| 431 |
+
name=row.pending_name or email.split("@")[0],
|
| 432 |
+
password_hash=row.pending_password_hash,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 433 |
)
|
| 434 |
+
db.delete(row)
|
| 435 |
|
| 436 |
+
rate_limit.verify_limiter.clear(rate_limit.client_key(request))
|
| 437 |
+
return _finalize_login(db, user, created_new_user=created, ref_code=ref_code)
|
| 438 |
+
|
| 439 |
+
|
| 440 |
+
@router.post("/email/register/resend", response_model=CodeSentResponse)
|
| 441 |
+
def email_register_resend(
|
| 442 |
+
body: EmailResendRequest,
|
| 443 |
+
request: Request,
|
| 444 |
+
db: Session = Depends(get_db),
|
| 445 |
+
):
|
| 446 |
+
"""Re-send the signup code, reusing the password already captured at start.
|
| 447 |
|
| 448 |
+
Returns 429 resend_too_soon (with Retry-After) inside the 60s cooldown, and
|
| 449 |
+
400 no_pending_registration when there is nothing to resend.
|
| 450 |
+
"""
|
| 451 |
+
rate_limit.resend_limiter.check(rate_limit.email_key(body.email))
|
| 452 |
+
|
| 453 |
+
email = body.email
|
| 454 |
+
pending = (
|
| 455 |
+
db.query(EmailVerificationCode)
|
| 456 |
+
.filter(
|
| 457 |
+
EmailVerificationCode.email == email,
|
| 458 |
+
EmailVerificationCode.purpose == VerificationPurpose.SIGNUP.value,
|
| 459 |
+
EmailVerificationCode.used.is_(False),
|
| 460 |
+
)
|
| 461 |
+
.order_by(EmailVerificationCode.created_at.desc(), EmailVerificationCode.id.desc())
|
| 462 |
+
.first()
|
| 463 |
+
)
|
| 464 |
+
if pending is None:
|
| 465 |
+
rate_limit.resend_limiter.record_failure(rate_limit.email_key(body.email))
|
| 466 |
+
raise HTTPException(status_code=400, detail="no_pending_registration")
|
| 467 |
|
| 468 |
+
# Never re-ask for the password: reuse what start() hashed.
|
| 469 |
+
_row, code = verification.issue_code(
|
| 470 |
+
db,
|
| 471 |
+
email=email,
|
| 472 |
+
purpose=VerificationPurpose.SIGNUP,
|
| 473 |
+
pending_password_hash=pending.pending_password_hash,
|
| 474 |
+
pending_name=pending.pending_name,
|
| 475 |
+
)
|
| 476 |
+
db.commit()
|
| 477 |
+
|
| 478 |
+
_send_code_or_502(
|
| 479 |
+
email_service.send_verification_code_email, email, code, kind="signup"
|
| 480 |
+
)
|
| 481 |
+
return CodeSentResponse()
|
| 482 |
+
|
| 483 |
+
|
| 484 |
+
@router.post("/email/login", response_model=AuthResponse)
|
| 485 |
+
def email_login(
|
| 486 |
+
body: EmailLoginRequest,
|
| 487 |
+
request: Request,
|
| 488 |
reactivate: bool = Query(False, description="Confirm reactivation of a previously deleted account"),
|
|
|
|
| 489 |
db: Session = Depends(get_db),
|
| 490 |
):
|
| 491 |
+
"""Sign in with email and password. No code is sent — verification happened at signup.
|
| 492 |
+
|
| 493 |
+
Ordering is deliberate and load-bearing:
|
| 494 |
+
1. resolve_password_user -> 409 wrong_auth_provider / 401 invalid_credentials
|
| 495 |
+
2. verify_password -> 401 invalid_credentials
|
| 496 |
+
3. only THEN reactivation
|
| 497 |
+
Checking the password before step 3 is what stops a wrong password plus
|
| 498 |
+
?reactivate=true from resurrecting a soft-deleted account on a failed login.
|
| 499 |
"""
|
| 500 |
+
ip_key = rate_limit.client_key(request)
|
| 501 |
+
mail_key = rate_limit.email_key(body.email)
|
| 502 |
+
rate_limit.login_ip_limiter.check(ip_key)
|
| 503 |
+
rate_limit.login_email_limiter.check(mail_key)
|
| 504 |
+
|
| 505 |
+
def _reject() -> HTTPException:
|
| 506 |
+
rate_limit.login_ip_limiter.record_failure(ip_key)
|
| 507 |
+
rate_limit.login_email_limiter.record_failure(mail_key)
|
| 508 |
+
return HTTPException(status_code=401, detail="invalid_credentials")
|
| 509 |
+
|
| 510 |
+
# A 409 here is a correct answer for a legitimate user, so it must not count
|
| 511 |
+
# as a failed attempt — otherwise someone who forgot they used Google gets
|
| 512 |
+
# locked out for 15 minutes for asking.
|
| 513 |
+
user = resolve_password_user(db, email=body.email)
|
| 514 |
+
|
| 515 |
+
if not verify_password(body.password, user.password_hash):
|
| 516 |
+
raise _reject()
|
| 517 |
+
|
| 518 |
+
if not user.is_active:
|
| 519 |
+
# Password is already proven; safe to run the reactivation gate, which
|
| 520 |
+
# raises 403 account_deleted unless the client confirmed.
|
| 521 |
+
_handle_soft_deleted(user, reactivate=reactivate, allow_reactivation=True)
|
| 522 |
+
|
| 523 |
+
# Opportunistically migrate hashes to current Argon2 parameters while we
|
| 524 |
+
# hold the plaintext. _finalize_login commits.
|
| 525 |
+
if needs_rehash(user.password_hash):
|
| 526 |
+
user.password_hash = hash_password(body.password)
|
| 527 |
+
|
| 528 |
+
rate_limit.login_ip_limiter.clear(ip_key)
|
| 529 |
+
rate_limit.login_email_limiter.clear(mail_key)
|
| 530 |
+
# ref_code is inert on login (no new user), passed as None to say so.
|
| 531 |
+
return _finalize_login(db, user, created_new_user=False, ref_code=None)
|
| 532 |
+
|
| 533 |
+
|
| 534 |
+
@router.post("/password/forgot/start", response_model=CodeSentResponse)
|
| 535 |
+
def forgot_password_start(
|
| 536 |
+
body: ForgotPasswordStartRequest,
|
| 537 |
+
request: Request,
|
| 538 |
+
reactivate: bool = Query(False, description="Confirm reactivation of a previously deleted account"),
|
| 539 |
+
db: Session = Depends(get_db),
|
| 540 |
+
):
|
| 541 |
+
"""Email a password-reset code.
|
| 542 |
+
|
| 543 |
+
Enumeration behaviour differs from registration on purpose. A social-owned
|
| 544 |
+
address still returns 409 naming the provider, because the user needs to know
|
| 545 |
+
there is no password to reset. But an address with NO account returns a
|
| 546 |
+
normal 200 and sends nothing: there is no recovery path to offer, so naming
|
| 547 |
+
it would turn this into a bulk address-harvesting endpoint for free.
|
| 548 |
+
|
| 549 |
+
A soft-deleted account returns 403 account_deleted, and ``?reactivate=true``
|
| 550 |
+
is the confirmation that revives it. This is the ONLY recovery path for
|
| 551 |
+
someone who deleted their account and has also forgotten the password — the
|
| 552 |
+
login route needs the old password, which by definition they don't have.
|
| 553 |
+
|
| 554 |
+
Reactivation here deliberately issues no token: it restores the account and
|
| 555 |
+
then emails the reset code exactly as for a live account, so the user still
|
| 556 |
+
has to prove mailbox control and set a new password before
|
| 557 |
+
``forgot/complete`` signs them in. Reviving on an unauthenticated request is
|
| 558 |
+
safe precisely because it grants no access — the mailbox, not this call, is
|
| 559 |
+
what unlocks the account.
|
| 560 |
+
"""
|
| 561 |
+
rate_limit.forgot_ip_limiter.check(rate_limit.client_key(request))
|
| 562 |
+
rate_limit.forgot_email_limiter.check(rate_limit.email_key(body.email))
|
| 563 |
+
|
| 564 |
+
email = body.email
|
| 565 |
+
user = assert_email_available_for_password(db, email)
|
| 566 |
+
|
| 567 |
+
if user is None:
|
| 568 |
+
rate_limit.forgot_ip_limiter.record_failure(rate_limit.client_key(request))
|
| 569 |
+
return CodeSentResponse()
|
| 570 |
+
|
| 571 |
+
if not user.is_active:
|
| 572 |
+
# Raises 403 account_deleted unless the client confirmed; on confirm it
|
| 573 |
+
# restores the row in the session, committed below alongside the code.
|
| 574 |
+
_handle_soft_deleted(user, reactivate=reactivate, allow_reactivation=True)
|
| 575 |
+
logger.info("[AUTH] Reactivated account %s via password reset", user.id)
|
| 576 |
+
|
| 577 |
+
_row, code = verification.issue_code(
|
| 578 |
+
db, email=email, purpose=VerificationPurpose.PASSWORD_RESET
|
| 579 |
+
)
|
| 580 |
+
db.commit()
|
| 581 |
+
|
| 582 |
+
_send_code_or_502(
|
| 583 |
+
email_service.send_password_reset_code_email, email, code, kind="password reset"
|
| 584 |
+
)
|
| 585 |
+
return CodeSentResponse()
|
| 586 |
+
|
| 587 |
|
| 588 |
+
@router.post("/password/forgot/check")
|
| 589 |
+
def forgot_password_check(
|
| 590 |
+
body: EmailCodeRequest,
|
| 591 |
+
request: Request,
|
| 592 |
+
db: Session = Depends(get_db),
|
| 593 |
+
):
|
| 594 |
+
"""Validate a reset code without spending it.
|
| 595 |
+
|
| 596 |
+
Lets the UI reject a wrong code at the "enter your code" step instead of
|
| 597 |
+
walking the user to the new-password screen and only failing on submit. The
|
| 598 |
+
code is NOT consumed here — forgot/complete still does that, because it is
|
| 599 |
+
what authorizes the actual password change.
|
| 600 |
+
|
| 601 |
+
Same error codes as forgot/complete's consume step, including the shared
|
| 602 |
+
attempt counter, so this cannot be used to brute-force the code for free.
|
| 603 |
"""
|
| 604 |
+
rate_limit.verify_limiter.check(rate_limit.client_key(request))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 605 |
|
| 606 |
+
verification.check_code(
|
| 607 |
+
db, email=body.email, purpose=VerificationPurpose.PASSWORD_RESET, code=body.code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 608 |
)
|
| 609 |
+
return {"status": "code_valid"}
|
| 610 |
|
| 611 |
+
|
| 612 |
+
@router.post("/password/forgot/complete", response_model=AuthResponse)
|
| 613 |
+
def forgot_password_complete(
|
| 614 |
+
body: ForgotPasswordCompleteRequest,
|
| 615 |
+
request: Request,
|
| 616 |
+
db: Session = Depends(get_db),
|
| 617 |
+
):
|
| 618 |
+
"""Verify the reset code, set the new password, and sign the user in.
|
| 619 |
+
|
| 620 |
+
The code is consumed here and nowhere earlier — verifying it in a separate
|
| 621 |
+
round trip would spend it and leave nothing to authorize the actual change.
|
| 622 |
+
"""
|
| 623 |
+
rate_limit.verify_limiter.check(rate_limit.client_key(request))
|
| 624 |
+
|
| 625 |
+
email = body.email
|
| 626 |
+
validate_password(body.new_password)
|
| 627 |
+
|
| 628 |
+
verification.consume_code(
|
| 629 |
+
db, email=email, purpose=VerificationPurpose.PASSWORD_RESET, code=body.code
|
| 630 |
+
)
|
| 631 |
+
|
| 632 |
+
user = resolve_password_user(db, email=email)
|
| 633 |
+
if not user.is_active:
|
| 634 |
+
raise HTTPException(
|
| 635 |
+
status_code=403,
|
| 636 |
+
detail="account_deleted",
|
| 637 |
+
headers={"X-Account-Deleted": "true"},
|
| 638 |
+
)
|
| 639 |
+
|
| 640 |
+
user.password_hash = hash_password(body.new_password)
|
| 641 |
+
# Revoke every token issued under the OLD password. This is the point of a
|
| 642 |
+
# password reset when the account is already compromised: without it the
|
| 643 |
+
# attacker's session survives the reset that was meant to evict them, for up
|
| 644 |
+
# to 72 hours (30 days for an MCP refresh token). _finalize_login below reads
|
| 645 |
+
# the bumped value, so the user's own new token is minted against it and they
|
| 646 |
+
# stay signed in on this device.
|
| 647 |
+
user.token_version = (user.token_version or 0) + 1
|
| 648 |
+
# Drop every code for this address, both purposes: an in-flight signup code
|
| 649 |
+
# must not stay replayable now that the credential has changed.
|
| 650 |
+
verification.clear_codes(db, email=email)
|
| 651 |
+
|
| 652 |
+
rate_limit.login_email_limiter.clear(rate_limit.email_key(email))
|
| 653 |
+
return _finalize_login(db, user, created_new_user=False, ref_code=None)
|
| 654 |
|
| 655 |
|
| 656 |
@router.get("/me", response_model=UserOut)
|
|
|
|
| 667 |
"""
|
| 668 |
Handle logout. Data is NOT deleted here — the periodic cleanup task
|
| 669 |
handles deletion after 24 hours for free-tier users.
|
| 670 |
+
|
| 671 |
+
Bumps token_version so the JWT just used stops working immediately. Our
|
| 672 |
+
tokens are stateless, so without this signing out would only clear the
|
| 673 |
+
browser's copy and leave the credential valid for the rest of its 72 hours —
|
| 674 |
+
which matters most on a shared or public machine, exactly where people press
|
| 675 |
+
"log out" deliberately.
|
| 676 |
+
|
| 677 |
+
Note this signs the account out everywhere, not just this browser: with one
|
| 678 |
+
counter per user there is no way to revoke a single token. That is the
|
| 679 |
+
conservative direction for a security control, and it is what "log out"
|
| 680 |
+
already implies to most people.
|
| 681 |
"""
|
| 682 |
+
user.token_version = (user.token_version or 0) + 1
|
| 683 |
+
db.commit()
|
| 684 |
return {"detail": "Logged out"}
|
| 685 |
|
| 686 |
|
|
|
|
| 756 |
if used > FREE_TIER_INCLUDED_VIDEOS:
|
| 757 |
user.videos_used_this_period = FREE_TIER_INCLUDED_VIDEOS
|
| 758 |
user.is_active = False
|
| 759 |
+
# NOTE: password_hash is deliberately NOT cleared here. For an email
|
| 760 |
+
# account it is the only credential, and reactivation authenticates with
|
| 761 |
+
# it (POST /email/login?reactivate=true) — clearing it would make a
|
| 762 |
+
# deleted email account uniquely unrecoverable, unlike every social one.
|
| 763 |
user.stripe_customer_id = None
|
| 764 |
user.stripe_subscription_id = None
|
| 765 |
user.plan = PlanTier.FREE
|
backend/app/routers/collab_ws.py
CHANGED
|
@@ -24,7 +24,7 @@ from fastapi import APIRouter, WebSocket, WebSocketDisconnect, Query
|
|
| 24 |
from starlette.websockets import WebSocketState
|
| 25 |
|
| 26 |
from app.database import SessionLocal
|
| 27 |
-
from app.auth import
|
| 28 |
from app.models.user import User
|
| 29 |
from app.models.project import Project
|
| 30 |
from app.services.access import get_member
|
|
@@ -214,7 +214,8 @@ def _authenticate(token: Optional[str], db) -> Optional[User]:
|
|
| 214 |
if not token:
|
| 215 |
return None
|
| 216 |
try:
|
| 217 |
-
|
|
|
|
| 218 |
except Exception:
|
| 219 |
return None
|
| 220 |
if not user_id:
|
|
@@ -222,6 +223,10 @@ def _authenticate(token: Optional[str], db) -> Optional[User]:
|
|
| 222 |
user = db.query(User).filter(User.id == user_id).first()
|
| 223 |
if not user or not user.is_active:
|
| 224 |
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
| 225 |
return user
|
| 226 |
|
| 227 |
|
|
|
|
| 24 |
from starlette.websockets import WebSocketState
|
| 25 |
|
| 26 |
from app.database import SessionLocal
|
| 27 |
+
from app.auth import decode_token_full, token_version_is_current
|
| 28 |
from app.models.user import User
|
| 29 |
from app.models.project import Project
|
| 30 |
from app.services.access import get_member
|
|
|
|
| 214 |
if not token:
|
| 215 |
return None
|
| 216 |
try:
|
| 217 |
+
payload = decode_token_full(token)
|
| 218 |
+
user_id = int(payload["sub"]) if payload else 0
|
| 219 |
except Exception:
|
| 220 |
return None
|
| 221 |
if not user_id:
|
|
|
|
| 223 |
user = db.query(User).filter(User.id == user_id).first()
|
| 224 |
if not user or not user.is_active:
|
| 225 |
return None
|
| 226 |
+
# Mirror get_current_user: a revoked token must not open a socket either,
|
| 227 |
+
# or logging out would leave a live collaboration session behind.
|
| 228 |
+
if not token_version_is_current(payload, user):
|
| 229 |
+
return None
|
| 230 |
return user
|
| 231 |
|
| 232 |
|
backend/app/routers/mcp_transport.py
CHANGED
|
@@ -574,6 +574,11 @@ async def _mcp_endpoint(request) -> None:
|
|
| 574 |
"""
|
| 575 |
method = request.scope.get("method", "GET")
|
| 576 |
token = _extract_token_from_scope(request.scope)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 577 |
user_id = decode_access_token(token) if token else None
|
| 578 |
if user_id is None:
|
| 579 |
from starlette.responses import JSONResponse
|
|
|
|
| 574 |
"""
|
| 575 |
method = request.scope.get("method", "GET")
|
| 576 |
token = _extract_token_from_scope(request.scope)
|
| 577 |
+
# A cheap signature/expiry pre-filter, not the authorization boundary: this
|
| 578 |
+
# layer has no DB session, and the tool handlers below call back into this
|
| 579 |
+
# same API over HTTP with the very same JWT, where get_current_user enforces
|
| 580 |
+
# the account's token_version. A revoked token therefore gets past this line
|
| 581 |
+
# and is then refused by every call it tries to make.
|
| 582 |
user_id = decode_access_token(token) if token else None
|
| 583 |
if user_id is None:
|
| 584 |
from starlette.responses import JSONResponse
|
backend/app/services/apple_auth.py
DELETED
|
@@ -1,168 +0,0 @@
|
|
| 1 |
-
"""Verify "Sign in with Apple" identity tokens.
|
| 2 |
-
|
| 3 |
-
Apple ships no server-side helper equivalent to Google's
|
| 4 |
-
``id_token.verify_oauth2_token``, so we do it by hand: fetch Apple's public
|
| 5 |
-
JWKS, pick the key named by the token header's ``kid``, and verify the RS256
|
| 6 |
-
signature plus the issuer/audience/expiry claims.
|
| 7 |
-
|
| 8 |
-
We verify the *identity token* the browser receives, rather than exchanging an
|
| 9 |
-
authorization code. That mirrors how the Google path works here and means no
|
| 10 |
-
Apple private key (and no client secret JWT) has to live in the deployment.
|
| 11 |
-
"""
|
| 12 |
-
from __future__ import annotations
|
| 13 |
-
|
| 14 |
-
import threading
|
| 15 |
-
import time
|
| 16 |
-
from dataclasses import dataclass
|
| 17 |
-
|
| 18 |
-
import jwt
|
| 19 |
-
import requests
|
| 20 |
-
from jwt import PyJWKSet
|
| 21 |
-
|
| 22 |
-
from app.config import settings
|
| 23 |
-
from app.observability.logging import get_logger
|
| 24 |
-
|
| 25 |
-
logger = get_logger(__name__)
|
| 26 |
-
|
| 27 |
-
APPLE_ISSUER = "https://appleid.apple.com"
|
| 28 |
-
APPLE_JWKS_URL = "https://appleid.apple.com/auth/keys"
|
| 29 |
-
|
| 30 |
-
# Apple's relay addresses for "Hide My Email". Such an address is a distinct
|
| 31 |
-
# mailbox from the user's real one, so accepting it would create a second
|
| 32 |
-
# account for the same human — which defeats our one-account-per-email rule.
|
| 33 |
-
APPLE_PRIVATE_RELAY_DOMAIN = "@privaterelay.appleid.com"
|
| 34 |
-
|
| 35 |
-
# Apple rotates signing keys, so the fetched set is cached only briefly.
|
| 36 |
-
_JWKS_TTL_SECONDS = 6 * 60 * 60
|
| 37 |
-
|
| 38 |
-
_jwks_lock = threading.Lock()
|
| 39 |
-
_jwks_cache: PyJWKSet | None = None
|
| 40 |
-
_jwks_fetched_at: float = 0.0
|
| 41 |
-
|
| 42 |
-
# Fetched with `requests` rather than PyJWKClient: PyJWKClient uses urllib,
|
| 43 |
-
# which relies on the host's OpenSSL CA store and fails with
|
| 44 |
-
# CERTIFICATE_VERIFY_FAILED wherever that store isn't populated (macOS with a
|
| 45 |
-
# python.org build, slim containers). `requests` ships certifi, so this works
|
| 46 |
-
# the same everywhere.
|
| 47 |
-
_JWKS_TIMEOUT_SECONDS = 10
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
class AppleAuthError(ValueError):
|
| 51 |
-
"""Raised when an Apple identity token cannot be trusted."""
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
@dataclass(frozen=True)
|
| 55 |
-
class AppleIdentity:
|
| 56 |
-
"""The claims we care about from a verified Apple identity token."""
|
| 57 |
-
|
| 58 |
-
apple_id: str # stable per-user id ("sub"); never reused
|
| 59 |
-
email: str
|
| 60 |
-
email_verified: bool
|
| 61 |
-
is_private_email: bool
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
def _get_jwks(force_refresh: bool = False) -> PyJWKSet:
|
| 65 |
-
"""Return Apple's signing-key set, refetching when stale or on demand."""
|
| 66 |
-
global _jwks_cache, _jwks_fetched_at
|
| 67 |
-
with _jwks_lock:
|
| 68 |
-
expired = (time.time() - _jwks_fetched_at) > _JWKS_TTL_SECONDS
|
| 69 |
-
if _jwks_cache is None or expired or force_refresh:
|
| 70 |
-
resp = requests.get(APPLE_JWKS_URL, timeout=_JWKS_TIMEOUT_SECONDS)
|
| 71 |
-
resp.raise_for_status()
|
| 72 |
-
_jwks_cache = PyJWKSet.from_dict(resp.json())
|
| 73 |
-
_jwks_fetched_at = time.time()
|
| 74 |
-
return _jwks_cache
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
def _signing_key_for(identity_token: str, force_refresh: bool = False):
|
| 78 |
-
"""Select the JWK named by the token header's ``kid``."""
|
| 79 |
-
kid = jwt.get_unverified_header(identity_token).get("kid")
|
| 80 |
-
if not kid:
|
| 81 |
-
raise AppleAuthError("Apple token header has no key id")
|
| 82 |
-
for key in _get_jwks(force_refresh).keys:
|
| 83 |
-
if key.key_id == kid:
|
| 84 |
-
return key
|
| 85 |
-
raise KeyError(f"no Apple signing key for kid {kid!r}")
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
def _claim_is_true(value: object) -> bool:
|
| 89 |
-
"""Apple sends these booleans as either real bools or the strings "true"/"false"."""
|
| 90 |
-
return value is True or value == "true"
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
def verify_apple_identity_token(identity_token: str) -> AppleIdentity:
|
| 94 |
-
"""Verify an Apple identity token and return its identity claims.
|
| 95 |
-
|
| 96 |
-
Raises AppleAuthError on any failure — an unfetchable JWKS, an unknown key,
|
| 97 |
-
a bad signature, a wrong issuer/audience, an expired token, or a missing
|
| 98 |
-
email claim. Callers map this to a 401.
|
| 99 |
-
"""
|
| 100 |
-
if not settings.APPLE_CLIENT_ID:
|
| 101 |
-
# Misconfiguration, not a bad token; surface it distinctly in the logs.
|
| 102 |
-
logger.error("[APPLE AUTH] APPLE_CLIENT_ID is not configured")
|
| 103 |
-
raise AppleAuthError("Apple sign-in is not configured")
|
| 104 |
-
|
| 105 |
-
# A key rotated in after our cache was built shows up as an unknown kid, so
|
| 106 |
-
# retry exactly once against a freshly fetched JWKS before giving up.
|
| 107 |
-
last_error: Exception | None = None
|
| 108 |
-
signing_key = None
|
| 109 |
-
for force_refresh in (False, True):
|
| 110 |
-
try:
|
| 111 |
-
signing_key = _signing_key_for(identity_token, force_refresh)
|
| 112 |
-
break
|
| 113 |
-
except (KeyError, jwt.PyJWKError, requests.RequestException, ValueError) as e:
|
| 114 |
-
last_error = e
|
| 115 |
-
if signing_key is None:
|
| 116 |
-
logger.error("[APPLE AUTH] Could not resolve Apple signing key: %s", last_error)
|
| 117 |
-
raise AppleAuthError(f"Could not verify Apple token: {last_error}")
|
| 118 |
-
|
| 119 |
-
try:
|
| 120 |
-
claims = jwt.decode(
|
| 121 |
-
identity_token,
|
| 122 |
-
signing_key.key,
|
| 123 |
-
algorithms=["RS256"],
|
| 124 |
-
audience=settings.APPLE_CLIENT_ID,
|
| 125 |
-
issuer=APPLE_ISSUER,
|
| 126 |
-
options={"require": ["exp", "iss", "aud", "sub"]},
|
| 127 |
-
)
|
| 128 |
-
except jwt.InvalidTokenError as e:
|
| 129 |
-
logger.warning("[APPLE AUTH] Identity token rejected: %s", e)
|
| 130 |
-
raise AppleAuthError(f"Invalid Apple token: {e}")
|
| 131 |
-
|
| 132 |
-
apple_id = claims.get("sub")
|
| 133 |
-
email = (claims.get("email") or "").strip().lower()
|
| 134 |
-
if not apple_id:
|
| 135 |
-
raise AppleAuthError("Apple token has no subject")
|
| 136 |
-
if not email:
|
| 137 |
-
# Happens when the user revoked email sharing; we cannot key an account.
|
| 138 |
-
raise AppleAuthError("Email not provided by Apple")
|
| 139 |
-
|
| 140 |
-
return AppleIdentity(
|
| 141 |
-
apple_id=apple_id,
|
| 142 |
-
email=email,
|
| 143 |
-
email_verified=_claim_is_true(claims.get("email_verified")),
|
| 144 |
-
is_private_email=(
|
| 145 |
-
_claim_is_true(claims.get("is_private_email"))
|
| 146 |
-
or email.endswith(APPLE_PRIVATE_RELAY_DOMAIN)
|
| 147 |
-
),
|
| 148 |
-
)
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
def full_name_from_apple_payload(payload: dict | None) -> str | None:
|
| 152 |
-
"""Build a display name from Apple's first-authorization ``user`` payload.
|
| 153 |
-
|
| 154 |
-
Apple sends the user's name exactly once — on the first authorization, in a
|
| 155 |
-
field alongside the token, never inside the token itself. The frontend
|
| 156 |
-
forwards it when present; every later sign-in has nothing here.
|
| 157 |
-
"""
|
| 158 |
-
if not isinstance(payload, dict):
|
| 159 |
-
return None
|
| 160 |
-
name = payload.get("name")
|
| 161 |
-
if not isinstance(name, dict):
|
| 162 |
-
return None
|
| 163 |
-
parts = [
|
| 164 |
-
str(name.get("firstName") or "").strip(),
|
| 165 |
-
str(name.get("lastName") or "").strip(),
|
| 166 |
-
]
|
| 167 |
-
full = " ".join(p for p in parts if p).strip()
|
| 168 |
-
return full or None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
backend/app/services/auth_identity.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
"""Resolve a verified
|
| 2 |
|
| 3 |
This is the single enforcement point for our identity rules, shared by the web
|
| 4 |
login endpoints and the MCP OAuth bridge so the two can never disagree about
|
|
@@ -10,9 +10,25 @@ which accounts may exist:
|
|
| 10 |
3. The wrong-provider error outranks the soft-delete/reactivation prompt, so a
|
| 11 |
deleted account is told which provider reactivates it.
|
| 12 |
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
``
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
"""
|
| 17 |
from __future__ import annotations
|
| 18 |
|
|
@@ -28,16 +44,20 @@ from app.models.user import (
|
|
| 28 |
User,
|
| 29 |
)
|
| 30 |
from app.observability.logging import get_logger
|
|
|
|
| 31 |
|
| 32 |
logger = get_logger(__name__)
|
| 33 |
|
| 34 |
-
# The column holding each provider's stable user id. Adding a provider is
|
| 35 |
-
# entry here plus the matching column — the resolution rules below are
|
| 36 |
# deliberately provider-agnostic.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
_PROVIDER_ID_COLUMN: dict[AuthProvider, str] = {
|
| 38 |
AuthProvider.GOOGLE: "google_id",
|
| 39 |
-
AuthProvider.APPLE: "apple_id",
|
| 40 |
-
AuthProvider.MICROSOFT: "microsoft_id",
|
| 41 |
}
|
| 42 |
|
| 43 |
|
|
@@ -81,7 +101,6 @@ def resolve_or_create_user(
|
|
| 81 |
email: str,
|
| 82 |
name: str,
|
| 83 |
picture: str | None = None,
|
| 84 |
-
refresh_name: bool = True,
|
| 85 |
reactivate: bool = False,
|
| 86 |
allow_reactivation: bool = True,
|
| 87 |
) -> tuple[User, bool]:
|
|
@@ -108,7 +127,7 @@ def resolve_or_create_user(
|
|
| 108 |
if existing:
|
| 109 |
if existing.auth_provider is not provider:
|
| 110 |
raise wrong_provider_error(existing)
|
| 111 |
-
# Same provider, new subject id.
|
| 112 |
# and never reused, so this is a re-issue rather than a new person;
|
| 113 |
# adopt the new id instead of stranding the account.
|
| 114 |
logger.info(
|
|
@@ -131,11 +150,9 @@ def resolve_or_create_user(
|
|
| 131 |
if not created and not user.is_active:
|
| 132 |
_handle_soft_deleted(user, reactivate=reactivate, allow_reactivation=allow_reactivation)
|
| 133 |
elif not created:
|
| 134 |
-
# Normal login: refresh profile fields from the provider
|
| 135 |
-
#
|
| 136 |
-
|
| 137 |
-
if refresh_name:
|
| 138 |
-
user.name = name
|
| 139 |
user.picture = picture or user.picture
|
| 140 |
|
| 141 |
return user, created
|
|
@@ -182,6 +199,106 @@ def _create_user(
|
|
| 182 |
return user, True
|
| 183 |
|
| 184 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 185 |
def _handle_soft_deleted(
|
| 186 |
user: User, *, reactivate: bool, allow_reactivation: bool
|
| 187 |
) -> None:
|
|
|
|
| 1 |
+
"""Resolve a verified identity to a Blog2Video user account.
|
| 2 |
|
| 3 |
This is the single enforcement point for our identity rules, shared by the web
|
| 4 |
login endpoints and the MCP OAuth bridge so the two can never disagree about
|
|
|
|
| 10 |
3. The wrong-provider error outranks the soft-delete/reactivation prompt, so a
|
| 11 |
deleted account is told which provider reactivates it.
|
| 12 |
|
| 13 |
+
Two entry points apply those rules to two shapes of identity:
|
| 14 |
+
|
| 15 |
+
- ``resolve_or_create_user`` — social providers, which supply an external subject
|
| 16 |
+
id. Callers pass an already-verified identity; token verification lives in the
|
| 17 |
+
provider-specific modules (google via the google-auth lib). Google is currently
|
| 18 |
+
the only one, but the path stays provider-agnostic: it is driven by
|
| 19 |
+
``_PROVIDER_ID_COLUMN``, so adding one back is an entry there plus a column.
|
| 20 |
+
- ``assert_email_available_for_password`` / ``resolve_password_user`` /
|
| 21 |
+
``create_password_user`` — our built-in email+password provider, which has no
|
| 22 |
+
external subject id at all. They share ``wrong_provider_error``,
|
| 23 |
+
``_lookup_by_email`` and ``_handle_soft_deleted`` with the social path, so
|
| 24 |
+
rules 1-3 hold identically across both.
|
| 25 |
+
|
| 26 |
+
Password auth is deliberately a parallel path rather than an extra entry in
|
| 27 |
+
``_PROVIDER_ID_COLUMN``: that map drives a lookup, a subject-id rebind and an
|
| 28 |
+
insert kwarg, all three of which are meaningless without a subject id. Mapping
|
| 29 |
+
EMAIL to None would need a guard at each site and would break the map's
|
| 30 |
+
fail-loudly property. The split has a second benefit — the MCP OAuth bridge calls
|
| 31 |
+
``resolve_or_create_user``, so password accounts structurally cannot reach it.
|
| 32 |
"""
|
| 33 |
from __future__ import annotations
|
| 34 |
|
|
|
|
| 44 |
User,
|
| 45 |
)
|
| 46 |
from app.observability.logging import get_logger
|
| 47 |
+
from app.services.password import verify_password_dummy
|
| 48 |
|
| 49 |
logger = get_logger(__name__)
|
| 50 |
|
| 51 |
+
# The column holding each provider's stable user id. Adding a SOCIAL provider is
|
| 52 |
+
# an entry here plus the matching column — the resolution rules below are
|
| 53 |
# deliberately provider-agnostic.
|
| 54 |
+
#
|
| 55 |
+
# AuthProvider.EMAIL is intentionally absent: our built-in provider has no
|
| 56 |
+
# external subject id (the credential is users.password_hash). Its absence is
|
| 57 |
+
# load-bearing — _lookup_by_provider_id raising KeyError for EMAIL is what
|
| 58 |
+
# guarantees the social path can never be entered with a password account.
|
| 59 |
_PROVIDER_ID_COLUMN: dict[AuthProvider, str] = {
|
| 60 |
AuthProvider.GOOGLE: "google_id",
|
|
|
|
|
|
|
| 61 |
}
|
| 62 |
|
| 63 |
|
|
|
|
| 101 |
email: str,
|
| 102 |
name: str,
|
| 103 |
picture: str | None = None,
|
|
|
|
| 104 |
reactivate: bool = False,
|
| 105 |
allow_reactivation: bool = True,
|
| 106 |
) -> tuple[User, bool]:
|
|
|
|
| 127 |
if existing:
|
| 128 |
if existing.auth_provider is not provider:
|
| 129 |
raise wrong_provider_error(existing)
|
| 130 |
+
# Same provider, new subject id. Google subject ids are stable
|
| 131 |
# and never reused, so this is a re-issue rather than a new person;
|
| 132 |
# adopt the new id instead of stranding the account.
|
| 133 |
logger.info(
|
|
|
|
| 150 |
if not created and not user.is_active:
|
| 151 |
_handle_soft_deleted(user, reactivate=reactivate, allow_reactivation=allow_reactivation)
|
| 152 |
elif not created:
|
| 153 |
+
# Normal login: refresh profile fields from the provider, which is
|
| 154 |
+
# authoritative for them and sends both on every sign-in.
|
| 155 |
+
user.name = name
|
|
|
|
|
|
|
| 156 |
user.picture = picture or user.picture
|
| 157 |
|
| 158 |
return user, created
|
|
|
|
| 199 |
return user, True
|
| 200 |
|
| 201 |
|
| 202 |
+
# ─── Built-in email + password provider ─────────────────────────────────────
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def assert_email_available_for_password(db: Session, email: str) -> User | None:
|
| 206 |
+
"""Gate an email address for password signup/reset. Returns the existing row, if any.
|
| 207 |
+
|
| 208 |
+
Raises 409 ``wrong_auth_provider`` when the address belongs to a social
|
| 209 |
+
account. Callers MUST run this before hashing a password, before issuing a
|
| 210 |
+
one-time code, and before sending any email — so someone whose address is
|
| 211 |
+
already a Google account is told so immediately rather than after a pointless
|
| 212 |
+
round trip through their inbox.
|
| 213 |
+
|
| 214 |
+
Enumeration, deliberately: a 409 confirms both that the address is registered
|
| 215 |
+
and which provider owns it. That is the point — the login modal turns it into
|
| 216 |
+
a one-click switch to the right provider, and the alternative is a user who
|
| 217 |
+
cannot sign in and is told nothing about why. Do not "fix" this into a
|
| 218 |
+
generic error without replacing that recovery path. Where there is no such UX
|
| 219 |
+
payoff (a forgotten password for an address with no account at all) the
|
| 220 |
+
routers stay quiet instead; see routers/auth.py.
|
| 221 |
+
|
| 222 |
+
Returns None when the address is free, or the ``User`` when it is an existing
|
| 223 |
+
EMAIL account — the caller decides what that means, since it is
|
| 224 |
+
``email_already_registered`` for signup but the normal case for a reset.
|
| 225 |
+
"""
|
| 226 |
+
existing = _lookup_by_email(db, email.strip().lower())
|
| 227 |
+
if existing is not None and existing.auth_provider is not AuthProvider.EMAIL:
|
| 228 |
+
raise wrong_provider_error(existing)
|
| 229 |
+
return existing
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def resolve_password_user(db: Session, *, email: str) -> User:
|
| 233 |
+
"""Return the EMAIL account for ``email``, or raise the login error.
|
| 234 |
+
|
| 235 |
+
Deliberately does NOT touch ``is_active``. A soft-deleted account must have
|
| 236 |
+
its password verified before ``_handle_soft_deleted`` reactivates it —
|
| 237 |
+
otherwise a wrong password plus ``?reactivate=true`` would resurrect someone
|
| 238 |
+
else's account on a request that then returns 401. The router owns that
|
| 239 |
+
ordering; see ``email_login``.
|
| 240 |
+
|
| 241 |
+
Raises:
|
| 242 |
+
409 ``wrong_auth_provider`` — the address belongs to a social provider.
|
| 243 |
+
401 ``invalid_credentials`` — no such account (body and timing identical to
|
| 244 |
+
a wrong password, so this is not an
|
| 245 |
+
account-existence oracle).
|
| 246 |
+
"""
|
| 247 |
+
user = _lookup_by_email(db, email.strip().lower())
|
| 248 |
+
if user is None:
|
| 249 |
+
# Burn a verification's worth of time so "no such account" is not
|
| 250 |
+
# measurably faster than "wrong password".
|
| 251 |
+
verify_password_dummy()
|
| 252 |
+
raise HTTPException(status_code=401, detail="invalid_credentials")
|
| 253 |
+
if user.auth_provider is not AuthProvider.EMAIL:
|
| 254 |
+
raise wrong_provider_error(user)
|
| 255 |
+
return user
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def create_password_user(
|
| 259 |
+
db: Session, *, email: str, name: str, password_hash: str
|
| 260 |
+
) -> tuple[User, bool]:
|
| 261 |
+
"""Insert a verified email/password account, tolerating a concurrent signup.
|
| 262 |
+
|
| 263 |
+
Only ever called after a one-time code has proven mailbox control, which is
|
| 264 |
+
what lets a row appear in ``users`` at all — see
|
| 265 |
+
``app/models/email_verification.py``.
|
| 266 |
+
"""
|
| 267 |
+
email = email.strip().lower()
|
| 268 |
+
user = User(
|
| 269 |
+
email=email,
|
| 270 |
+
name=name,
|
| 271 |
+
picture=None,
|
| 272 |
+
auth_provider=AuthProvider.EMAIL,
|
| 273 |
+
password_hash=password_hash,
|
| 274 |
+
plan=PlanTier.FREE,
|
| 275 |
+
videos_used_this_period=0,
|
| 276 |
+
video_limit_bonus=0,
|
| 277 |
+
is_active=True,
|
| 278 |
+
)
|
| 279 |
+
db.add(user)
|
| 280 |
+
try:
|
| 281 |
+
db.flush()
|
| 282 |
+
except IntegrityError:
|
| 283 |
+
# Two signups raced on the unique email index. Mirror _create_user: roll
|
| 284 |
+
# back and re-resolve against the row the winner committed, so the loser
|
| 285 |
+
# gets the correct 409 instead of a raw 500.
|
| 286 |
+
db.rollback()
|
| 287 |
+
logger.info("[AUTH] Concurrent password signup for %s; re-resolving", email)
|
| 288 |
+
winner = _lookup_by_email(db, email)
|
| 289 |
+
if winner is None:
|
| 290 |
+
raise
|
| 291 |
+
if winner.auth_provider is not AuthProvider.EMAIL:
|
| 292 |
+
raise wrong_provider_error(winner)
|
| 293 |
+
# Do NOT adopt the winner's row: its password hash is a different secret
|
| 294 |
+
# from the one this request just verified, so logging this caller in
|
| 295 |
+
# would hand them an account whose password they may not know.
|
| 296 |
+
raise HTTPException(
|
| 297 |
+
status_code=409, detail={"code": "email_already_registered"}
|
| 298 |
+
)
|
| 299 |
+
return user, True
|
| 300 |
+
|
| 301 |
+
|
| 302 |
def _handle_soft_deleted(
|
| 303 |
user: User, *, reactivate: bool, allow_reactivation: bool
|
| 304 |
) -> None:
|
backend/app/services/email.py
CHANGED
|
@@ -1030,6 +1030,123 @@ class EmailService:
|
|
| 1030 |
from_email=getattr(settings, "NOREPLY_EMAIL", "noreply@blog2video.app"),
|
| 1031 |
)
|
| 1032 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1033 |
def send_collab_invite_email(
|
| 1034 |
self, to_email: str, inviter_name: str, project_name: str, accept_link: str
|
| 1035 |
) -> None:
|
|
|
|
| 1030 |
from_email=getattr(settings, "NOREPLY_EMAIL", "noreply@blog2video.app"),
|
| 1031 |
)
|
| 1032 |
|
| 1033 |
+
# ─── Email/password auth codes ───────────────────────────────────────────
|
| 1034 |
+
# Both are TRANSACTIONAL: no unsubscribe link, and callers must NOT check
|
| 1035 |
+
# user.email_unsubscribed. Someone who opted out of product emails must still
|
| 1036 |
+
# be able to verify their address and reset their password — suppressing
|
| 1037 |
+
# these would lock them out of their own account.
|
| 1038 |
+
|
| 1039 |
+
def _build_code_html(self, headline: str, body_paragraph: str, code: str) -> str:
|
| 1040 |
+
"""Branded shell with the code shown large and selectable.
|
| 1041 |
+
|
| 1042 |
+
Deliberately not _build_html: that renders a CTA button, and a one-time
|
| 1043 |
+
code has nothing to link to — the user reads it and types it back.
|
| 1044 |
+
"""
|
| 1045 |
+
from app.services.email_verification import CODE_TTL_SECONDS
|
| 1046 |
+
|
| 1047 |
+
minutes = CODE_TTL_SECONDS // 60
|
| 1048 |
+
return f"""<!DOCTYPE html>
|
| 1049 |
+
<html>
|
| 1050 |
+
<head>
|
| 1051 |
+
<meta charset="UTF-8" />
|
| 1052 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
| 1053 |
+
<title>{html.escape(headline)}</title>
|
| 1054 |
+
</head>
|
| 1055 |
+
<body style="margin:0;padding:0;background:#f4f4f5;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Arial,sans-serif;">
|
| 1056 |
+
<table width="100%" cellpadding="0" cellspacing="0" style="background:#f4f4f5;padding:40px 0;">
|
| 1057 |
+
<tr>
|
| 1058 |
+
<td align="center">
|
| 1059 |
+
<table width="560" cellpadding="0" cellspacing="0"
|
| 1060 |
+
style="background:#ffffff;border-radius:8px;overflow:hidden;box-shadow:0 2px 8px rgba(0,0,0,0.08);">
|
| 1061 |
+
<tr>
|
| 1062 |
+
<td style="background:#9333EA;padding:32px 40px;text-align:center;">
|
| 1063 |
+
<span style="font-size:24px;font-weight:700;color:#ffffff;letter-spacing:-0.5px;">
|
| 1064 |
+
Blog<span style="color:#c4b5fd;">2</span>Video
|
| 1065 |
+
</span>
|
| 1066 |
+
</td>
|
| 1067 |
+
</tr>
|
| 1068 |
+
<tr>
|
| 1069 |
+
<td style="padding:40px 40px 32px;">
|
| 1070 |
+
<p style="margin:0 0 16px;font-size:18px;font-weight:600;color:#111827;">{html.escape(headline)}</p>
|
| 1071 |
+
<p style="margin:0 0 24px;font-size:15px;line-height:1.6;color:#4b5563;">{body_paragraph}</p>
|
| 1072 |
+
<div style="margin:0 0 24px;padding:20px;background:#f9fafb;border:1px solid #e5e7eb;border-radius:8px;text-align:center;">
|
| 1073 |
+
<span style="font-family:'SF Mono',Menlo,Consolas,monospace;font-size:32px;font-weight:700;letter-spacing:8px;color:#111827;">{html.escape(code)}</span>
|
| 1074 |
+
</div>
|
| 1075 |
+
<p style="margin:0;font-size:13px;line-height:1.6;color:#6b7280;">
|
| 1076 |
+
This code expires in {minutes} minutes. If you didn't request it, you can safely ignore this email.
|
| 1077 |
+
</p>
|
| 1078 |
+
</td>
|
| 1079 |
+
</tr>
|
| 1080 |
+
<tr>
|
| 1081 |
+
<td style="padding:0 40px 32px;">
|
| 1082 |
+
<p style="margin:0;font-size:13px;color:#9ca3af;">Team Blog2Video</p>
|
| 1083 |
+
</td>
|
| 1084 |
+
</tr>
|
| 1085 |
+
</table>
|
| 1086 |
+
</td>
|
| 1087 |
+
</tr>
|
| 1088 |
+
</table>
|
| 1089 |
+
</body>
|
| 1090 |
+
</html>"""
|
| 1091 |
+
|
| 1092 |
+
def send_verification_code_email(self, to_email: str, code: str) -> None:
|
| 1093 |
+
"""Signup verification code — proves the user controls this mailbox."""
|
| 1094 |
+
from app.services.email_verification import CODE_TTL_SECONDS
|
| 1095 |
+
|
| 1096 |
+
minutes = CODE_TTL_SECONDS // 60
|
| 1097 |
+
subject = f"{code} is your Blog2Video verification code"
|
| 1098 |
+
text_content = (
|
| 1099 |
+
f"Your Blog2Video verification code is {code}\n\n"
|
| 1100 |
+
f"Enter it to finish creating your account. "
|
| 1101 |
+
f"This code expires in {minutes} minutes.\n\n"
|
| 1102 |
+
f"If you didn't request it, you can safely ignore this email.\n\n"
|
| 1103 |
+
f"Team Blog2Video\n"
|
| 1104 |
+
)
|
| 1105 |
+
html_content = self._build_code_html(
|
| 1106 |
+
headline="Verify your email address",
|
| 1107 |
+
body_paragraph=(
|
| 1108 |
+
"Enter this code to finish creating your Blog2Video account."
|
| 1109 |
+
),
|
| 1110 |
+
code=code,
|
| 1111 |
+
)
|
| 1112 |
+
self.provider.send_email(
|
| 1113 |
+
to=to_email,
|
| 1114 |
+
subject=subject,
|
| 1115 |
+
html_content=html_content,
|
| 1116 |
+
text_content=text_content,
|
| 1117 |
+
from_email=getattr(settings, "NOREPLY_EMAIL", "noreply@blog2video.app"),
|
| 1118 |
+
)
|
| 1119 |
+
|
| 1120 |
+
def send_password_reset_code_email(self, to_email: str, code: str) -> None:
|
| 1121 |
+
"""Password-reset code for an existing email/password account."""
|
| 1122 |
+
from app.services.email_verification import CODE_TTL_SECONDS
|
| 1123 |
+
|
| 1124 |
+
minutes = CODE_TTL_SECONDS // 60
|
| 1125 |
+
subject = f"{code} is your Blog2Video password reset code"
|
| 1126 |
+
text_content = (
|
| 1127 |
+
f"Your Blog2Video password reset code is {code}\n\n"
|
| 1128 |
+
f"Enter it to choose a new password. "
|
| 1129 |
+
f"This code expires in {minutes} minutes.\n\n"
|
| 1130 |
+
f"If you didn't request a password reset, you can safely ignore this "
|
| 1131 |
+
f"email — your password has not changed.\n\n"
|
| 1132 |
+
f"Team Blog2Video\n"
|
| 1133 |
+
)
|
| 1134 |
+
html_content = self._build_code_html(
|
| 1135 |
+
headline="Reset your password",
|
| 1136 |
+
body_paragraph=(
|
| 1137 |
+
"Enter this code to choose a new password. If you didn't request a "
|
| 1138 |
+
"reset, your password has not changed."
|
| 1139 |
+
),
|
| 1140 |
+
code=code,
|
| 1141 |
+
)
|
| 1142 |
+
self.provider.send_email(
|
| 1143 |
+
to=to_email,
|
| 1144 |
+
subject=subject,
|
| 1145 |
+
html_content=html_content,
|
| 1146 |
+
text_content=text_content,
|
| 1147 |
+
from_email=getattr(settings, "NOREPLY_EMAIL", "noreply@blog2video.app"),
|
| 1148 |
+
)
|
| 1149 |
+
|
| 1150 |
def send_collab_invite_email(
|
| 1151 |
self, to_email: str, inviter_name: str, project_name: str, accept_link: str
|
| 1152 |
) -> None:
|
backend/app/services/email_verification.py
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Issue and consume the one-time codes that gate email/password auth.
|
| 2 |
+
|
| 3 |
+
Two rules here are deliberately stored in the database rather than in the
|
| 4 |
+
in-process rate limiter (services/rate_limit.py): the 60-second resend cooldown
|
| 5 |
+
and the 5-attempt burn. Those two MUST hold across workers and restarts — an
|
| 6 |
+
attacker who can reset a counter by waiting for a redeploy has no attempt limit
|
| 7 |
+
at all — whereas the per-IP limits are only a speed bump in front of Argon2.
|
| 8 |
+
"""
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import hashlib
|
| 12 |
+
import hmac
|
| 13 |
+
import secrets
|
| 14 |
+
from datetime import datetime, timedelta
|
| 15 |
+
|
| 16 |
+
from fastapi import HTTPException
|
| 17 |
+
from sqlalchemy.orm import Session
|
| 18 |
+
|
| 19 |
+
from app.models.email_verification import EmailVerificationCode, VerificationPurpose
|
| 20 |
+
from app.observability.logging import get_logger
|
| 21 |
+
|
| 22 |
+
logger = get_logger(__name__)
|
| 23 |
+
|
| 24 |
+
CODE_LENGTH = 6
|
| 25 |
+
CODE_TTL_SECONDS = 10 * 60
|
| 26 |
+
MAX_CODE_ATTEMPTS = 5
|
| 27 |
+
RESEND_COOLDOWN_SECONDS = 60
|
| 28 |
+
|
| 29 |
+
# Rows older than this are dead weight; swept opportunistically on issue.
|
| 30 |
+
_PURGE_AFTER = timedelta(days=1)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def generate_code() -> str:
|
| 34 |
+
"""A cryptographically random 6-digit code, zero-padded.
|
| 35 |
+
|
| 36 |
+
``secrets``, not ``random`` — the latter's Mersenne Twister state is
|
| 37 |
+
recoverable from observed output. Returned as a STRING and kept one all the
|
| 38 |
+
way to the client: ``039123`` is a valid code and an int would eat the zero.
|
| 39 |
+
"""
|
| 40 |
+
return f"{secrets.randbelow(10 ** CODE_LENGTH):0{CODE_LENGTH}d}"
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def hash_code(code: str) -> str:
|
| 44 |
+
"""sha256 hex of a code. See the model docstring for why this isn't a KDF."""
|
| 45 |
+
return hashlib.sha256(code.encode("utf-8")).hexdigest()
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _active_code(
|
| 49 |
+
db: Session, email: str, purpose: VerificationPurpose
|
| 50 |
+
) -> EmailVerificationCode | None:
|
| 51 |
+
"""The newest unused code for this (email, purpose), if any."""
|
| 52 |
+
return (
|
| 53 |
+
db.query(EmailVerificationCode)
|
| 54 |
+
.filter(
|
| 55 |
+
EmailVerificationCode.email == email,
|
| 56 |
+
EmailVerificationCode.purpose == purpose.value,
|
| 57 |
+
EmailVerificationCode.used.is_(False),
|
| 58 |
+
)
|
| 59 |
+
.order_by(EmailVerificationCode.created_at.desc(), EmailVerificationCode.id.desc())
|
| 60 |
+
.first()
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def purge_expired(db: Session) -> int:
|
| 65 |
+
"""Delete long-dead code rows. Cheap and indexed; called on issue."""
|
| 66 |
+
cutoff = datetime.utcnow() - _PURGE_AFTER
|
| 67 |
+
deleted = (
|
| 68 |
+
db.query(EmailVerificationCode)
|
| 69 |
+
.filter(EmailVerificationCode.expires_at < cutoff)
|
| 70 |
+
.delete(synchronize_session=False)
|
| 71 |
+
)
|
| 72 |
+
return deleted or 0
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def issue_code(
|
| 76 |
+
db: Session,
|
| 77 |
+
*,
|
| 78 |
+
email: str,
|
| 79 |
+
purpose: VerificationPurpose,
|
| 80 |
+
pending_password_hash: str | None = None,
|
| 81 |
+
pending_name: str | None = None,
|
| 82 |
+
) -> tuple[EmailVerificationCode, str]:
|
| 83 |
+
"""Create a fresh code, returning ``(row, plaintext_code)`` for the caller to send.
|
| 84 |
+
|
| 85 |
+
Enforces the resend cooldown. Any previous code for this (email, purpose) is
|
| 86 |
+
deleted, so exactly one is live at a time and an old code stops working the
|
| 87 |
+
moment a new one is sent.
|
| 88 |
+
|
| 89 |
+
Raises 429 ``resend_too_soon`` (with ``Retry-After``) inside the cooldown.
|
| 90 |
+
The caller must commit — the code must be durable before the email goes out,
|
| 91 |
+
or a send that succeeds against a rolled-back row hands the user a dead code.
|
| 92 |
+
"""
|
| 93 |
+
now = datetime.utcnow()
|
| 94 |
+
purge_expired(db)
|
| 95 |
+
|
| 96 |
+
existing = _active_code(db, email, purpose)
|
| 97 |
+
if existing is not None:
|
| 98 |
+
elapsed = (now - existing.last_sent_at).total_seconds()
|
| 99 |
+
if elapsed < RESEND_COOLDOWN_SECONDS:
|
| 100 |
+
retry_in = max(1, int(RESEND_COOLDOWN_SECONDS - elapsed))
|
| 101 |
+
raise HTTPException(
|
| 102 |
+
status_code=429,
|
| 103 |
+
detail="resend_too_soon",
|
| 104 |
+
headers={"Retry-After": str(retry_in)},
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
db.query(EmailVerificationCode).filter(
|
| 108 |
+
EmailVerificationCode.email == email,
|
| 109 |
+
EmailVerificationCode.purpose == purpose.value,
|
| 110 |
+
).delete(synchronize_session=False)
|
| 111 |
+
|
| 112 |
+
code = generate_code()
|
| 113 |
+
row = EmailVerificationCode(
|
| 114 |
+
email=email,
|
| 115 |
+
purpose=purpose.value,
|
| 116 |
+
code_hash=hash_code(code),
|
| 117 |
+
pending_password_hash=pending_password_hash,
|
| 118 |
+
pending_name=pending_name,
|
| 119 |
+
attempts=0,
|
| 120 |
+
expires_at=now + timedelta(seconds=CODE_TTL_SECONDS),
|
| 121 |
+
used=False,
|
| 122 |
+
last_sent_at=now,
|
| 123 |
+
created_at=now,
|
| 124 |
+
)
|
| 125 |
+
db.add(row)
|
| 126 |
+
db.flush()
|
| 127 |
+
return row, code
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def consume_code(
|
| 131 |
+
db: Session, *, email: str, purpose: VerificationPurpose, code: str
|
| 132 |
+
) -> EmailVerificationCode:
|
| 133 |
+
"""Verify a code and mark it used, or raise.
|
| 134 |
+
|
| 135 |
+
Failure paths COMMIT the incremented attempt counter before raising. If they
|
| 136 |
+
didn't, the router's rollback on the HTTPException would undo the increment
|
| 137 |
+
and the 5-attempt cap would silently never trigger — the code could be
|
| 138 |
+
brute-forced at whatever rate the per-IP limiter allows.
|
| 139 |
+
|
| 140 |
+
Raises:
|
| 141 |
+
400 ``code_invalid`` — no live code, or the wrong digits (with
|
| 142 |
+
``attempts_remaining`` so the UI can warn).
|
| 143 |
+
400 ``code_expired`` — past the 10-minute window.
|
| 144 |
+
429 ``code_attempts_exceeded`` — 5th wrong try; the code is burned.
|
| 145 |
+
"""
|
| 146 |
+
row = _active_code(db, email, purpose)
|
| 147 |
+
if row is None:
|
| 148 |
+
raise HTTPException(status_code=400, detail="code_invalid")
|
| 149 |
+
|
| 150 |
+
if row.expires_at <= datetime.utcnow():
|
| 151 |
+
db.delete(row)
|
| 152 |
+
db.commit()
|
| 153 |
+
raise HTTPException(status_code=400, detail="code_expired")
|
| 154 |
+
|
| 155 |
+
if not hmac.compare_digest(hash_code(code), row.code_hash):
|
| 156 |
+
row.attempts = (row.attempts or 0) + 1
|
| 157 |
+
if row.attempts >= MAX_CODE_ATTEMPTS:
|
| 158 |
+
# Burn it: a code that has survived five guesses has leaked enough
|
| 159 |
+
# signal that reissuing is the only safe move.
|
| 160 |
+
db.delete(row)
|
| 161 |
+
db.commit()
|
| 162 |
+
logger.info("[AUTH] Burned %s code for %s after %d attempts",
|
| 163 |
+
purpose.value, email, MAX_CODE_ATTEMPTS)
|
| 164 |
+
raise HTTPException(status_code=429, detail="code_attempts_exceeded")
|
| 165 |
+
remaining = MAX_CODE_ATTEMPTS - row.attempts
|
| 166 |
+
db.commit()
|
| 167 |
+
raise HTTPException(
|
| 168 |
+
status_code=400,
|
| 169 |
+
detail={"code": "code_invalid", "attempts_remaining": remaining},
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
row.used = True
|
| 173 |
+
db.flush()
|
| 174 |
+
return row
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def check_code(
|
| 178 |
+
db: Session, *, email: str, purpose: VerificationPurpose, code: str
|
| 179 |
+
) -> None:
|
| 180 |
+
"""Validate a code WITHOUT spending it. Raises exactly as consume_code does.
|
| 181 |
+
|
| 182 |
+
The reset flow needs this because the code authorizes the password change at
|
| 183 |
+
the very end — consuming it at the "enter your code" step would leave nothing
|
| 184 |
+
to submit the new password with. So this runs the same expiry / mismatch /
|
| 185 |
+
burn logic and leaves ``used`` alone, letting the UI reject a wrong code up
|
| 186 |
+
front while the real consumption still happens in forgot/complete.
|
| 187 |
+
|
| 188 |
+
The attempt counter IS incremented and committed on a mismatch, same as
|
| 189 |
+
consume_code — otherwise this endpoint would be a free, unlimited oracle for
|
| 190 |
+
brute-forcing the code that consume_code carefully rate-limits.
|
| 191 |
+
"""
|
| 192 |
+
row = _active_code(db, email, purpose)
|
| 193 |
+
if row is None:
|
| 194 |
+
raise HTTPException(status_code=400, detail="code_invalid")
|
| 195 |
+
|
| 196 |
+
if row.expires_at <= datetime.utcnow():
|
| 197 |
+
db.delete(row)
|
| 198 |
+
db.commit()
|
| 199 |
+
raise HTTPException(status_code=400, detail="code_expired")
|
| 200 |
+
|
| 201 |
+
if not hmac.compare_digest(hash_code(code), row.code_hash):
|
| 202 |
+
row.attempts = (row.attempts or 0) + 1
|
| 203 |
+
if row.attempts >= MAX_CODE_ATTEMPTS:
|
| 204 |
+
db.delete(row)
|
| 205 |
+
db.commit()
|
| 206 |
+
logger.info("[AUTH] Burned %s code for %s after %d attempts",
|
| 207 |
+
purpose.value, email, MAX_CODE_ATTEMPTS)
|
| 208 |
+
raise HTTPException(status_code=429, detail="code_attempts_exceeded")
|
| 209 |
+
remaining = MAX_CODE_ATTEMPTS - row.attempts
|
| 210 |
+
db.commit()
|
| 211 |
+
raise HTTPException(
|
| 212 |
+
status_code=400,
|
| 213 |
+
detail={"code": "code_invalid", "attempts_remaining": remaining},
|
| 214 |
+
)
|
| 215 |
+
# Valid: deliberately no `used = True` — forgot/complete still consumes it.
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def clear_codes(db: Session, *, email: str) -> None:
|
| 219 |
+
"""Drop every code for an email, whatever its purpose.
|
| 220 |
+
|
| 221 |
+
Called after a password reset: an in-flight signup code for the same address
|
| 222 |
+
must not remain replayable once the account's credential has changed.
|
| 223 |
+
"""
|
| 224 |
+
db.query(EmailVerificationCode).filter(
|
| 225 |
+
EmailVerificationCode.email == email
|
| 226 |
+
).delete(synchronize_session=False)
|
backend/app/services/mcp_provider.py
CHANGED
|
@@ -49,6 +49,18 @@ from app.models.mcp_oauth import MCPAuthCode, MCPClient
|
|
| 49 |
AUTH_CODE_TTL_SECONDS = 600 # 10 minutes
|
| 50 |
|
| 51 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
class BlogVideoOAuthProvider(
|
| 53 |
OAuthAuthorizationServerProvider[AuthorizationCode, RefreshToken, AccessToken]
|
| 54 |
):
|
|
@@ -176,8 +188,9 @@ class BlogVideoOAuthProvider(
|
|
| 176 |
row.used = True
|
| 177 |
db.commit()
|
| 178 |
|
| 179 |
-
|
| 180 |
-
|
|
|
|
| 181 |
return OAuthToken(
|
| 182 |
access_token=access_token,
|
| 183 |
token_type="Bearer",
|
|
@@ -215,8 +228,18 @@ class BlogVideoOAuthProvider(
|
|
| 215 |
if not payload or payload.get("typ") != "refresh":
|
| 216 |
raise ValueError("Invalid refresh token")
|
| 217 |
user_id = int(payload["sub"])
|
| 218 |
-
|
| 219 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 220 |
return OAuthToken(
|
| 221 |
access_token=new_access,
|
| 222 |
token_type="Bearer",
|
|
|
|
| 49 |
AUTH_CODE_TTL_SECONDS = 600 # 10 minutes
|
| 50 |
|
| 51 |
|
| 52 |
+
def _token_version(db, user_id: int) -> int:
|
| 53 |
+
"""The account's current revocation counter, or 0 if it has no row.
|
| 54 |
+
|
| 55 |
+
Read at issue time so the token carries the value it must still match to be
|
| 56 |
+
accepted; see app/auth.py::token_version_is_current.
|
| 57 |
+
"""
|
| 58 |
+
from app.models.user import User
|
| 59 |
+
|
| 60 |
+
value = db.query(User.token_version).filter(User.id == user_id).scalar()
|
| 61 |
+
return int(value or 0)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
class BlogVideoOAuthProvider(
|
| 65 |
OAuthAuthorizationServerProvider[AuthorizationCode, RefreshToken, AccessToken]
|
| 66 |
):
|
|
|
|
| 188 |
row.used = True
|
| 189 |
db.commit()
|
| 190 |
|
| 191 |
+
tv = _token_version(db, row.user_id)
|
| 192 |
+
access_token = create_access_token(row.user_id, tv)
|
| 193 |
+
refresh_token = create_refresh_token(row.user_id, tv)
|
| 194 |
return OAuthToken(
|
| 195 |
access_token=access_token,
|
| 196 |
token_type="Bearer",
|
|
|
|
| 228 |
if not payload or payload.get("typ") != "refresh":
|
| 229 |
raise ValueError("Invalid refresh token")
|
| 230 |
user_id = int(payload["sub"])
|
| 231 |
+
# A revoked refresh token must not mint a fresh pair, or revocation
|
| 232 |
+
# would be undone by the next refresh — the 30-day credential would
|
| 233 |
+
# quietly reissue itself past a password change.
|
| 234 |
+
db = SessionLocal()
|
| 235 |
+
try:
|
| 236 |
+
tv = _token_version(db, user_id)
|
| 237 |
+
finally:
|
| 238 |
+
db.close()
|
| 239 |
+
if int(payload.get("tv", 0)) != tv:
|
| 240 |
+
raise ValueError("Invalid refresh token")
|
| 241 |
+
new_access = create_access_token(user_id, tv)
|
| 242 |
+
new_refresh = create_refresh_token(user_id, tv)
|
| 243 |
return OAuthToken(
|
| 244 |
access_token=new_access,
|
| 245 |
token_type="Bearer",
|
backend/app/services/microsoft_auth.py
DELETED
|
@@ -1,172 +0,0 @@
|
|
| 1 |
-
"""Verify "Sign in with Microsoft" ID tokens (Microsoft Entra ID / Azure AD).
|
| 2 |
-
|
| 3 |
-
Mirrors ``app.services.apple_auth``: fetch Microsoft's public JWKS, pick the key
|
| 4 |
-
named by the token header's ``kid``, and verify the RS256 signature plus the
|
| 5 |
-
audience, issuer and expiry claims.
|
| 6 |
-
|
| 7 |
-
We verify the *ID token* the browser receives from MSAL, rather than exchanging
|
| 8 |
-
an authorization code, so no client secret has to live in the deployment.
|
| 9 |
-
"""
|
| 10 |
-
from __future__ import annotations
|
| 11 |
-
|
| 12 |
-
import threading
|
| 13 |
-
import time
|
| 14 |
-
from dataclasses import dataclass
|
| 15 |
-
|
| 16 |
-
import jwt
|
| 17 |
-
import requests
|
| 18 |
-
from jwt import PyJWKSet
|
| 19 |
-
|
| 20 |
-
from app.config import settings
|
| 21 |
-
from app.observability.logging import get_logger
|
| 22 |
-
|
| 23 |
-
logger = get_logger(__name__)
|
| 24 |
-
|
| 25 |
-
# The "common" endpoint accepts both personal Microsoft accounts (outlook.com,
|
| 26 |
-
# hotmail.com, live.com) and any organization's Microsoft 365 tenant.
|
| 27 |
-
MICROSOFT_JWKS_URL = "https://login.microsoftonline.com/common/discovery/v2.0/keys"
|
| 28 |
-
|
| 29 |
-
# Microsoft rotates signing keys, so the fetched set is cached only briefly.
|
| 30 |
-
_JWKS_TTL_SECONDS = 6 * 60 * 60
|
| 31 |
-
|
| 32 |
-
_jwks_lock = threading.Lock()
|
| 33 |
-
_jwks_cache: PyJWKSet | None = None
|
| 34 |
-
_jwks_fetched_at: float = 0.0
|
| 35 |
-
|
| 36 |
-
# Fetched with `requests` rather than PyJWKClient: PyJWKClient uses urllib,
|
| 37 |
-
# which relies on the host's OpenSSL CA store and fails with
|
| 38 |
-
# CERTIFICATE_VERIFY_FAILED wherever that store isn't populated (macOS with a
|
| 39 |
-
# python.org build, slim containers). `requests` ships certifi, so this works
|
| 40 |
-
# the same everywhere.
|
| 41 |
-
_JWKS_TIMEOUT_SECONDS = 10
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
class MicrosoftAuthError(ValueError):
|
| 45 |
-
"""Raised when a Microsoft ID token cannot be trusted."""
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
class MicrosoftNoEmailError(MicrosoftAuthError):
|
| 49 |
-
"""The token was valid but carried no usable email address.
|
| 50 |
-
|
| 51 |
-
Distinct from the general error because it is a fixable account-settings
|
| 52 |
-
problem rather than an untrusted token, so the router answers 400 (with
|
| 53 |
-
specific UI copy) instead of 401.
|
| 54 |
-
"""
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
@dataclass(frozen=True)
|
| 58 |
-
class MicrosoftIdentity:
|
| 59 |
-
"""The claims we care about from a verified Microsoft ID token."""
|
| 60 |
-
|
| 61 |
-
microsoft_id: str # stable per-user object id ("oid")
|
| 62 |
-
email: str
|
| 63 |
-
name: str | None
|
| 64 |
-
tenant_id: str | None
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
def _get_jwks(force_refresh: bool = False) -> PyJWKSet:
|
| 68 |
-
"""Return Microsoft's signing-key set, refetching when stale or on demand."""
|
| 69 |
-
global _jwks_cache, _jwks_fetched_at
|
| 70 |
-
with _jwks_lock:
|
| 71 |
-
expired = (time.time() - _jwks_fetched_at) > _JWKS_TTL_SECONDS
|
| 72 |
-
if _jwks_cache is None or expired or force_refresh:
|
| 73 |
-
resp = requests.get(MICROSOFT_JWKS_URL, timeout=_JWKS_TIMEOUT_SECONDS)
|
| 74 |
-
resp.raise_for_status()
|
| 75 |
-
_jwks_cache = PyJWKSet.from_dict(resp.json())
|
| 76 |
-
_jwks_fetched_at = time.time()
|
| 77 |
-
return _jwks_cache
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
def _signing_key_for(id_token: str, force_refresh: bool = False):
|
| 81 |
-
"""Select the JWK named by the token header's ``kid``."""
|
| 82 |
-
kid = jwt.get_unverified_header(id_token).get("kid")
|
| 83 |
-
if not kid:
|
| 84 |
-
raise MicrosoftAuthError("Microsoft token header has no key id")
|
| 85 |
-
for key in _get_jwks(force_refresh).keys:
|
| 86 |
-
if key.key_id == kid:
|
| 87 |
-
return key
|
| 88 |
-
raise KeyError(f"no Microsoft signing key for kid {kid!r}")
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
def _email_from_claims(claims: dict) -> str:
|
| 92 |
-
"""Pick the account's email address, or raise if there isn't a usable one.
|
| 93 |
-
|
| 94 |
-
Without an email we cannot enforce one-account-per-email, so a token that
|
| 95 |
-
carries none is rejected rather than being keyed on something else.
|
| 96 |
-
``preferred_username`` is the normal source for both personal and org
|
| 97 |
-
accounts, but it is a UPN and is only trusted when actually email-shaped.
|
| 98 |
-
"""
|
| 99 |
-
email = (claims.get("email") or "").strip().lower()
|
| 100 |
-
if email:
|
| 101 |
-
return email
|
| 102 |
-
|
| 103 |
-
upn = (claims.get("preferred_username") or "").strip().lower()
|
| 104 |
-
if "@" in upn:
|
| 105 |
-
return upn
|
| 106 |
-
|
| 107 |
-
raise MicrosoftNoEmailError("Email not provided by Microsoft")
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
def verify_microsoft_id_token(id_token: str) -> MicrosoftIdentity:
|
| 111 |
-
"""Verify a Microsoft ID token and return its identity claims.
|
| 112 |
-
|
| 113 |
-
Raises MicrosoftAuthError on any failure — an unfetchable JWKS, an unknown
|
| 114 |
-
key, a bad signature, a wrong audience/issuer, an expired token, or a
|
| 115 |
-
missing email claim. Callers map this to a 401.
|
| 116 |
-
"""
|
| 117 |
-
if not settings.MICROSOFT_CLIENT_ID:
|
| 118 |
-
# Misconfiguration, not a bad token; surface it distinctly in the logs.
|
| 119 |
-
logger.error("[MICROSOFT AUTH] MICROSOFT_CLIENT_ID is not configured")
|
| 120 |
-
raise MicrosoftAuthError("Microsoft sign-in is not configured")
|
| 121 |
-
|
| 122 |
-
# A key rotated in after our cache was built shows up as an unknown kid, so
|
| 123 |
-
# retry exactly once against a freshly fetched JWKS before giving up.
|
| 124 |
-
last_error: Exception | None = None
|
| 125 |
-
signing_key = None
|
| 126 |
-
for force_refresh in (False, True):
|
| 127 |
-
try:
|
| 128 |
-
signing_key = _signing_key_for(id_token, force_refresh)
|
| 129 |
-
break
|
| 130 |
-
except (KeyError, jwt.PyJWKError, requests.RequestException, ValueError) as e:
|
| 131 |
-
last_error = e
|
| 132 |
-
if signing_key is None:
|
| 133 |
-
logger.error("[MICROSOFT AUTH] Could not resolve signing key: %s", last_error)
|
| 134 |
-
raise MicrosoftAuthError(f"Could not verify Microsoft token: {last_error}")
|
| 135 |
-
|
| 136 |
-
try:
|
| 137 |
-
claims = jwt.decode(
|
| 138 |
-
id_token,
|
| 139 |
-
signing_key.key,
|
| 140 |
-
algorithms=["RS256"],
|
| 141 |
-
audience=settings.MICROSOFT_CLIENT_ID,
|
| 142 |
-
# The issuer is per-tenant under the "common" endpoint, so it cannot
|
| 143 |
-
# be matched against one constant — it is checked against the
|
| 144 |
-
# token's own `tid` below instead.
|
| 145 |
-
options={"verify_iss": False, "require": ["exp", "iss", "aud"]},
|
| 146 |
-
)
|
| 147 |
-
except jwt.InvalidTokenError as e:
|
| 148 |
-
logger.warning("[MICROSOFT AUTH] ID token rejected: %s", e)
|
| 149 |
-
raise MicrosoftAuthError(f"Invalid Microsoft token: {e}")
|
| 150 |
-
|
| 151 |
-
# Bind the issuer to the tenant that minted the token. Hard-coding a single
|
| 152 |
-
# issuer would reject every organizational account; skipping the check would
|
| 153 |
-
# accept a well-formed token from an unrelated tenant.
|
| 154 |
-
tenant_id = claims.get("tid")
|
| 155 |
-
issuer = claims.get("iss")
|
| 156 |
-
if not tenant_id or issuer != f"https://login.microsoftonline.com/{tenant_id}/v2.0":
|
| 157 |
-
logger.warning("[MICROSOFT AUTH] Issuer/tenant mismatch: iss=%r tid=%r", issuer, tenant_id)
|
| 158 |
-
raise MicrosoftAuthError("Invalid Microsoft token issuer")
|
| 159 |
-
|
| 160 |
-
# `oid` is the durable per-user object id. `sub` is pairwise per application
|
| 161 |
-
# and changes if the app registration is recreated, which would strand every
|
| 162 |
-
# existing account — so prefer `oid` and only fall back when it is absent.
|
| 163 |
-
microsoft_id = claims.get("oid") or claims.get("sub")
|
| 164 |
-
if not microsoft_id:
|
| 165 |
-
raise MicrosoftAuthError("Microsoft token has no subject")
|
| 166 |
-
|
| 167 |
-
return MicrosoftIdentity(
|
| 168 |
-
microsoft_id=microsoft_id,
|
| 169 |
-
email=_email_from_claims(claims),
|
| 170 |
-
name=(claims.get("name") or "").strip() or None,
|
| 171 |
-
tenant_id=tenant_id,
|
| 172 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
backend/app/services/password.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Password hashing and policy for built-in email/password sign-in.
|
| 2 |
+
|
| 3 |
+
Argon2id via argon2-cffi. Chosen over bcrypt because bcrypt silently truncates
|
| 4 |
+
its input at 72 bytes — ``"a" * 72 + "X"`` and ``"a" * 72 + "Y"`` are the same
|
| 5 |
+
password to it — and the usual SHA-256 pre-hash workaround bakes an encoding
|
| 6 |
+
decision into every stored hash that can never be changed afterwards. Argon2id
|
| 7 |
+
has no input length limit and carries its parameters inside the encoded hash, so
|
| 8 |
+
the cost can be raised later and existing hashes upgraded on next login via
|
| 9 |
+
``needs_rehash``.
|
| 10 |
+
|
| 11 |
+
Policy is a length minimum plus two composition rules (one capital, one special
|
| 12 |
+
character). Note that composition rules are a product decision rather than a
|
| 13 |
+
security win — NIST SP 800-63B advises against them, because they push users
|
| 14 |
+
toward predictable substitutions ("Password1!") without adding much real entropy.
|
| 15 |
+
Length is what actually helps, which is why the minimum stays and is checked
|
| 16 |
+
first.
|
| 17 |
+
"""
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
import re
|
| 21 |
+
|
| 22 |
+
from fastapi import HTTPException
|
| 23 |
+
|
| 24 |
+
from argon2 import PasswordHasher
|
| 25 |
+
from argon2.exceptions import (
|
| 26 |
+
HashingError,
|
| 27 |
+
InvalidHashError,
|
| 28 |
+
VerificationError,
|
| 29 |
+
VerifyMismatchError,
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
MIN_PASSWORD_LENGTH = 8
|
| 33 |
+
# Not a security limit — an upper bound on KDF input so a huge body can't be used
|
| 34 |
+
# to burn CPU. We reject rather than truncate: silently ignoring the tail is the
|
| 35 |
+
# exact bcrypt failure mode this module exists to avoid.
|
| 36 |
+
MAX_PASSWORD_LENGTH = 256
|
| 37 |
+
|
| 38 |
+
_UPPERCASE_RE = re.compile(r"[A-Z]")
|
| 39 |
+
# Anything that is not a letter or digit counts, including spaces and non-ASCII
|
| 40 |
+
# punctuation. Deliberately broad: the rule exists to widen the character space,
|
| 41 |
+
# and a narrow allowlist would reject a non-English speaker's perfectly good
|
| 42 |
+
# password for using the "wrong" symbol.
|
| 43 |
+
_SPECIAL_RE = re.compile(r"[^A-Za-z0-9]")
|
| 44 |
+
|
| 45 |
+
# Defaults are Argon2id with ~64 MiB per verify. That memory cost is per
|
| 46 |
+
# concurrent verification, so if the API runs on a small instance lower it to the
|
| 47 |
+
# OWASP 19 MiB profile (memory_cost=19456) rather than weakening time_cost.
|
| 48 |
+
_hasher = PasswordHasher()
|
| 49 |
+
|
| 50 |
+
# Precomputed hash of a value nobody can supply, used to equalize response time
|
| 51 |
+
# when an email has no account at all. Without it, "no such user" returns
|
| 52 |
+
# measurably faster than "wrong password" and the login endpoint becomes an
|
| 53 |
+
# account-existence oracle. Module-level so the cost is paid once at import.
|
| 54 |
+
_DUMMY_HASH = _hasher.hash("blog2video-nonexistent-account-timing-equalizer")
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def validate_password(password: str) -> None:
|
| 58 |
+
"""Enforce the password policy, raising the API's error codes.
|
| 59 |
+
|
| 60 |
+
Authoritative: the frontend mirrors these rules for instant feedback, but the
|
| 61 |
+
browser is not a security boundary — anyone can POST straight to the API — so
|
| 62 |
+
every path that SETS a password calls this.
|
| 63 |
+
|
| 64 |
+
Critically, it is never called on the login path. The policy governs
|
| 65 |
+
passwords being set, never ones being used: re-validating at sign-in would
|
| 66 |
+
lock every existing user out of their own account the moment a rule is added.
|
| 67 |
+
``verify_password`` must stay free of policy for exactly that reason.
|
| 68 |
+
|
| 69 |
+
Each failure has its own code so the UI can say precisely what is missing
|
| 70 |
+
rather than restating the whole policy.
|
| 71 |
+
"""
|
| 72 |
+
if len(password) < MIN_PASSWORD_LENGTH:
|
| 73 |
+
raise HTTPException(status_code=422, detail="password_too_short")
|
| 74 |
+
if len(password) > MAX_PASSWORD_LENGTH:
|
| 75 |
+
raise HTTPException(status_code=422, detail="password_too_long")
|
| 76 |
+
if not _UPPERCASE_RE.search(password):
|
| 77 |
+
raise HTTPException(status_code=422, detail="password_needs_uppercase")
|
| 78 |
+
if not _SPECIAL_RE.search(password):
|
| 79 |
+
raise HTTPException(status_code=422, detail="password_needs_special")
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def hash_password(password: str) -> str:
|
| 83 |
+
"""Return an Argon2id encoded hash (algorithm, params and salt included)."""
|
| 84 |
+
return _hasher.hash(password)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def verify_password(password: str, password_hash: str | None) -> bool:
|
| 88 |
+
"""Check a password against a stored hash, returning False rather than raising.
|
| 89 |
+
|
| 90 |
+
``password_hash`` is None for every social account, which must read as "does
|
| 91 |
+
not match" — never as an error the caller might mishandle into a successful
|
| 92 |
+
login. A corrupt or unparseable hash is treated the same way. The dummy verify
|
| 93 |
+
on the None path keeps the timing indistinguishable from a real mismatch.
|
| 94 |
+
"""
|
| 95 |
+
if not password_hash:
|
| 96 |
+
verify_password_dummy()
|
| 97 |
+
return False
|
| 98 |
+
try:
|
| 99 |
+
return _hasher.verify(password_hash, password)
|
| 100 |
+
except (VerifyMismatchError, InvalidHashError, VerificationError):
|
| 101 |
+
return False
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def verify_password_dummy() -> None:
|
| 105 |
+
"""Burn one verification's worth of time against a throwaway hash.
|
| 106 |
+
|
| 107 |
+
Called on paths that reject before a real hash is available (no such account),
|
| 108 |
+
so response time doesn't reveal whether the email exists.
|
| 109 |
+
"""
|
| 110 |
+
try:
|
| 111 |
+
_hasher.verify(_DUMMY_HASH, "")
|
| 112 |
+
except (VerifyMismatchError, InvalidHashError, VerificationError, HashingError):
|
| 113 |
+
pass
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def needs_rehash(password_hash: str | None) -> bool:
|
| 117 |
+
"""True when a stored hash predates the current Argon2 parameters.
|
| 118 |
+
|
| 119 |
+
Callers re-hash on successful login, so raising the cost factor migrates
|
| 120 |
+
accounts as their owners sign in, with no bulk job and no forced reset.
|
| 121 |
+
"""
|
| 122 |
+
if not password_hash:
|
| 123 |
+
return False
|
| 124 |
+
try:
|
| 125 |
+
return _hasher.check_needs_rehash(password_hash)
|
| 126 |
+
except InvalidHashError:
|
| 127 |
+
return False
|
backend/app/services/rate_limit.py
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""In-process rate limiting for unauthenticated auth endpoints.
|
| 2 |
+
|
| 3 |
+
Generalizes the per-IP lockout in routers/template_studio.py so login, signup and
|
| 4 |
+
password-reset can share one implementation.
|
| 5 |
+
|
| 6 |
+
SCOPE, stated plainly: this is per-process state. Under ``uvicorn --workers N``
|
| 7 |
+
or several containers the effective allowance is N x the configured number, and a
|
| 8 |
+
restart clears it entirely. That is acceptable for what it is — a speed bump in
|
| 9 |
+
front of an Argon2 verification, where the KDF is the real cost bound — but it is
|
| 10 |
+
NOT a control to point at in a compliance document, and it must never be the only
|
| 11 |
+
thing enforcing a security-critical limit. The two limits that genuinely must
|
| 12 |
+
hold across workers (the 60s resend cooldown and the 5-attempt code burn) live in
|
| 13 |
+
the database instead; see services/email_verification.py. Swapping this for Redis
|
| 14 |
+
later means reimplementing this class and nothing else.
|
| 15 |
+
"""
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import hashlib
|
| 19 |
+
import time
|
| 20 |
+
from dataclasses import dataclass
|
| 21 |
+
from threading import Lock
|
| 22 |
+
|
| 23 |
+
from fastapi import HTTPException, Request
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@dataclass(frozen=True)
|
| 27 |
+
class RateLimitPolicy:
|
| 28 |
+
max_attempts: int
|
| 29 |
+
lockout_seconds: int
|
| 30 |
+
# Attempts stop counting toward the limit once this long has passed since the
|
| 31 |
+
# last one, so an occasional typo over a week never accumulates into a lockout.
|
| 32 |
+
window_seconds: int
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class InProcessRateLimiter:
|
| 36 |
+
"""Failure-counting limiter with a fixed lockout. Not a token bucket.
|
| 37 |
+
|
| 38 |
+
Only failures are recorded, so a user typing their password correctly is
|
| 39 |
+
never throttled no matter how often they sign in.
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
def __init__(self, name: str, policy: RateLimitPolicy) -> None:
|
| 43 |
+
self.name = name
|
| 44 |
+
self.policy = policy
|
| 45 |
+
self._entries: dict[str, dict[str, float]] = {}
|
| 46 |
+
self._lock = Lock()
|
| 47 |
+
|
| 48 |
+
def check(self, key: str) -> None:
|
| 49 |
+
"""Raise 429 if ``key`` is currently locked out."""
|
| 50 |
+
now = time.time()
|
| 51 |
+
with self._lock:
|
| 52 |
+
self._sweep(now)
|
| 53 |
+
entry = self._entries.get(key)
|
| 54 |
+
if entry and entry["locked_until"] > now:
|
| 55 |
+
retry_in = max(1, int(entry["locked_until"] - now))
|
| 56 |
+
raise HTTPException(
|
| 57 |
+
status_code=429,
|
| 58 |
+
detail="too_many_attempts",
|
| 59 |
+
headers={"Retry-After": str(retry_in)},
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
def record_failure(self, key: str) -> int:
|
| 63 |
+
"""Count a failed attempt. Returns attempts remaining before lockout."""
|
| 64 |
+
now = time.time()
|
| 65 |
+
with self._lock:
|
| 66 |
+
entry = self._entries.get(key)
|
| 67 |
+
if entry is None or now - entry["last_seen"] > self.policy.window_seconds:
|
| 68 |
+
entry = {"count": 0.0, "locked_until": 0.0, "last_seen": now}
|
| 69 |
+
entry["count"] += 1
|
| 70 |
+
entry["last_seen"] = now
|
| 71 |
+
if entry["count"] >= self.policy.max_attempts:
|
| 72 |
+
entry["locked_until"] = now + self.policy.lockout_seconds
|
| 73 |
+
entry["count"] = 0.0
|
| 74 |
+
self._entries[key] = entry
|
| 75 |
+
return max(0, self.policy.max_attempts - int(entry["count"]))
|
| 76 |
+
|
| 77 |
+
def clear(self, key: str) -> None:
|
| 78 |
+
"""Forget a key's failures — called on a successful authentication."""
|
| 79 |
+
with self._lock:
|
| 80 |
+
self._entries.pop(key, None)
|
| 81 |
+
|
| 82 |
+
def reset(self) -> None:
|
| 83 |
+
"""Drop all state. For tests, which would otherwise bleed into each other."""
|
| 84 |
+
with self._lock:
|
| 85 |
+
self._entries.clear()
|
| 86 |
+
|
| 87 |
+
def _sweep(self, now: float) -> None:
|
| 88 |
+
"""Drop entries that are neither locked nor inside their window.
|
| 89 |
+
|
| 90 |
+
The template-studio limiter this is modelled on leaks one dict entry per
|
| 91 |
+
IP forever; these endpoints face the open internet, so that is a slow
|
| 92 |
+
memory leak rather than a curiosity.
|
| 93 |
+
"""
|
| 94 |
+
if len(self._entries) < 512:
|
| 95 |
+
return
|
| 96 |
+
stale = [
|
| 97 |
+
k
|
| 98 |
+
for k, e in self._entries.items()
|
| 99 |
+
if e["locked_until"] <= now
|
| 100 |
+
and now - e["last_seen"] > self.policy.window_seconds
|
| 101 |
+
]
|
| 102 |
+
for k in stale:
|
| 103 |
+
self._entries.pop(k, None)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def client_key(request: Request) -> str:
|
| 107 |
+
"""Best-effort client identifier, preferring X-Forwarded-For behind a proxy."""
|
| 108 |
+
fwd = (request.headers.get("x-forwarded-for") or "").split(",")[0].strip()
|
| 109 |
+
if fwd:
|
| 110 |
+
return fwd
|
| 111 |
+
return request.client.host if request.client else "unknown"
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def email_key(email: str) -> str:
|
| 115 |
+
"""Hashed key for per-account limiting.
|
| 116 |
+
|
| 117 |
+
Hashed so the limiter's state isn't a plaintext list of who has been trying
|
| 118 |
+
to sign in — it lives in memory, but it also reaches logs and crash dumps.
|
| 119 |
+
"""
|
| 120 |
+
return hashlib.sha256(email.strip().lower().encode("utf-8")).hexdigest()
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
_MINUTE = 60
|
| 124 |
+
_HOUR = 60 * 60
|
| 125 |
+
|
| 126 |
+
# Login is limited on BOTH axes on purpose: per-IP alone lets a botnet credential-
|
| 127 |
+
# stuff a single account, per-email alone lets one host spray many accounts.
|
| 128 |
+
login_ip_limiter = InProcessRateLimiter(
|
| 129 |
+
"login_ip", RateLimitPolicy(max_attempts=10, lockout_seconds=15 * _MINUTE, window_seconds=15 * _MINUTE)
|
| 130 |
+
)
|
| 131 |
+
login_email_limiter = InProcessRateLimiter(
|
| 132 |
+
"login_email", RateLimitPolicy(max_attempts=5, lockout_seconds=15 * _MINUTE, window_seconds=15 * _MINUTE)
|
| 133 |
+
)
|
| 134 |
+
register_limiter = InProcessRateLimiter(
|
| 135 |
+
"register", RateLimitPolicy(max_attempts=5, lockout_seconds=_HOUR, window_seconds=_HOUR)
|
| 136 |
+
)
|
| 137 |
+
resend_limiter = InProcessRateLimiter(
|
| 138 |
+
"resend", RateLimitPolicy(max_attempts=5, lockout_seconds=_HOUR, window_seconds=_HOUR)
|
| 139 |
+
)
|
| 140 |
+
verify_limiter = InProcessRateLimiter(
|
| 141 |
+
"verify", RateLimitPolicy(max_attempts=20, lockout_seconds=15 * _MINUTE, window_seconds=15 * _MINUTE)
|
| 142 |
+
)
|
| 143 |
+
forgot_ip_limiter = InProcessRateLimiter(
|
| 144 |
+
"forgot_ip", RateLimitPolicy(max_attempts=5, lockout_seconds=_HOUR, window_seconds=_HOUR)
|
| 145 |
+
)
|
| 146 |
+
forgot_email_limiter = InProcessRateLimiter(
|
| 147 |
+
"forgot_email", RateLimitPolicy(max_attempts=5, lockout_seconds=_HOUR, window_seconds=_HOUR)
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
ALL_LIMITERS = (
|
| 151 |
+
login_ip_limiter,
|
| 152 |
+
login_email_limiter,
|
| 153 |
+
register_limiter,
|
| 154 |
+
resend_limiter,
|
| 155 |
+
verify_limiter,
|
| 156 |
+
forgot_ip_limiter,
|
| 157 |
+
forgot_email_limiter,
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def reset_all_limiters() -> None:
|
| 162 |
+
"""Clear every limiter. Used by the test suite between cases."""
|
| 163 |
+
for limiter in ALL_LIMITERS:
|
| 164 |
+
limiter.reset()
|
backend/app/support/identity.py
CHANGED
|
@@ -27,6 +27,15 @@ class SupportIdentity:
|
|
| 27 |
|
| 28 |
|
| 29 |
def _extract_jwt_user(request: Request) -> Optional[int]:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
auth = request.headers.get("authorization") or request.headers.get("Authorization")
|
| 31 |
if not auth:
|
| 32 |
return None
|
|
|
|
| 27 |
|
| 28 |
|
| 29 |
def _extract_jwt_user(request: Request) -> Optional[int]:
|
| 30 |
+
"""Best-effort user id from the bearer token, or None for anonymous visitors.
|
| 31 |
+
|
| 32 |
+
Signature and expiry only — this helper has no DB session, so unlike
|
| 33 |
+
get_current_user it cannot check the account's token_version. A revoked
|
| 34 |
+
token can therefore still attribute a support-chat message to its user until
|
| 35 |
+
it expires. Accepted deliberately: this identity only labels conversations
|
| 36 |
+
and gates sending a message, never reads or mutates account data. Anything
|
| 37 |
+
that touches user data must depend on get_current_user instead.
|
| 38 |
+
"""
|
| 39 |
auth = request.headers.get("authorization") or request.headers.get("Authorization")
|
| 40 |
if not auth:
|
| 41 |
return None
|
backend/requirements.txt
CHANGED
|
@@ -30,9 +30,16 @@ opentelemetry-instrumentation-logging>=0.45b0
|
|
| 30 |
|
| 31 |
# Auth & Billing
|
| 32 |
PyJWT>=2.8.0
|
| 33 |
-
#
|
|
|
|
|
|
|
| 34 |
cryptography>=42.0.0
|
| 35 |
google-auth>=2.29.0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
stripe>=10.0.0
|
| 37 |
|
| 38 |
# PostgreSQL driver
|
|
|
|
| 30 |
|
| 31 |
# Auth & Billing
|
| 32 |
PyJWT>=2.8.0
|
| 33 |
+
# Kept as an explicit pin rather than an implicit transitive of google-auth /
|
| 34 |
+
# requests. Our own tokens are HS256 and need no asymmetric crypto, so nothing
|
| 35 |
+
# here depends on it directly since Apple sign-in was removed.
|
| 36 |
cryptography>=42.0.0
|
| 37 |
google-auth>=2.29.0
|
| 38 |
+
# Password hashing for built-in email/password sign-in (services/password.py).
|
| 39 |
+
# Argon2id rather than bcrypt: bcrypt silently truncates input at 72 bytes, so two
|
| 40 |
+
# different long passwords can collide, and the SHA-256 pre-hash workaround is a
|
| 41 |
+
# format decision you can never reverse. Ships prebuilt wheels — no compiler needed.
|
| 42 |
+
argon2-cffi>=23.1.0
|
| 43 |
stripe>=10.0.0
|
| 44 |
|
| 45 |
# PostgreSQL driver
|
backend/templates/newspaper/meta.json
CHANGED
|
@@ -35,11 +35,11 @@
|
|
| 35 |
"label": "News Headline",
|
| 36 |
"defaults": {
|
| 37 |
"titleFontSize": {
|
| 38 |
-
"portrait":
|
| 39 |
"landscape": 62
|
| 40 |
},
|
| 41 |
"descriptionFontSize": {
|
| 42 |
-
"portrait":
|
| 43 |
"landscape": 28
|
| 44 |
},
|
| 45 |
"category": "News",
|
|
@@ -106,11 +106,11 @@
|
|
| 106 |
"label": "News Headline — Broadsheet",
|
| 107 |
"defaults": {
|
| 108 |
"titleFontSize": {
|
| 109 |
-
"portrait":
|
| 110 |
"landscape": 54
|
| 111 |
},
|
| 112 |
"descriptionFontSize": {
|
| 113 |
-
"portrait":
|
| 114 |
"landscape": 27
|
| 115 |
}
|
| 116 |
}
|
|
@@ -119,11 +119,11 @@
|
|
| 119 |
"label": "News Headline — Stacked Deck",
|
| 120 |
"defaults": {
|
| 121 |
"titleFontSize": {
|
| 122 |
-
"portrait":
|
| 123 |
"landscape": 50
|
| 124 |
},
|
| 125 |
"descriptionFontSize": {
|
| 126 |
-
"portrait":
|
| 127 |
"landscape": 26
|
| 128 |
}
|
| 129 |
}
|
|
|
|
| 35 |
"label": "News Headline",
|
| 36 |
"defaults": {
|
| 37 |
"titleFontSize": {
|
| 38 |
+
"portrait": 68,
|
| 39 |
"landscape": 62
|
| 40 |
},
|
| 41 |
"descriptionFontSize": {
|
| 42 |
+
"portrait": 37,
|
| 43 |
"landscape": 28
|
| 44 |
},
|
| 45 |
"category": "News",
|
|
|
|
| 106 |
"label": "News Headline — Broadsheet",
|
| 107 |
"defaults": {
|
| 108 |
"titleFontSize": {
|
| 109 |
+
"portrait": 65,
|
| 110 |
"landscape": 54
|
| 111 |
},
|
| 112 |
"descriptionFontSize": {
|
| 113 |
+
"portrait": 32,
|
| 114 |
"landscape": 27
|
| 115 |
}
|
| 116 |
}
|
|
|
|
| 119 |
"label": "News Headline — Stacked Deck",
|
| 120 |
"defaults": {
|
| 121 |
"titleFontSize": {
|
| 122 |
+
"portrait": 66,
|
| 123 |
"landscape": 50
|
| 124 |
},
|
| 125 |
"descriptionFontSize": {
|
| 126 |
+
"portrait": 33,
|
| 127 |
"landscape": 26
|
| 128 |
}
|
| 129 |
}
|
backend/tests/conftest.py
CHANGED
|
@@ -100,6 +100,8 @@ def kill_network(monkeypatch):
|
|
| 100 |
"send_custom_template_request_email",
|
| 101 |
"send_referral_invite_email",
|
| 102 |
"send_support_escalation_email",
|
|
|
|
|
|
|
| 103 |
):
|
| 104 |
monkeypatch.setattr(
|
| 105 |
email_module.EmailService, method,
|
|
|
|
| 100 |
"send_custom_template_request_email",
|
| 101 |
"send_referral_invite_email",
|
| 102 |
"send_support_escalation_email",
|
| 103 |
+
"send_verification_code_email",
|
| 104 |
+
"send_password_reset_code_email",
|
| 105 |
):
|
| 106 |
monkeypatch.setattr(
|
| 107 |
email_module.EmailService, method,
|
backend/tests/test_auth_providers.py
CHANGED
|
@@ -1,24 +1,26 @@
|
|
| 1 |
"""
|
| 2 |
-
Depth tier — multi-provider identity rules (Google +
|
| 3 |
|
| 4 |
The invariant under test: one account per email, forever, bound for life to the
|
| 5 |
provider that created it. A second provider presenting a known email is always
|
| 6 |
rejected (409 wrong_auth_provider) — never linked, never duplicated — and that
|
| 7 |
rejection outranks the soft-delete/reactivation prompt.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
"""
|
| 9 |
import pytest
|
| 10 |
|
| 11 |
import app.routers.auth as auth_router
|
| 12 |
from app.models.user import AuthProvider, PlanTier, User
|
| 13 |
-
from app.services.
|
| 14 |
-
from app.services.microsoft_auth import (
|
| 15 |
-
MicrosoftAuthError,
|
| 16 |
-
MicrosoftIdentity,
|
| 17 |
-
MicrosoftNoEmailError,
|
| 18 |
-
)
|
| 19 |
|
| 20 |
pytestmark = pytest.mark.depth
|
| 21 |
|
|
|
|
|
|
|
| 22 |
|
| 23 |
# ─── Helpers ────────────────────────────────────────────────────────────────
|
| 24 |
|
|
@@ -30,54 +32,40 @@ def _mock_google(monkeypatch, *, sub, email, name="Google User"):
|
|
| 30 |
)
|
| 31 |
|
| 32 |
|
| 33 |
-
def _mock_apple(monkeypatch, *, sub, email, private=False):
|
| 34 |
-
monkeypatch.setattr(
|
| 35 |
-
auth_router, "verify_apple_identity_token",
|
| 36 |
-
lambda *a, **k: AppleIdentity(
|
| 37 |
-
apple_id=sub, email=email, email_verified=True, is_private_email=private
|
| 38 |
-
),
|
| 39 |
-
raising=True,
|
| 40 |
-
)
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
def _mock_microsoft(monkeypatch, *, oid, email, name="Microsoft User"):
|
| 44 |
-
monkeypatch.setattr(
|
| 45 |
-
auth_router, "verify_microsoft_id_token",
|
| 46 |
-
lambda *a, **k: MicrosoftIdentity(
|
| 47 |
-
microsoft_id=oid, email=email, name=name, tenant_id="tenant-1"
|
| 48 |
-
),
|
| 49 |
-
raising=True,
|
| 50 |
-
)
|
| 51 |
-
|
| 52 |
-
|
| 53 |
def _google_login(client, **params):
|
| 54 |
return client.post("/api/auth/google", json={"credential": "tok"}, params=params)
|
| 55 |
|
| 56 |
|
| 57 |
-
def
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
return client.post("/api/auth/apple", json=body, params=params)
|
| 62 |
|
| 63 |
|
| 64 |
-
def
|
| 65 |
-
return client.post(
|
|
|
|
|
|
|
| 66 |
|
| 67 |
|
| 68 |
# Mirrors auth_identity._PROVIDER_ID_COLUMN — kept explicit so a new provider
|
| 69 |
-
# fails here loudly rather than silently writing the wrong column.
|
|
|
|
|
|
|
| 70 |
_ID_COLUMN = {
|
| 71 |
AuthProvider.GOOGLE: "google_id",
|
| 72 |
-
AuthProvider.APPLE: "apple_id",
|
| 73 |
-
AuthProvider.MICROSOFT: "microsoft_id",
|
| 74 |
}
|
| 75 |
|
| 76 |
|
| 77 |
-
def _make_user(db, *, email, provider, sub, **kw):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
user = User(
|
| 79 |
email=email, name="Existing", auth_provider=provider,
|
| 80 |
-
plan=kw.pop("plan", PlanTier.FREE), **
|
| 81 |
)
|
| 82 |
db.add(user)
|
| 83 |
db.commit()
|
|
@@ -87,57 +75,41 @@ def _make_user(db, *, email, provider, sub, **kw):
|
|
| 87 |
|
| 88 |
# ─── Rule 3: an email never yields a second account ─────────────────────────
|
| 89 |
|
| 90 |
-
def
|
| 91 |
-
client, db_session
|
| 92 |
):
|
| 93 |
-
|
| 94 |
-
db_session, email="dup@test.local", provider=AuthProvider.GOOGLE, sub="g-1"
|
| 95 |
-
)
|
| 96 |
-
_mock_apple(monkeypatch, sub="a-1", email="dup@test.local")
|
| 97 |
|
| 98 |
-
resp =
|
| 99 |
|
| 100 |
assert resp.status_code == 409
|
| 101 |
detail = resp.json()["detail"]
|
| 102 |
assert detail["code"] == "wrong_auth_provider"
|
| 103 |
assert detail["provider"] == "google"
|
| 104 |
assert detail["provider_label"] == "Google"
|
| 105 |
-
assert
|
| 106 |
-
|
| 107 |
-
# No second account, and the existing row is untouched.
|
| 108 |
-
assert db_session.query(User).filter_by(email="dup@test.local").count() == 1
|
| 109 |
-
db_session.refresh(existing)
|
| 110 |
-
assert existing.google_id == "g-1"
|
| 111 |
-
assert existing.apple_id is None
|
| 112 |
-
assert existing.auth_provider is AuthProvider.GOOGLE
|
| 113 |
|
| 114 |
|
| 115 |
-
def
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
)
|
| 119 |
-
_mock_google(monkeypatch, sub="g-2", email="dup2@test.local")
|
| 120 |
|
| 121 |
resp = _google_login(client)
|
| 122 |
|
| 123 |
assert resp.status_code == 409
|
| 124 |
detail = resp.json()["detail"]
|
| 125 |
-
assert detail["provider"] == "
|
| 126 |
-
assert detail["provider_label"] == "
|
| 127 |
-
|
| 128 |
-
# The pre-existing bug this guards: google_id must NOT be overwritten.
|
| 129 |
-
db_session.refresh(existing)
|
| 130 |
-
assert existing.google_id is None
|
| 131 |
-
assert existing.apple_id == "a-2"
|
| 132 |
-
assert db_session.query(User).filter_by(email="dup2@test.local").count() == 1
|
| 133 |
|
| 134 |
|
| 135 |
def test_email_match_is_case_insensitive(client, db_session, monkeypatch):
|
| 136 |
"""A mixed-case legacy row must still be found, or it would be duplicated."""
|
| 137 |
-
_make_user(db_session, email="MiXeD@test.local", provider=AuthProvider.
|
| 138 |
-
|
| 139 |
|
| 140 |
-
resp =
|
| 141 |
|
| 142 |
assert resp.status_code == 409
|
| 143 |
assert db_session.query(User).count() == 1
|
|
@@ -145,21 +117,20 @@ def test_email_match_is_case_insensitive(client, db_session, monkeypatch):
|
|
| 145 |
|
| 146 |
# ─── Rule 2: deleted account + wrong provider ───────────────────────────────
|
| 147 |
|
| 148 |
-
def
|
| 149 |
-
client, db_session
|
| 150 |
):
|
| 151 |
-
"""Wrong-provider outranks
|
|
|
|
| 152 |
_make_user(
|
| 153 |
db_session, email="gone@test.local", provider=AuthProvider.GOOGLE,
|
| 154 |
-
sub="g-
|
| 155 |
)
|
| 156 |
-
_mock_apple(monkeypatch, sub="a-4", email="gone@test.local")
|
| 157 |
|
| 158 |
-
resp =
|
| 159 |
|
| 160 |
-
assert resp.status_code == 409
|
| 161 |
detail = resp.json()["detail"]
|
| 162 |
-
assert detail["code"] == "wrong_auth_provider"
|
| 163 |
assert detail["provider"] == "google"
|
| 164 |
assert detail["deleted"] is True
|
| 165 |
|
|
@@ -167,89 +138,34 @@ def test_deleted_google_account__apple_login__409_with_deleted_flag(
|
|
| 167 |
def test_deleted_google_account__google_login__still_403_account_deleted(
|
| 168 |
client, db_session, monkeypatch
|
| 169 |
):
|
| 170 |
-
"""The correct provider keeps the existing reactivation flow."""
|
| 171 |
_make_user(
|
| 172 |
-
db_session, email="
|
| 173 |
-
sub="g-
|
| 174 |
)
|
| 175 |
-
_mock_google(monkeypatch, sub="g-
|
| 176 |
|
| 177 |
-
|
| 178 |
-
assert _google_login(client).json()["detail"] == "account_deleted"
|
| 179 |
|
| 180 |
-
resp =
|
| 181 |
-
assert resp.
|
| 182 |
-
assert resp.json()["user"]["auth_provider"] == "google"
|
| 183 |
|
| 184 |
|
| 185 |
-
def
|
|
|
|
|
|
|
| 186 |
user = _make_user(
|
| 187 |
-
db_session, email="
|
| 188 |
-
sub="
|
| 189 |
)
|
| 190 |
-
|
| 191 |
|
| 192 |
-
|
| 193 |
-
resp = _apple_login(client, reactivate="true")
|
| 194 |
|
| 195 |
assert resp.status_code == 200
|
| 196 |
db_session.refresh(user)
|
| 197 |
assert user.is_active is True
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
# ─── Apple sign-up specifics ────────────────────────────────────────────────
|
| 202 |
-
|
| 203 |
-
def test_apple_signup__creates_apple_bound_account(client, db_session, monkeypatch):
|
| 204 |
-
_mock_apple(monkeypatch, sub="a-new", email="fresh@test.local")
|
| 205 |
-
|
| 206 |
-
resp = _apple_login(client, user={"name": {"firstName": "Ada", "lastName": "Lovelace"}})
|
| 207 |
-
|
| 208 |
-
assert resp.status_code == 200
|
| 209 |
-
assert resp.json()["user"]["auth_provider"] == "apple"
|
| 210 |
-
user = db_session.query(User).filter_by(email="fresh@test.local").one()
|
| 211 |
-
assert user.auth_provider is AuthProvider.APPLE
|
| 212 |
-
assert user.apple_id == "a-new"
|
| 213 |
-
assert user.google_id is None
|
| 214 |
-
assert user.name == "Ada Lovelace"
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
def test_apple_relogin__does_not_clobber_name_with_email_stub(
|
| 218 |
-
client, db_session, monkeypatch
|
| 219 |
-
):
|
| 220 |
-
"""Apple sends the name only on first authorization; later logins must not
|
| 221 |
-
overwrite it with the email-derived placeholder."""
|
| 222 |
-
_mock_apple(monkeypatch, sub="a-name", email="ada@test.local")
|
| 223 |
-
_apple_login(client, user={"name": {"firstName": "Ada", "lastName": "Lovelace"}})
|
| 224 |
-
|
| 225 |
-
_apple_login(client) # second sign-in: no user payload
|
| 226 |
-
|
| 227 |
-
user = db_session.query(User).filter_by(email="ada@test.local").one()
|
| 228 |
-
assert user.name == "Ada Lovelace"
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
def test_apple_private_relay_email__rejected_and_no_account(
|
| 232 |
-
client, db_session, monkeypatch
|
| 233 |
-
):
|
| 234 |
-
_mock_apple(
|
| 235 |
-
monkeypatch, sub="a-priv",
|
| 236 |
-
email="abc123@privaterelay.appleid.com", private=True,
|
| 237 |
-
)
|
| 238 |
-
|
| 239 |
-
resp = _apple_login(client)
|
| 240 |
-
|
| 241 |
-
assert resp.status_code == 400
|
| 242 |
-
assert resp.json()["detail"] == "apple_private_email"
|
| 243 |
-
assert db_session.query(User).count() == 0
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
def test_apple_invalid_token__401(client, monkeypatch):
|
| 247 |
-
def _boom(*a, **k):
|
| 248 |
-
raise AppleAuthError("Invalid Apple token: signature mismatch")
|
| 249 |
-
|
| 250 |
-
monkeypatch.setattr(auth_router, "verify_apple_identity_token", _boom, raising=True)
|
| 251 |
-
|
| 252 |
-
assert _apple_login(client).status_code == 401
|
| 253 |
|
| 254 |
|
| 255 |
# ─── Google regression: nothing about the existing flow changed ─────────────
|
|
@@ -265,7 +181,7 @@ def test_google_signup__still_works_and_reports_provider(client, db_session, mon
|
|
| 265 |
assert body["user"]["auth_provider"] == "google"
|
| 266 |
user = db_session.query(User).filter_by(email="newgoogle@test.local").one()
|
| 267 |
assert user.google_id == "g-new"
|
| 268 |
-
assert user.
|
| 269 |
assert user.auth_provider is AuthProvider.GOOGLE
|
| 270 |
|
| 271 |
|
|
@@ -280,6 +196,22 @@ def test_google_relogin__same_account_no_duplicate(client, db_session, monkeypat
|
|
| 280 |
assert db_session.query(User).filter_by(email="repeat@test.local").count() == 1
|
| 281 |
|
| 282 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 283 |
def test_same_provider_new_subject_id__rebinds_instead_of_duplicating(
|
| 284 |
client, db_session, monkeypatch
|
| 285 |
):
|
|
@@ -297,6 +229,24 @@ def test_same_provider_new_subject_id__rebinds_instead_of_duplicating(
|
|
| 297 |
assert db_session.query(User).filter_by(email="reissue@test.local").count() == 1
|
| 298 |
|
| 299 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 300 |
# ─── Concurrency ────────────────────────────────────────────────────────────
|
| 301 |
|
| 302 |
def test_concurrent_signup_race__resolves_instead_of_500(
|
|
@@ -331,235 +281,3 @@ def test_concurrent_signup_race__resolves_instead_of_500(
|
|
| 331 |
|
| 332 |
assert resp.status_code == 200
|
| 333 |
assert db_session.query(User).filter_by(email="race@test.local").count() == 1
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
# ─── Microsoft ──────────────────────────────────────────────────────────────
|
| 337 |
-
|
| 338 |
-
def test_microsoft_signup__creates_microsoft_bound_account(
|
| 339 |
-
client, db_session, monkeypatch
|
| 340 |
-
):
|
| 341 |
-
_mock_microsoft(monkeypatch, oid="ms-new", email="new@outlook.com", name="Grace H")
|
| 342 |
-
|
| 343 |
-
resp = _microsoft_login(client)
|
| 344 |
-
|
| 345 |
-
assert resp.status_code == 200
|
| 346 |
-
assert resp.json()["user"]["auth_provider"] == "microsoft"
|
| 347 |
-
user = db_session.query(User).filter_by(email="new@outlook.com").one()
|
| 348 |
-
assert user.auth_provider is AuthProvider.MICROSOFT
|
| 349 |
-
assert user.microsoft_id == "ms-new"
|
| 350 |
-
assert user.google_id is None
|
| 351 |
-
assert user.apple_id is None
|
| 352 |
-
assert user.name == "Grace H"
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
def test_google_account__microsoft_login_same_email__409_and_no_new_account(
|
| 356 |
-
client, db_session, monkeypatch
|
| 357 |
-
):
|
| 358 |
-
existing = _make_user(
|
| 359 |
-
db_session, email="dup-ms@test.local", provider=AuthProvider.GOOGLE, sub="g-ms"
|
| 360 |
-
)
|
| 361 |
-
_mock_microsoft(monkeypatch, oid="ms-1", email="dup-ms@test.local")
|
| 362 |
-
|
| 363 |
-
resp = _microsoft_login(client)
|
| 364 |
-
|
| 365 |
-
assert resp.status_code == 409
|
| 366 |
-
detail = resp.json()["detail"]
|
| 367 |
-
assert detail["code"] == "wrong_auth_provider"
|
| 368 |
-
assert detail["provider"] == "google"
|
| 369 |
-
assert detail["provider_label"] == "Google"
|
| 370 |
-
assert detail["deleted"] is False
|
| 371 |
-
|
| 372 |
-
assert db_session.query(User).filter_by(email="dup-ms@test.local").count() == 1
|
| 373 |
-
db_session.refresh(existing)
|
| 374 |
-
assert existing.google_id == "g-ms"
|
| 375 |
-
assert existing.microsoft_id is None
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
def test_microsoft_account__google_login_same_email__409_labels_microsoft(
|
| 379 |
-
client, db_session, monkeypatch
|
| 380 |
-
):
|
| 381 |
-
"""Guards the AuthProvider.label mapping.
|
| 382 |
-
|
| 383 |
-
A two-way ternary would mislabel Microsoft as "Apple" here, telling the user
|
| 384 |
-
to sign in with a provider that does not own their account.
|
| 385 |
-
"""
|
| 386 |
-
existing = _make_user(
|
| 387 |
-
db_session, email="ms-owner@test.local", provider=AuthProvider.MICROSOFT, sub="ms-2"
|
| 388 |
-
)
|
| 389 |
-
_mock_google(monkeypatch, sub="g-2b", email="ms-owner@test.local")
|
| 390 |
-
|
| 391 |
-
resp = _google_login(client)
|
| 392 |
-
|
| 393 |
-
assert resp.status_code == 409
|
| 394 |
-
detail = resp.json()["detail"]
|
| 395 |
-
assert detail["provider"] == "microsoft"
|
| 396 |
-
assert detail["provider_label"] == "Microsoft"
|
| 397 |
-
|
| 398 |
-
db_session.refresh(existing)
|
| 399 |
-
assert existing.google_id is None
|
| 400 |
-
assert existing.microsoft_id == "ms-2"
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
def test_microsoft_and_apple__reject_each_other(client, db_session, monkeypatch):
|
| 404 |
-
_make_user(
|
| 405 |
-
db_session, email="cross@test.local", provider=AuthProvider.APPLE, sub="a-x"
|
| 406 |
-
)
|
| 407 |
-
_mock_microsoft(monkeypatch, oid="ms-x", email="cross@test.local")
|
| 408 |
-
resp = _microsoft_login(client)
|
| 409 |
-
assert resp.status_code == 409
|
| 410 |
-
assert resp.json()["detail"]["provider_label"] == "Apple"
|
| 411 |
-
|
| 412 |
-
_make_user(
|
| 413 |
-
db_session, email="cross2@test.local", provider=AuthProvider.MICROSOFT, sub="ms-y"
|
| 414 |
-
)
|
| 415 |
-
_mock_apple(monkeypatch, sub="a-y", email="cross2@test.local")
|
| 416 |
-
resp = _apple_login(client)
|
| 417 |
-
assert resp.status_code == 409
|
| 418 |
-
assert resp.json()["detail"]["provider_label"] == "Microsoft"
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
def test_deleted_google_account__microsoft_login__409_with_deleted_flag(
|
| 422 |
-
client, db_session, monkeypatch
|
| 423 |
-
):
|
| 424 |
-
"""Wrong-provider outranks account_deleted, for the new provider too."""
|
| 425 |
-
_make_user(
|
| 426 |
-
db_session, email="gone-ms@test.local", provider=AuthProvider.GOOGLE,
|
| 427 |
-
sub="g-gone-ms", is_active=False,
|
| 428 |
-
)
|
| 429 |
-
_mock_microsoft(monkeypatch, oid="ms-gone", email="gone-ms@test.local")
|
| 430 |
-
|
| 431 |
-
resp = _microsoft_login(client)
|
| 432 |
-
|
| 433 |
-
assert resp.status_code == 409 # NOT 403 account_deleted
|
| 434 |
-
detail = resp.json()["detail"]
|
| 435 |
-
assert detail["provider"] == "google"
|
| 436 |
-
assert detail["deleted"] is True
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
def test_deleted_microsoft_account__microsoft_login_reactivates(
|
| 440 |
-
client, db_session, monkeypatch
|
| 441 |
-
):
|
| 442 |
-
user = _make_user(
|
| 443 |
-
db_session, email="ms-dead@test.local", provider=AuthProvider.MICROSOFT,
|
| 444 |
-
sub="ms-dead", is_active=False, plan=PlanTier.PRO,
|
| 445 |
-
)
|
| 446 |
-
_mock_microsoft(monkeypatch, oid="ms-dead", email="ms-dead@test.local")
|
| 447 |
-
|
| 448 |
-
assert _microsoft_login(client).status_code == 403
|
| 449 |
-
resp = _microsoft_login(client, reactivate="true")
|
| 450 |
-
|
| 451 |
-
assert resp.status_code == 200
|
| 452 |
-
db_session.refresh(user)
|
| 453 |
-
assert user.is_active is True
|
| 454 |
-
assert user.plan == PlanTier.FREE
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
def test_microsoft_relogin__same_account_no_duplicate(client, db_session, monkeypatch):
|
| 458 |
-
_mock_microsoft(monkeypatch, oid="ms-rep", email="repeat-ms@test.local")
|
| 459 |
-
|
| 460 |
-
first = _microsoft_login(client)
|
| 461 |
-
second = _microsoft_login(client)
|
| 462 |
-
|
| 463 |
-
assert first.status_code == second.status_code == 200
|
| 464 |
-
assert first.json()["user"]["id"] == second.json()["user"]["id"]
|
| 465 |
-
assert db_session.query(User).filter_by(email="repeat-ms@test.local").count() == 1
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
def test_microsoft_no_email__400_and_no_account(client, db_session, monkeypatch):
|
| 469 |
-
def _boom(*a, **k):
|
| 470 |
-
raise MicrosoftNoEmailError("Email not provided by Microsoft")
|
| 471 |
-
|
| 472 |
-
monkeypatch.setattr(auth_router, "verify_microsoft_id_token", _boom, raising=True)
|
| 473 |
-
|
| 474 |
-
resp = _microsoft_login(client)
|
| 475 |
-
|
| 476 |
-
assert resp.status_code == 400
|
| 477 |
-
assert resp.json()["detail"] == "microsoft_no_email"
|
| 478 |
-
assert db_session.query(User).count() == 0
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
def test_microsoft_invalid_token__401(client, monkeypatch):
|
| 482 |
-
def _boom(*a, **k):
|
| 483 |
-
raise MicrosoftAuthError("Invalid Microsoft token: signature mismatch")
|
| 484 |
-
|
| 485 |
-
monkeypatch.setattr(auth_router, "verify_microsoft_id_token", _boom, raising=True)
|
| 486 |
-
|
| 487 |
-
assert _microsoft_login(client).status_code == 401
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
# ─── Microsoft token verification (claim handling) ──────────────────────────
|
| 491 |
-
# These exercise microsoft_auth directly rather than through the router, since
|
| 492 |
-
# the router tests mock verification out.
|
| 493 |
-
|
| 494 |
-
def _ms_claims(**over):
|
| 495 |
-
base = {
|
| 496 |
-
"oid": "oid-1", "sub": "sub-1", "tid": "tenant-1",
|
| 497 |
-
"iss": "https://login.microsoftonline.com/tenant-1/v2.0",
|
| 498 |
-
"aud": "test-client", "exp": 9999999999,
|
| 499 |
-
"email": "person@outlook.com", "name": "A Person",
|
| 500 |
-
}
|
| 501 |
-
base.update(over)
|
| 502 |
-
return base
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
def _verify_with(monkeypatch, claims, client_id="test-client"):
|
| 506 |
-
"""Drive verify_microsoft_id_token with decode/JWKS stubbed out."""
|
| 507 |
-
import app.services.microsoft_auth as ms
|
| 508 |
-
from app.config import settings
|
| 509 |
-
|
| 510 |
-
monkeypatch.setattr(settings, "MICROSOFT_CLIENT_ID", client_id, raising=False)
|
| 511 |
-
monkeypatch.setattr(ms, "_signing_key_for", lambda *a, **k: type("K", (), {"key": "k"})(), raising=True)
|
| 512 |
-
monkeypatch.setattr(ms.jwt, "decode", lambda *a, **k: claims, raising=True)
|
| 513 |
-
return ms.verify_microsoft_id_token("tok")
|
| 514 |
-
|
| 515 |
-
|
| 516 |
-
def test_verify__prefers_oid_over_sub(monkeypatch):
|
| 517 |
-
identity = _verify_with(monkeypatch, _ms_claims())
|
| 518 |
-
# `sub` is pairwise per-app and changes if the registration is recreated.
|
| 519 |
-
assert identity.microsoft_id == "oid-1"
|
| 520 |
-
|
| 521 |
-
|
| 522 |
-
def test_verify__falls_back_to_sub_when_oid_absent(monkeypatch):
|
| 523 |
-
claims = _ms_claims()
|
| 524 |
-
del claims["oid"]
|
| 525 |
-
assert _verify_with(monkeypatch, claims).microsoft_id == "sub-1"
|
| 526 |
-
|
| 527 |
-
|
| 528 |
-
def test_verify__issuer_must_match_token_tenant(monkeypatch):
|
| 529 |
-
# Well-formed token from an unrelated tenant: iss and tid disagree.
|
| 530 |
-
claims = _ms_claims(iss="https://login.microsoftonline.com/other-tenant/v2.0")
|
| 531 |
-
with pytest.raises(MicrosoftAuthError, match="issuer"):
|
| 532 |
-
_verify_with(monkeypatch, claims)
|
| 533 |
-
|
| 534 |
-
|
| 535 |
-
def test_verify__org_tenant_issuer_accepted(monkeypatch):
|
| 536 |
-
# Any tenant is fine as long as iss matches that tenant — this is what
|
| 537 |
-
# makes work/school accounts work under the "common" endpoint.
|
| 538 |
-
claims = _ms_claims(tid="contoso", iss="https://login.microsoftonline.com/contoso/v2.0")
|
| 539 |
-
assert _verify_with(monkeypatch, claims).tenant_id == "contoso"
|
| 540 |
-
|
| 541 |
-
|
| 542 |
-
def test_verify__uses_preferred_username_when_email_missing(monkeypatch):
|
| 543 |
-
claims = _ms_claims(preferred_username="Work.User@contoso.com")
|
| 544 |
-
del claims["email"]
|
| 545 |
-
assert _verify_with(monkeypatch, claims).email == "work.user@contoso.com"
|
| 546 |
-
|
| 547 |
-
|
| 548 |
-
def test_verify__rejects_non_email_upn(monkeypatch):
|
| 549 |
-
# A UPN that isn't email-shaped is not a deliverable address.
|
| 550 |
-
claims = _ms_claims(preferred_username="DOMAIN\\user")
|
| 551 |
-
del claims["email"]
|
| 552 |
-
with pytest.raises(MicrosoftNoEmailError):
|
| 553 |
-
_verify_with(monkeypatch, claims)
|
| 554 |
-
|
| 555 |
-
|
| 556 |
-
def test_verify__rejects_when_no_email_claims_at_all(monkeypatch):
|
| 557 |
-
claims = _ms_claims()
|
| 558 |
-
del claims["email"]
|
| 559 |
-
with pytest.raises(MicrosoftNoEmailError):
|
| 560 |
-
_verify_with(monkeypatch, claims)
|
| 561 |
-
|
| 562 |
-
|
| 563 |
-
def test_verify__unconfigured_client_id_fails_closed(monkeypatch):
|
| 564 |
-
with pytest.raises(MicrosoftAuthError, match="not configured"):
|
| 565 |
-
_verify_with(monkeypatch, _ms_claims(), client_id="")
|
|
|
|
| 1 |
"""
|
| 2 |
+
Depth tier — multi-provider identity rules (Google + built-in email/password).
|
| 3 |
|
| 4 |
The invariant under test: one account per email, forever, bound for life to the
|
| 5 |
provider that created it. A second provider presenting a known email is always
|
| 6 |
rejected (409 wrong_auth_provider) — never linked, never duplicated — and that
|
| 7 |
rejection outranks the soft-delete/reactivation prompt.
|
| 8 |
+
|
| 9 |
+
Apple and Microsoft sign-in were removed (see the drop_apple_microsoft_auth
|
| 10 |
+
migration), so the cross-provider cases here run Google against our own
|
| 11 |
+
email/password provider — the only pair that still exists. The rules themselves
|
| 12 |
+
are provider-agnostic and live in services/auth_identity.py.
|
| 13 |
"""
|
| 14 |
import pytest
|
| 15 |
|
| 16 |
import app.routers.auth as auth_router
|
| 17 |
from app.models.user import AuthProvider, PlanTier, User
|
| 18 |
+
from app.services.password import hash_password
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
pytestmark = pytest.mark.depth
|
| 21 |
|
| 22 |
+
PASSWORD = "Correct-Horse-1"
|
| 23 |
+
|
| 24 |
|
| 25 |
# ─── Helpers ────────────────────────────────────────────────────────────────
|
| 26 |
|
|
|
|
| 32 |
)
|
| 33 |
|
| 34 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
def _google_login(client, **params):
|
| 36 |
return client.post("/api/auth/google", json={"credential": "tok"}, params=params)
|
| 37 |
|
| 38 |
|
| 39 |
+
def _email_login(client, email, password=PASSWORD, **params):
|
| 40 |
+
return client.post(
|
| 41 |
+
"/api/auth/email/login", json={"email": email, "password": password}, params=params
|
| 42 |
+
)
|
|
|
|
| 43 |
|
| 44 |
|
| 45 |
+
def _email_register_start(client, email, password=PASSWORD):
|
| 46 |
+
return client.post(
|
| 47 |
+
"/api/auth/email/register/start", json={"email": email, "password": password}
|
| 48 |
+
)
|
| 49 |
|
| 50 |
|
| 51 |
# Mirrors auth_identity._PROVIDER_ID_COLUMN — kept explicit so a new provider
|
| 52 |
+
# fails here loudly rather than silently writing the wrong column. EMAIL is
|
| 53 |
+
# absent on purpose: it has no external subject id, its credential is
|
| 54 |
+
# password_hash.
|
| 55 |
_ID_COLUMN = {
|
| 56 |
AuthProvider.GOOGLE: "google_id",
|
|
|
|
|
|
|
| 57 |
}
|
| 58 |
|
| 59 |
|
| 60 |
+
def _make_user(db, *, email, provider, sub=None, **kw):
|
| 61 |
+
ident = (
|
| 62 |
+
{_ID_COLUMN[provider]: sub}
|
| 63 |
+
if provider in _ID_COLUMN
|
| 64 |
+
else {"password_hash": hash_password(kw.pop("password", PASSWORD))}
|
| 65 |
+
)
|
| 66 |
user = User(
|
| 67 |
email=email, name="Existing", auth_provider=provider,
|
| 68 |
+
plan=kw.pop("plan", PlanTier.FREE), **ident, **kw,
|
| 69 |
)
|
| 70 |
db.add(user)
|
| 71 |
db.commit()
|
|
|
|
| 75 |
|
| 76 |
# ─── Rule 3: an email never yields a second account ─────────────────────────
|
| 77 |
|
| 78 |
+
def test_google_account__email_signup_same_email__409_and_no_new_account(
|
| 79 |
+
client, db_session
|
| 80 |
):
|
| 81 |
+
_make_user(db_session, email="taken@test.local", provider=AuthProvider.GOOGLE, sub="g-1")
|
|
|
|
|
|
|
|
|
|
| 82 |
|
| 83 |
+
resp = _email_register_start(client, "taken@test.local")
|
| 84 |
|
| 85 |
assert resp.status_code == 409
|
| 86 |
detail = resp.json()["detail"]
|
| 87 |
assert detail["code"] == "wrong_auth_provider"
|
| 88 |
assert detail["provider"] == "google"
|
| 89 |
assert detail["provider_label"] == "Google"
|
| 90 |
+
assert db_session.query(User).count() == 1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
|
| 92 |
|
| 93 |
+
def test_email_account__google_login_same_email__409(client, db_session, monkeypatch):
|
| 94 |
+
"""The mirror image: a password account is not signed into with Google."""
|
| 95 |
+
_make_user(db_session, email="mine@test.local", provider=AuthProvider.EMAIL)
|
| 96 |
+
_mock_google(monkeypatch, sub="g-2", email="mine@test.local")
|
|
|
|
| 97 |
|
| 98 |
resp = _google_login(client)
|
| 99 |
|
| 100 |
assert resp.status_code == 409
|
| 101 |
detail = resp.json()["detail"]
|
| 102 |
+
assert detail["provider"] == "email"
|
| 103 |
+
assert detail["provider_label"] == "Email"
|
| 104 |
+
assert db_session.query(User).count() == 1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
|
| 106 |
|
| 107 |
def test_email_match_is_case_insensitive(client, db_session, monkeypatch):
|
| 108 |
"""A mixed-case legacy row must still be found, or it would be duplicated."""
|
| 109 |
+
_make_user(db_session, email="MiXeD@test.local", provider=AuthProvider.EMAIL)
|
| 110 |
+
_mock_google(monkeypatch, sub="g-3", email="mixed@test.local")
|
| 111 |
|
| 112 |
+
resp = _google_login(client)
|
| 113 |
|
| 114 |
assert resp.status_code == 409
|
| 115 |
assert db_session.query(User).count() == 1
|
|
|
|
| 117 |
|
| 118 |
# ─── Rule 2: deleted account + wrong provider ───────────────────────────────
|
| 119 |
|
| 120 |
+
def test_deleted_google_account__email_signup__409_with_deleted_flag(
|
| 121 |
+
client, db_session
|
| 122 |
):
|
| 123 |
+
"""Wrong-provider outranks the deletion prompt, and says so — otherwise the
|
| 124 |
+
user is offered a reactivation they cannot complete on this provider."""
|
| 125 |
_make_user(
|
| 126 |
db_session, email="gone@test.local", provider=AuthProvider.GOOGLE,
|
| 127 |
+
sub="g-gone", is_active=False,
|
| 128 |
)
|
|
|
|
| 129 |
|
| 130 |
+
resp = _email_register_start(client, "gone@test.local")
|
| 131 |
|
| 132 |
+
assert resp.status_code == 409
|
| 133 |
detail = resp.json()["detail"]
|
|
|
|
| 134 |
assert detail["provider"] == "google"
|
| 135 |
assert detail["deleted"] is True
|
| 136 |
|
|
|
|
| 138 |
def test_deleted_google_account__google_login__still_403_account_deleted(
|
| 139 |
client, db_session, monkeypatch
|
| 140 |
):
|
|
|
|
| 141 |
_make_user(
|
| 142 |
+
db_session, email="back@test.local", provider=AuthProvider.GOOGLE,
|
| 143 |
+
sub="g-back", is_active=False,
|
| 144 |
)
|
| 145 |
+
_mock_google(monkeypatch, sub="g-back", email="back@test.local")
|
| 146 |
|
| 147 |
+
resp = _google_login(client)
|
|
|
|
| 148 |
|
| 149 |
+
assert resp.status_code == 403
|
| 150 |
+
assert resp.json()["detail"] == "account_deleted"
|
|
|
|
| 151 |
|
| 152 |
|
| 153 |
+
def test_deleted_google_account__google_login_reactivates(
|
| 154 |
+
client, db_session, monkeypatch
|
| 155 |
+
):
|
| 156 |
user = _make_user(
|
| 157 |
+
db_session, email="revive@test.local", provider=AuthProvider.GOOGLE,
|
| 158 |
+
sub="g-revive", is_active=False, plan=PlanTier.PRO,
|
| 159 |
)
|
| 160 |
+
_mock_google(monkeypatch, sub="g-revive", email="revive@test.local")
|
| 161 |
|
| 162 |
+
resp = _google_login(client, reactivate=True)
|
|
|
|
| 163 |
|
| 164 |
assert resp.status_code == 200
|
| 165 |
db_session.refresh(user)
|
| 166 |
assert user.is_active is True
|
| 167 |
+
# Reactivation is always as a FREE user.
|
| 168 |
+
assert user.plan is PlanTier.FREE
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
|
| 170 |
|
| 171 |
# ─── Google regression: nothing about the existing flow changed ─────────────
|
|
|
|
| 181 |
assert body["user"]["auth_provider"] == "google"
|
| 182 |
user = db_session.query(User).filter_by(email="newgoogle@test.local").one()
|
| 183 |
assert user.google_id == "g-new"
|
| 184 |
+
assert user.password_hash is None
|
| 185 |
assert user.auth_provider is AuthProvider.GOOGLE
|
| 186 |
|
| 187 |
|
|
|
|
| 196 |
assert db_session.query(User).filter_by(email="repeat@test.local").count() == 1
|
| 197 |
|
| 198 |
|
| 199 |
+
def test_google_relogin__refreshes_name_from_the_provider(
|
| 200 |
+
client, db_session, monkeypatch
|
| 201 |
+
):
|
| 202 |
+
"""Google sends name and picture on every sign-in and is authoritative for
|
| 203 |
+
them, so a changed profile name lands on the row."""
|
| 204 |
+
user = _make_user(
|
| 205 |
+
db_session, email="renamed@test.local", provider=AuthProvider.GOOGLE, sub="g-rename"
|
| 206 |
+
)
|
| 207 |
+
_mock_google(monkeypatch, sub="g-rename", email="renamed@test.local", name="New Name")
|
| 208 |
+
|
| 209 |
+
assert _google_login(client).status_code == 200
|
| 210 |
+
|
| 211 |
+
db_session.refresh(user)
|
| 212 |
+
assert user.name == "New Name"
|
| 213 |
+
|
| 214 |
+
|
| 215 |
def test_same_provider_new_subject_id__rebinds_instead_of_duplicating(
|
| 216 |
client, db_session, monkeypatch
|
| 217 |
):
|
|
|
|
| 229 |
assert db_session.query(User).filter_by(email="reissue@test.local").count() == 1
|
| 230 |
|
| 231 |
|
| 232 |
+
# ─── Removed providers ──────────────────────────────────────────────────────
|
| 233 |
+
|
| 234 |
+
@pytest.mark.parametrize("path", ["/api/auth/apple", "/api/auth/microsoft"])
|
| 235 |
+
def test_removed_provider_routes_are_gone(client, path):
|
| 236 |
+
"""Apple and Microsoft sign-in were removed; their routes must not linger."""
|
| 237 |
+
resp = client.post(path, json={"identity_token": "tok", "id_token": "tok"})
|
| 238 |
+
|
| 239 |
+
assert resp.status_code == 404
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
@pytest.mark.parametrize("value", ["apple", "microsoft"])
|
| 243 |
+
def test_removed_providers_are_not_valid_auth_provider_values(value):
|
| 244 |
+
"""The enum coerces on load, so a legacy row fails loudly rather than
|
| 245 |
+
silently degrading to a bare string."""
|
| 246 |
+
with pytest.raises(ValueError):
|
| 247 |
+
AuthProvider(value)
|
| 248 |
+
|
| 249 |
+
|
| 250 |
# ─── Concurrency ────────────────────────────────────────────────────────────
|
| 251 |
|
| 252 |
def test_concurrent_signup_race__resolves_instead_of_500(
|
|
|
|
| 281 |
|
| 282 |
assert resp.status_code == 200
|
| 283 |
assert db_session.query(User).filter_by(email="race@test.local").count() == 1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
backend/tests/test_email_password_auth.py
ADDED
|
@@ -0,0 +1,714 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Depth tier — built-in email/password auth.
|
| 3 |
+
|
| 4 |
+
Two invariants carry most of the weight here:
|
| 5 |
+
|
| 6 |
+
1. One account per email, across ALL four providers. A social-owned address is
|
| 7 |
+
rejected before a password is accepted, before a code is issued, and before
|
| 8 |
+
any mail is sent — a user whose address is a Google account learns that
|
| 9 |
+
immediately rather than after a round trip through their inbox.
|
| 10 |
+
2. A row in ``users`` always means a real, verified account. A pending signup
|
| 11 |
+
lives on a code row, never as an inactive user, so an abandoned registration
|
| 12 |
+
can neither squat the unique email nor masquerade as a deleted account.
|
| 13 |
+
"""
|
| 14 |
+
from datetime import datetime, timedelta
|
| 15 |
+
|
| 16 |
+
import pytest
|
| 17 |
+
|
| 18 |
+
import app.routers.auth as auth_router
|
| 19 |
+
from app.models.email_verification import EmailVerificationCode, VerificationPurpose
|
| 20 |
+
from app.models.user import AuthProvider, PlanTier, User
|
| 21 |
+
from app.services import rate_limit
|
| 22 |
+
from app.services.password import hash_password
|
| 23 |
+
|
| 24 |
+
pytestmark = pytest.mark.depth
|
| 25 |
+
|
| 26 |
+
CODE = "123456"
|
| 27 |
+
PASSWORD = "Correct-Horse-1"
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
# ─── Fixtures & helpers ─────────────────────────────────────────────────────
|
| 31 |
+
|
| 32 |
+
@pytest.fixture(autouse=True)
|
| 33 |
+
def _fixed_code(monkeypatch):
|
| 34 |
+
"""Pin the generated code and clear limiter state between tests.
|
| 35 |
+
|
| 36 |
+
The limiters are module-level singletons, so without the reset a test that
|
| 37 |
+
trips a lockout silently breaks every later test sharing its key.
|
| 38 |
+
"""
|
| 39 |
+
monkeypatch.setattr(
|
| 40 |
+
auth_router.verification, "generate_code", lambda: CODE, raising=True
|
| 41 |
+
)
|
| 42 |
+
rate_limit.reset_all_limiters()
|
| 43 |
+
yield
|
| 44 |
+
rate_limit.reset_all_limiters()
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
@pytest.fixture()
|
| 48 |
+
def sent(monkeypatch):
|
| 49 |
+
"""Capture outgoing codes: list of (kind, email, code)."""
|
| 50 |
+
out: list[tuple[str, str, str]] = []
|
| 51 |
+
monkeypatch.setattr(
|
| 52 |
+
auth_router.email_service, "send_verification_code_email",
|
| 53 |
+
lambda to, code: out.append(("signup", to, code)), raising=True,
|
| 54 |
+
)
|
| 55 |
+
monkeypatch.setattr(
|
| 56 |
+
auth_router.email_service, "send_password_reset_code_email",
|
| 57 |
+
lambda to, code: out.append(("reset", to, code)), raising=True,
|
| 58 |
+
)
|
| 59 |
+
return out
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def _start(client, email, password=PASSWORD, **body):
|
| 63 |
+
return client.post(
|
| 64 |
+
"/api/auth/email/register/start",
|
| 65 |
+
json={"email": email, "password": password, **body},
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def _verify(client, email, code=CODE, **params):
|
| 70 |
+
return client.post(
|
| 71 |
+
"/api/auth/email/register/verify", json={"email": email, "code": code}, params=params
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _login(client, email, password=PASSWORD, **params):
|
| 76 |
+
return client.post(
|
| 77 |
+
"/api/auth/email/login", json={"email": email, "password": password}, params=params
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _forgot_start(client, email, **params):
|
| 82 |
+
return client.post(
|
| 83 |
+
"/api/auth/password/forgot/start", json={"email": email}, params=params
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def _forgot_complete(client, email, new_password, code=CODE):
|
| 88 |
+
return client.post(
|
| 89 |
+
"/api/auth/password/forgot/complete",
|
| 90 |
+
json={"email": email, "code": code, "new_password": new_password},
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def _register(client, email, password=PASSWORD):
|
| 95 |
+
"""Complete a full signup, returning the auth response body."""
|
| 96 |
+
assert _start(client, email, password).status_code == 200
|
| 97 |
+
res = _verify(client, email)
|
| 98 |
+
assert res.status_code == 200, res.text
|
| 99 |
+
return res.json()
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def _make_social(db, *, email, provider, **kw):
|
| 103 |
+
column = {AuthProvider.GOOGLE: "google_id"}[provider]
|
| 104 |
+
user = User(
|
| 105 |
+
email=email, name="Existing", auth_provider=provider,
|
| 106 |
+
plan=kw.pop("plan", PlanTier.FREE), is_active=kw.pop("is_active", True),
|
| 107 |
+
**{column: f"{provider.value}-sub"}, **kw,
|
| 108 |
+
)
|
| 109 |
+
db.add(user)
|
| 110 |
+
db.commit()
|
| 111 |
+
db.refresh(user)
|
| 112 |
+
return user
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def _make_email_user(db, *, email, password=PASSWORD, **kw):
|
| 116 |
+
user = User(
|
| 117 |
+
email=email, name="Email User", auth_provider=AuthProvider.EMAIL,
|
| 118 |
+
password_hash=hash_password(password),
|
| 119 |
+
plan=kw.pop("plan", PlanTier.FREE), is_active=kw.pop("is_active", True), **kw,
|
| 120 |
+
)
|
| 121 |
+
db.add(user)
|
| 122 |
+
db.commit()
|
| 123 |
+
db.refresh(user)
|
| 124 |
+
return user
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def _codes(db, email=None, purpose=None):
|
| 128 |
+
q = db.query(EmailVerificationCode)
|
| 129 |
+
if email:
|
| 130 |
+
q = q.filter(EmailVerificationCode.email == email)
|
| 131 |
+
if purpose:
|
| 132 |
+
q = q.filter(EmailVerificationCode.purpose == purpose.value)
|
| 133 |
+
return q.all()
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
# ─── One account per email, across providers ────────────────────────────────
|
| 137 |
+
|
| 138 |
+
@pytest.mark.parametrize("provider", [AuthProvider.GOOGLE])
|
| 139 |
+
def test_register_rejects_socially_owned_email_before_issuing_any_code(
|
| 140 |
+
client, db_session, sent, provider
|
| 141 |
+
):
|
| 142 |
+
"""The core guarantee: 409 lands with nothing issued and nothing sent."""
|
| 143 |
+
_make_social(db_session, email="taken@test.local", provider=provider)
|
| 144 |
+
|
| 145 |
+
res = _start(client, "taken@test.local")
|
| 146 |
+
|
| 147 |
+
assert res.status_code == 409
|
| 148 |
+
detail = res.json()["detail"]
|
| 149 |
+
assert detail["code"] == "wrong_auth_provider"
|
| 150 |
+
assert detail["provider"] == provider.value
|
| 151 |
+
assert sent == []
|
| 152 |
+
assert _codes(db_session, "taken@test.local") == []
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def test_register_start_does_not_hash_into_users_table(client, db_session, sent):
|
| 156 |
+
"""No user row exists between start and verify — Decision B's invariant."""
|
| 157 |
+
assert _start(client, "pending@test.local").status_code == 200
|
| 158 |
+
|
| 159 |
+
assert db_session.query(User).filter_by(email="pending@test.local").first() is None
|
| 160 |
+
codes = _codes(db_session, "pending@test.local", VerificationPurpose.SIGNUP)
|
| 161 |
+
assert len(codes) == 1
|
| 162 |
+
# The password is present but hashed, and the code is not stored in the clear.
|
| 163 |
+
assert codes[0].pending_password_hash.startswith("$argon2")
|
| 164 |
+
assert codes[0].code_hash != CODE
|
| 165 |
+
assert sent == [("signup", "pending@test.local", CODE)]
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def test_social_login_rejects_email_owned_address(client, db_session, monkeypatch):
|
| 169 |
+
"""The rule holds in the other direction: social login onto an email account."""
|
| 170 |
+
_make_email_user(db_session, email="mine@test.local")
|
| 171 |
+
|
| 172 |
+
monkeypatch.setattr(
|
| 173 |
+
auth_router.id_token, "verify_oauth2_token",
|
| 174 |
+
lambda *a, **k: {"sub": "g1", "email": "mine@test.local", "name": "G"},
|
| 175 |
+
raising=True,
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
res = client.post("/api/auth/google", json={"credential": "tok"})
|
| 179 |
+
|
| 180 |
+
assert res.status_code == 409
|
| 181 |
+
detail = res.json()["detail"]
|
| 182 |
+
assert detail["provider"] == "email"
|
| 183 |
+
assert detail["provider_label"] == "Email"
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def test_email_matching_is_case_insensitive(client, db_session, sent):
|
| 187 |
+
_register(client, "mixed@test.local")
|
| 188 |
+
|
| 189 |
+
assert _start(client, "MIXED@Test.Local").status_code == 409
|
| 190 |
+
assert _login(client, "MIXED@Test.Local").status_code == 200
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def test_forgot_rejects_socially_owned_email(client, db_session, sent):
|
| 194 |
+
_make_social(db_session, email="g@test.local", provider=AuthProvider.GOOGLE)
|
| 195 |
+
|
| 196 |
+
res = _forgot_start(client, "g@test.local")
|
| 197 |
+
|
| 198 |
+
assert res.status_code == 409
|
| 199 |
+
assert res.json()["detail"]["provider"] == "google"
|
| 200 |
+
assert sent == []
|
| 201 |
+
assert _codes(db_session, "g@test.local") == []
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
# ─── Registration ───────────────────────────────────────────────────────────
|
| 205 |
+
|
| 206 |
+
def test_register_happy_path_creates_verified_account(client, db_session, sent):
|
| 207 |
+
data = _register(client, "new@test.local")
|
| 208 |
+
|
| 209 |
+
assert data["access_token"]
|
| 210 |
+
assert data["user"]["auth_provider"] == "email"
|
| 211 |
+
user = db_session.query(User).filter_by(email="new@test.local").one()
|
| 212 |
+
assert user.is_active is True
|
| 213 |
+
assert user.password_hash and user.password_hash != PASSWORD
|
| 214 |
+
# The code row is spent, not left behind.
|
| 215 |
+
assert _codes(db_session, "new@test.local") == []
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
@pytest.mark.parametrize(
|
| 219 |
+
"password,expected",
|
| 220 |
+
[
|
| 221 |
+
("abc1234", "password_too_short"), # 7 chars
|
| 222 |
+
("Ab1!", "password_too_short"), # short wins over the rest
|
| 223 |
+
("lowercase-only-1", "password_needs_uppercase"),
|
| 224 |
+
("NoSymbolsHere123", "password_needs_special"),
|
| 225 |
+
],
|
| 226 |
+
)
|
| 227 |
+
def test_register_rejects_policy_violations_without_issuing_a_code(
|
| 228 |
+
client, db_session, sent, password, expected
|
| 229 |
+
):
|
| 230 |
+
"""Every policy failure is rejected before a code is issued or mail is sent."""
|
| 231 |
+
res = _start(client, "policy@test.local", password=password)
|
| 232 |
+
|
| 233 |
+
assert res.status_code == 422
|
| 234 |
+
assert res.json()["detail"] == expected
|
| 235 |
+
assert sent == []
|
| 236 |
+
assert _codes(db_session, "policy@test.local") == []
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def test_login_never_applies_the_password_policy(client, db_session):
|
| 240 |
+
"""A stored password that breaks the CURRENT rules must still sign in.
|
| 241 |
+
|
| 242 |
+
Policy governs passwords being set, never ones being used. If sign-in
|
| 243 |
+
re-validated, adding a rule would lock every existing user out of their own
|
| 244 |
+
account — so this guards the one thing a future "tighten the policy" change
|
| 245 |
+
is most likely to break.
|
| 246 |
+
"""
|
| 247 |
+
_make_email_user(db_session, email="legacy@test.local", password="allsmall-nosymbol")
|
| 248 |
+
|
| 249 |
+
assert _login(client, "legacy@test.local", password="allsmall-nosymbol").status_code == 200
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def test_forgot_complete_enforces_the_full_policy(client, db_session, sent):
|
| 253 |
+
"""The reset path sets a password, so it gets the same rules as signup."""
|
| 254 |
+
_make_email_user(db_session, email="weak@test.local")
|
| 255 |
+
assert _forgot_start(client, "weak@test.local").status_code == 200
|
| 256 |
+
|
| 257 |
+
res = _forgot_complete(client, "weak@test.local", "nocapitals-or-symbols1")
|
| 258 |
+
|
| 259 |
+
assert res.status_code == 422
|
| 260 |
+
assert res.json()["detail"] == "password_needs_uppercase"
|
| 261 |
+
# The old password still works — a rejected reset changes nothing.
|
| 262 |
+
assert _login(client, "weak@test.local").status_code == 200
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def test_register_start_on_existing_email_account_conflicts(client, db_session, sent):
|
| 266 |
+
_register(client, "dupe@test.local")
|
| 267 |
+
sent.clear()
|
| 268 |
+
|
| 269 |
+
res = _start(client, "dupe@test.local")
|
| 270 |
+
|
| 271 |
+
assert res.status_code == 409
|
| 272 |
+
assert res.json()["detail"]["code"] == "email_already_registered"
|
| 273 |
+
assert sent == []
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
@pytest.mark.parametrize(
|
| 277 |
+
"password",
|
| 278 |
+
["short", "nouppercase-1!", "NoSpecialChar1"],
|
| 279 |
+
ids=["too_short", "no_uppercase", "no_special"],
|
| 280 |
+
)
|
| 281 |
+
def test_existing_account_outranks_the_password_policy(
|
| 282 |
+
client, db_session, sent, password
|
| 283 |
+
):
|
| 284 |
+
"""An address that already has an account answers 409, whatever was typed.
|
| 285 |
+
|
| 286 |
+
Checking the policy first would tell someone to fix a password they are never
|
| 287 |
+
going to use, on a form they should not be on — and hides the one fact that
|
| 288 |
+
actually helps them ("you already have an account, sign in"). The client
|
| 289 |
+
relies on this: it stops gating submit on the policy so a wrong password on
|
| 290 |
+
the signup form still surfaces the existing account instead of doing nothing.
|
| 291 |
+
|
| 292 |
+
The one case NOT covered here is an over-length password: _PasswordField caps
|
| 293 |
+
it at 512 chars, so pydantic rejects the body with a 422 before the handler
|
| 294 |
+
runs. That bound is deliberately left in front — it costs no DB work and no
|
| 295 |
+
real user types 512 characters into a login box.
|
| 296 |
+
"""
|
| 297 |
+
_make_email_user(db_session, email="exists@test.local")
|
| 298 |
+
|
| 299 |
+
res = _start(client, "exists@test.local", password=password)
|
| 300 |
+
|
| 301 |
+
assert res.status_code == 409
|
| 302 |
+
assert res.json()["detail"]["code"] == "email_already_registered"
|
| 303 |
+
assert sent == []
|
| 304 |
+
assert _codes(db_session, "exists@test.local") == []
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
def test_policy_still_applies_once_the_address_is_free(client, db_session, sent):
|
| 308 |
+
"""The reordering must not weaken the policy for real signups."""
|
| 309 |
+
res = _start(client, "brandnew@test.local", password="short")
|
| 310 |
+
|
| 311 |
+
assert res.status_code == 422
|
| 312 |
+
assert res.json()["detail"] == "password_too_short"
|
| 313 |
+
assert sent == []
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
def test_register_start_on_deleted_account_says_already_registered(
|
| 317 |
+
client, db_session, sent
|
| 318 |
+
):
|
| 319 |
+
"""Signup must NEVER surface reactivation.
|
| 320 |
+
|
| 321 |
+
A soft-deleted account answers exactly as a live one: reactivation is a
|
| 322 |
+
decision about an account you are signing in to, so a form headed "Create
|
| 323 |
+
your account" must not offer it. The login and password-reset flows own that
|
| 324 |
+
prompt, after the password (or a mailbox code) is proven.
|
| 325 |
+
"""
|
| 326 |
+
user = _make_email_user(db_session, email="deleted@test.local", is_active=False)
|
| 327 |
+
|
| 328 |
+
res = _start(client, "deleted@test.local")
|
| 329 |
+
|
| 330 |
+
assert res.status_code == 409
|
| 331 |
+
assert res.json()["detail"]["code"] == "email_already_registered"
|
| 332 |
+
assert "X-Account-Deleted" not in res.headers
|
| 333 |
+
assert sent == []
|
| 334 |
+
assert _codes(db_session, "deleted@test.local") == []
|
| 335 |
+
# And signup left the account exactly as deleted as it found it.
|
| 336 |
+
db_session.refresh(user)
|
| 337 |
+
assert user.is_active is False
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
def test_register_start_cannot_tell_deleted_from_live(client, db_session, sent):
|
| 341 |
+
"""The two responses are byte-identical, so this endpoint is not an oracle
|
| 342 |
+
for whether a known address is deleted or active."""
|
| 343 |
+
_make_email_user(db_session, email="live@test.local")
|
| 344 |
+
_make_email_user(db_session, email="dead@test.local", is_active=False)
|
| 345 |
+
|
| 346 |
+
live = _start(client, "live@test.local")
|
| 347 |
+
dead = _start(client, "dead@test.local")
|
| 348 |
+
|
| 349 |
+
assert live.status_code == dead.status_code == 409
|
| 350 |
+
assert live.json() == dead.json()
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
def test_wrong_code_burns_after_five_attempts(client, db_session, sent):
|
| 354 |
+
assert _start(client, "brute@test.local").status_code == 200
|
| 355 |
+
|
| 356 |
+
for expected_remaining in (4, 3, 2, 1):
|
| 357 |
+
res = _verify(client, "brute@test.local", code="000000")
|
| 358 |
+
assert res.status_code == 400
|
| 359 |
+
assert res.json()["detail"]["attempts_remaining"] == expected_remaining
|
| 360 |
+
|
| 361 |
+
res = _verify(client, "brute@test.local", code="000000")
|
| 362 |
+
assert res.status_code == 429
|
| 363 |
+
assert res.json()["detail"] == "code_attempts_exceeded"
|
| 364 |
+
# Burned: even the correct code is now worthless, and no account was made.
|
| 365 |
+
assert _codes(db_session, "brute@test.local") == []
|
| 366 |
+
assert _verify(client, "brute@test.local").status_code == 400
|
| 367 |
+
assert db_session.query(User).filter_by(email="brute@test.local").first() is None
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
def test_expired_code_is_rejected(client, db_session, sent):
|
| 371 |
+
assert _start(client, "slow@test.local").status_code == 200
|
| 372 |
+
row = _codes(db_session, "slow@test.local")[0]
|
| 373 |
+
row.expires_at = datetime.utcnow() - timedelta(seconds=1)
|
| 374 |
+
db_session.commit()
|
| 375 |
+
|
| 376 |
+
res = _verify(client, "slow@test.local")
|
| 377 |
+
|
| 378 |
+
assert res.status_code == 400
|
| 379 |
+
assert res.json()["detail"] == "code_expired"
|
| 380 |
+
assert db_session.query(User).filter_by(email="slow@test.local").first() is None
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
def test_resend_respects_cooldown_then_invalidates_the_old_code(client, db_session, sent):
|
| 384 |
+
assert _start(client, "resend@test.local").status_code == 200
|
| 385 |
+
old_hash = _codes(db_session, "resend@test.local")[0].code_hash
|
| 386 |
+
|
| 387 |
+
res = client.post("/api/auth/email/register/resend", json={"email": "resend@test.local"})
|
| 388 |
+
assert res.status_code == 429
|
| 389 |
+
assert res.json()["detail"] == "resend_too_soon"
|
| 390 |
+
assert int(res.headers["Retry-After"]) > 0
|
| 391 |
+
|
| 392 |
+
row = _codes(db_session, "resend@test.local")[0]
|
| 393 |
+
row.last_sent_at = datetime.utcnow() - timedelta(seconds=120)
|
| 394 |
+
db_session.commit()
|
| 395 |
+
|
| 396 |
+
# A different code this time, so we can prove the old one stopped working.
|
| 397 |
+
import app.services.email_verification as verification_mod
|
| 398 |
+
original = verification_mod.generate_code
|
| 399 |
+
verification_mod.generate_code = lambda: "654321"
|
| 400 |
+
try:
|
| 401 |
+
res = client.post(
|
| 402 |
+
"/api/auth/email/register/resend", json={"email": "resend@test.local"}
|
| 403 |
+
)
|
| 404 |
+
finally:
|
| 405 |
+
verification_mod.generate_code = original
|
| 406 |
+
|
| 407 |
+
assert res.status_code == 200
|
| 408 |
+
rows = _codes(db_session, "resend@test.local")
|
| 409 |
+
assert len(rows) == 1 and rows[0].code_hash != old_hash
|
| 410 |
+
# The password captured at start survives the resend — never re-asked for.
|
| 411 |
+
assert rows[0].pending_password_hash.startswith("$argon2")
|
| 412 |
+
|
| 413 |
+
|
| 414 |
+
def test_resend_without_pending_registration(client, db_session, sent):
|
| 415 |
+
res = client.post("/api/auth/email/register/resend", json={"email": "nobody@test.local"})
|
| 416 |
+
|
| 417 |
+
assert res.status_code == 400
|
| 418 |
+
assert res.json()["detail"] == "no_pending_registration"
|
| 419 |
+
assert sent == []
|
| 420 |
+
|
| 421 |
+
|
| 422 |
+
def test_social_signup_between_start_and_verify_loses(client, db_session, sent):
|
| 423 |
+
"""A Google account created in the window wins; verify 409s rather than 500s."""
|
| 424 |
+
assert _start(client, "race@test.local").status_code == 200
|
| 425 |
+
_make_social(db_session, email="race@test.local", provider=AuthProvider.GOOGLE)
|
| 426 |
+
|
| 427 |
+
res = _verify(client, "race@test.local")
|
| 428 |
+
|
| 429 |
+
assert res.status_code == 409
|
| 430 |
+
assert res.json()["detail"]["code"] == "wrong_auth_provider"
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
def test_ref_code_grants_referral_bonus_on_verify(client, db_session, sent):
|
| 434 |
+
from app.models.referral import Referral, REFERRAL_BONUS_VIDEOS
|
| 435 |
+
|
| 436 |
+
referrer = _make_email_user(db_session, email="referrer@test.local")
|
| 437 |
+
db_session.add(Referral(code="FRIEND", referrer_id=referrer.id, is_active=True))
|
| 438 |
+
db_session.commit()
|
| 439 |
+
|
| 440 |
+
assert _start(client, "invited@test.local").status_code == 200
|
| 441 |
+
res = _verify(client, "invited@test.local", ref_code="FRIEND")
|
| 442 |
+
|
| 443 |
+
assert res.status_code == 200
|
| 444 |
+
invited = db_session.query(User).filter_by(email="invited@test.local").one()
|
| 445 |
+
assert invited.referral_video_bonus == REFERRAL_BONUS_VIDEOS
|
| 446 |
+
|
| 447 |
+
|
| 448 |
+
# ─── Login ──────────────────────────────────────────────────────────────────
|
| 449 |
+
|
| 450 |
+
def test_login_succeeds_with_correct_password(client, db_session):
|
| 451 |
+
_make_email_user(db_session, email="who@test.local")
|
| 452 |
+
|
| 453 |
+
res = _login(client, "who@test.local")
|
| 454 |
+
|
| 455 |
+
assert res.status_code == 200
|
| 456 |
+
assert res.json()["user"]["auth_provider"] == "email"
|
| 457 |
+
|
| 458 |
+
|
| 459 |
+
def test_wrong_password_and_unknown_email_are_indistinguishable(client, db_session):
|
| 460 |
+
_make_email_user(db_session, email="known@test.local")
|
| 461 |
+
|
| 462 |
+
wrong = _login(client, "known@test.local", password="not-the-password")
|
| 463 |
+
unknown = _login(client, "nobody@test.local")
|
| 464 |
+
|
| 465 |
+
assert wrong.status_code == unknown.status_code == 401
|
| 466 |
+
assert wrong.json() == unknown.json() == {"detail": "invalid_credentials"}
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
def test_social_account_password_login_409s_before_touching_the_hash(client, db_session):
|
| 470 |
+
"""A Google row has password_hash=None; it must 409, never 401."""
|
| 471 |
+
_make_social(db_session, email="g2@test.local", provider=AuthProvider.GOOGLE)
|
| 472 |
+
|
| 473 |
+
res = _login(client, "g2@test.local")
|
| 474 |
+
|
| 475 |
+
assert res.status_code == 409
|
| 476 |
+
assert res.json()["detail"]["provider"] == "google"
|
| 477 |
+
|
| 478 |
+
|
| 479 |
+
def test_soft_deleted_account_requires_confirmation_then_reactivates(client, db_session):
|
| 480 |
+
_make_email_user(db_session, email="gone@test.local", is_active=False, plan=PlanTier.PRO)
|
| 481 |
+
|
| 482 |
+
res = _login(client, "gone@test.local")
|
| 483 |
+
assert res.status_code == 403
|
| 484 |
+
assert res.json()["detail"] == "account_deleted"
|
| 485 |
+
|
| 486 |
+
res = _login(client, "gone@test.local", reactivate=True)
|
| 487 |
+
assert res.status_code == 200
|
| 488 |
+
user = db_session.query(User).filter_by(email="gone@test.local").one()
|
| 489 |
+
db_session.refresh(user)
|
| 490 |
+
assert user.is_active is True
|
| 491 |
+
assert user.plan is PlanTier.FREE
|
| 492 |
+
|
| 493 |
+
|
| 494 |
+
def test_wrong_password_cannot_reactivate_a_deleted_account(client, db_session):
|
| 495 |
+
"""The ordering trap: reactivation must never precede the password check."""
|
| 496 |
+
_make_email_user(db_session, email="ghost@test.local", is_active=False)
|
| 497 |
+
|
| 498 |
+
res = _login(client, "ghost@test.local", password="wrong-password", reactivate=True)
|
| 499 |
+
|
| 500 |
+
assert res.status_code == 401
|
| 501 |
+
user = db_session.query(User).filter_by(email="ghost@test.local").one()
|
| 502 |
+
db_session.refresh(user)
|
| 503 |
+
assert user.is_active is False
|
| 504 |
+
|
| 505 |
+
|
| 506 |
+
def test_login_locks_out_after_repeated_failures(client, db_session):
|
| 507 |
+
_make_email_user(db_session, email="target@test.local")
|
| 508 |
+
|
| 509 |
+
for _ in range(5):
|
| 510 |
+
assert _login(client, "target@test.local", password="nope").status_code == 401
|
| 511 |
+
|
| 512 |
+
res = _login(client, "target@test.local", password="nope")
|
| 513 |
+
assert res.status_code == 429
|
| 514 |
+
assert res.json()["detail"] == "too_many_attempts"
|
| 515 |
+
assert int(res.headers["Retry-After"]) > 0
|
| 516 |
+
# Even the correct password is refused while locked out.
|
| 517 |
+
assert _login(client, "target@test.local").status_code == 429
|
| 518 |
+
|
| 519 |
+
|
| 520 |
+
def test_wrong_provider_does_not_count_as_a_failed_attempt(client, db_session):
|
| 521 |
+
"""A 409 is a correct answer, so asking repeatedly must not lock anyone out."""
|
| 522 |
+
_make_social(db_session, email="g3@test.local", provider=AuthProvider.GOOGLE)
|
| 523 |
+
|
| 524 |
+
for _ in range(8):
|
| 525 |
+
assert _login(client, "g3@test.local").status_code == 409
|
| 526 |
+
|
| 527 |
+
assert _login(client, "g3@test.local").status_code == 409
|
| 528 |
+
|
| 529 |
+
|
| 530 |
+
# ─── Forgot password ────────────────────────────────────────────────────────
|
| 531 |
+
|
| 532 |
+
def test_forgot_start_is_silent_for_unknown_email(client, db_session, sent):
|
| 533 |
+
res = _forgot_start(client, "stranger@test.local")
|
| 534 |
+
|
| 535 |
+
assert res.status_code == 200
|
| 536 |
+
assert res.json()["status"] == "code_sent"
|
| 537 |
+
assert sent == []
|
| 538 |
+
assert _codes(db_session, "stranger@test.local") == []
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
def test_forgot_start_on_deleted_account_requires_confirmation(client, db_session, sent):
|
| 542 |
+
"""Without ?reactivate=true it stays deleted and no code goes out."""
|
| 543 |
+
_make_email_user(db_session, email="rip@test.local", is_active=False)
|
| 544 |
+
|
| 545 |
+
res = _forgot_start(client, "rip@test.local")
|
| 546 |
+
|
| 547 |
+
assert res.status_code == 403
|
| 548 |
+
assert res.json()["detail"] == "account_deleted"
|
| 549 |
+
assert sent == []
|
| 550 |
+
assert _codes(db_session, "rip@test.local") == []
|
| 551 |
+
user = db_session.query(User).filter_by(email="rip@test.local").one()
|
| 552 |
+
db_session.refresh(user)
|
| 553 |
+
assert user.is_active is False
|
| 554 |
+
|
| 555 |
+
|
| 556 |
+
def test_forgot_start_reactivates_on_confirm_without_signing_in(client, db_session, sent):
|
| 557 |
+
"""The whole point: a deleted account whose password is also forgotten.
|
| 558 |
+
|
| 559 |
+
Confirming reactivation revives the account and emails a code — it must NOT
|
| 560 |
+
hand back a token, or the confirmation click alone would be a way into an
|
| 561 |
+
account without knowing the password or holding the mailbox.
|
| 562 |
+
"""
|
| 563 |
+
_make_email_user(db_session, email="back@test.local", is_active=False, plan=PlanTier.PRO)
|
| 564 |
+
|
| 565 |
+
res = _forgot_start(client, "back@test.local", reactivate=True)
|
| 566 |
+
|
| 567 |
+
assert res.status_code == 200
|
| 568 |
+
assert res.json()["status"] == "code_sent"
|
| 569 |
+
assert "access_token" not in res.json()
|
| 570 |
+
assert sent == [("reset", "back@test.local", CODE)]
|
| 571 |
+
|
| 572 |
+
user = db_session.query(User).filter_by(email="back@test.local").one()
|
| 573 |
+
db_session.refresh(user)
|
| 574 |
+
assert user.is_active is True
|
| 575 |
+
# Reactivation is always as a FREE user, exactly as on the login path.
|
| 576 |
+
assert user.plan is PlanTier.FREE
|
| 577 |
+
|
| 578 |
+
# And the reset still has to be completed to get a session.
|
| 579 |
+
res = _forgot_complete(client, "back@test.local", "Brand-New-Password1")
|
| 580 |
+
assert res.status_code == 200
|
| 581 |
+
assert res.json()["access_token"]
|
| 582 |
+
assert _login(client, "back@test.local", password="Brand-New-Password1").status_code == 200
|
| 583 |
+
|
| 584 |
+
|
| 585 |
+
def test_forgot_start_reactivate_flag_is_inert_for_unknown_email(client, db_session, sent):
|
| 586 |
+
"""?reactivate=true must not become an account-existence oracle."""
|
| 587 |
+
res = _forgot_start(client, "nobody@test.local", reactivate=True)
|
| 588 |
+
|
| 589 |
+
assert res.status_code == 200
|
| 590 |
+
assert sent == []
|
| 591 |
+
assert db_session.query(User).filter_by(email="nobody@test.local").first() is None
|
| 592 |
+
|
| 593 |
+
|
| 594 |
+
def test_forgot_start_reactivate_cannot_revive_a_social_account(client, db_session, sent):
|
| 595 |
+
"""The wrong-provider 409 still outranks reactivation — there is no password
|
| 596 |
+
to reset on a Google account, so reviving it here would be the wrong door."""
|
| 597 |
+
_make_social(
|
| 598 |
+
db_session, email="gdead@test.local", provider=AuthProvider.GOOGLE, is_active=False
|
| 599 |
+
)
|
| 600 |
+
|
| 601 |
+
res = _forgot_start(client, "gdead@test.local", reactivate=True)
|
| 602 |
+
|
| 603 |
+
assert res.status_code == 409
|
| 604 |
+
assert res.json()["detail"]["provider"] == "google"
|
| 605 |
+
user = db_session.query(User).filter_by(email="gdead@test.local").one()
|
| 606 |
+
db_session.refresh(user)
|
| 607 |
+
assert user.is_active is False
|
| 608 |
+
|
| 609 |
+
|
| 610 |
+
def test_forgot_password_replaces_the_credential(client, db_session, sent):
|
| 611 |
+
_make_email_user(db_session, email="reset@test.local")
|
| 612 |
+
|
| 613 |
+
assert _forgot_start(client, "reset@test.local").status_code == 200
|
| 614 |
+
assert sent == [("reset", "reset@test.local", CODE)]
|
| 615 |
+
|
| 616 |
+
res = _forgot_complete(client, "reset@test.local", "Brand-New-Password1")
|
| 617 |
+
assert res.status_code == 200
|
| 618 |
+
assert res.json()["access_token"]
|
| 619 |
+
|
| 620 |
+
assert _login(client, "reset@test.local").status_code == 401
|
| 621 |
+
assert _login(client, "reset@test.local", password="Brand-New-Password1").status_code == 200
|
| 622 |
+
assert _codes(db_session, "reset@test.local") == []
|
| 623 |
+
|
| 624 |
+
|
| 625 |
+
def test_forgot_complete_rejects_short_password_and_keeps_the_old_one(
|
| 626 |
+
client, db_session, sent
|
| 627 |
+
):
|
| 628 |
+
_make_email_user(db_session, email="keep@test.local")
|
| 629 |
+
assert _forgot_start(client, "keep@test.local").status_code == 200
|
| 630 |
+
|
| 631 |
+
res = _forgot_complete(client, "keep@test.local", "short")
|
| 632 |
+
|
| 633 |
+
assert res.status_code == 422
|
| 634 |
+
assert res.json()["detail"] == "password_too_short"
|
| 635 |
+
assert _login(client, "keep@test.local").status_code == 200
|
| 636 |
+
|
| 637 |
+
|
| 638 |
+
def test_signup_and_reset_codes_are_not_interchangeable(client, db_session, sent):
|
| 639 |
+
"""Codes are scoped to a purpose, so neither can be replayed as the other."""
|
| 640 |
+
_make_email_user(db_session, email="scope@test.local")
|
| 641 |
+
assert _forgot_start(client, "scope@test.local").status_code == 200
|
| 642 |
+
|
| 643 |
+
# A reset code cannot complete a registration...
|
| 644 |
+
assert _verify(client, "scope@test.local").status_code == 400
|
| 645 |
+
|
| 646 |
+
# ...and a signup code cannot complete a reset.
|
| 647 |
+
db_session.query(EmailVerificationCode).delete()
|
| 648 |
+
db_session.add(
|
| 649 |
+
EmailVerificationCode(
|
| 650 |
+
email="scope@test.local",
|
| 651 |
+
purpose=VerificationPurpose.SIGNUP.value,
|
| 652 |
+
code_hash=auth_router.verification.hash_code(CODE),
|
| 653 |
+
expires_at=datetime.utcnow() + timedelta(minutes=10),
|
| 654 |
+
last_sent_at=datetime.utcnow(),
|
| 655 |
+
created_at=datetime.utcnow(),
|
| 656 |
+
)
|
| 657 |
+
)
|
| 658 |
+
db_session.commit()
|
| 659 |
+
|
| 660 |
+
assert _forgot_complete(client, "scope@test.local", "Another-Password1").status_code == 400
|
| 661 |
+
|
| 662 |
+
|
| 663 |
+
# ─── forgot/check — validate without consuming ──────────────────────────────
|
| 664 |
+
|
| 665 |
+
def test_forgot_check_accepts_valid_code_without_spending_it(client, db_session, sent):
|
| 666 |
+
"""The whole point: checking must not consume, or complete() has nothing left."""
|
| 667 |
+
_make_email_user(db_session, email="chk@test.local")
|
| 668 |
+
assert _forgot_start(client, "chk@test.local").status_code == 200
|
| 669 |
+
|
| 670 |
+
res = client.post(
|
| 671 |
+
"/api/auth/password/forgot/check",
|
| 672 |
+
json={"email": "chk@test.local", "code": CODE},
|
| 673 |
+
)
|
| 674 |
+
assert res.status_code == 200
|
| 675 |
+
assert res.json()["status"] == "code_valid"
|
| 676 |
+
|
| 677 |
+
# Still usable afterwards — the code was validated, not spent.
|
| 678 |
+
assert _forgot_complete(client, "chk@test.local", "Brand-New-Password1").status_code == 200
|
| 679 |
+
assert _login(client, "chk@test.local", password="Brand-New-Password1").status_code == 200
|
| 680 |
+
|
| 681 |
+
|
| 682 |
+
def test_forgot_check_rejects_wrong_code(client, db_session, sent):
|
| 683 |
+
_make_email_user(db_session, email="chkbad@test.local")
|
| 684 |
+
assert _forgot_start(client, "chkbad@test.local").status_code == 200
|
| 685 |
+
|
| 686 |
+
res = client.post(
|
| 687 |
+
"/api/auth/password/forgot/check",
|
| 688 |
+
json={"email": "chkbad@test.local", "code": "000000"},
|
| 689 |
+
)
|
| 690 |
+
assert res.status_code == 400
|
| 691 |
+
assert res.json()["detail"]["code"] == "code_invalid"
|
| 692 |
+
# The real code still works, so a wrong guess did not destroy it.
|
| 693 |
+
assert _forgot_complete(client, "chkbad@test.local", "Brand-New-Password1").status_code == 200
|
| 694 |
+
|
| 695 |
+
|
| 696 |
+
def test_forgot_check_is_not_a_free_brute_force_oracle(client, db_session, sent):
|
| 697 |
+
"""Attempts must count here too, or this endpoint bypasses the 5-try cap."""
|
| 698 |
+
_make_email_user(db_session, email="chkbrute@test.local")
|
| 699 |
+
assert _forgot_start(client, "chkbrute@test.local").status_code == 200
|
| 700 |
+
|
| 701 |
+
for _ in range(4):
|
| 702 |
+
assert client.post(
|
| 703 |
+
"/api/auth/password/forgot/check",
|
| 704 |
+
json={"email": "chkbrute@test.local", "code": "000000"},
|
| 705 |
+
).status_code == 400
|
| 706 |
+
|
| 707 |
+
res = client.post(
|
| 708 |
+
"/api/auth/password/forgot/check",
|
| 709 |
+
json={"email": "chkbrute@test.local", "code": "000000"},
|
| 710 |
+
)
|
| 711 |
+
assert res.status_code == 429
|
| 712 |
+
assert res.json()["detail"] == "code_attempts_exceeded"
|
| 713 |
+
# Burned: even the correct code is gone now.
|
| 714 |
+
assert _forgot_complete(client, "chkbrute@test.local", "Brand-New-Password1").status_code == 400
|
backend/tests/test_token_revocation.py
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Depth tier — JWT revocation via users.token_version.
|
| 3 |
+
|
| 4 |
+
Our access tokens are stateless, so the only thing standing between a leaked
|
| 5 |
+
token and a live session is this counter. The properties under test:
|
| 6 |
+
|
| 7 |
+
1. Bumping the counter invalidates every token issued before the bump.
|
| 8 |
+
2. Logging out and resetting a password both bump it — the two moments a user
|
| 9 |
+
expects their old sessions to die.
|
| 10 |
+
3. A token minted before the ``tv`` claim existed still works, so shipping this
|
| 11 |
+
signs nobody out.
|
| 12 |
+
"""
|
| 13 |
+
import jwt as pyjwt
|
| 14 |
+
import pytest
|
| 15 |
+
|
| 16 |
+
from app.auth import create_access_token, create_refresh_token
|
| 17 |
+
from app.config import settings
|
| 18 |
+
from app.models.user import AuthProvider, PlanTier, User
|
| 19 |
+
from app.services import rate_limit
|
| 20 |
+
from app.services.password import hash_password
|
| 21 |
+
|
| 22 |
+
import app.routers.auth as auth_router
|
| 23 |
+
|
| 24 |
+
pytestmark = pytest.mark.depth
|
| 25 |
+
|
| 26 |
+
CODE = "123456"
|
| 27 |
+
PASSWORD = "Correct-Horse-1"
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@pytest.fixture(autouse=True)
|
| 31 |
+
def _fixed_code(monkeypatch):
|
| 32 |
+
monkeypatch.setattr(
|
| 33 |
+
auth_router.verification, "generate_code", lambda: CODE, raising=True
|
| 34 |
+
)
|
| 35 |
+
rate_limit.reset_all_limiters()
|
| 36 |
+
yield
|
| 37 |
+
rate_limit.reset_all_limiters()
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@pytest.fixture()
|
| 41 |
+
def sent(monkeypatch):
|
| 42 |
+
out: list[tuple[str, str]] = []
|
| 43 |
+
monkeypatch.setattr(
|
| 44 |
+
auth_router.email_service, "send_password_reset_code_email",
|
| 45 |
+
lambda to, code: out.append((to, code)), raising=True,
|
| 46 |
+
)
|
| 47 |
+
return out
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _make_email_user(db, *, email, password=PASSWORD, **kw):
|
| 51 |
+
user = User(
|
| 52 |
+
email=email, name="Token User", auth_provider=AuthProvider.EMAIL,
|
| 53 |
+
password_hash=hash_password(password), plan=PlanTier.FREE, is_active=True, **kw,
|
| 54 |
+
)
|
| 55 |
+
db.add(user)
|
| 56 |
+
db.commit()
|
| 57 |
+
db.refresh(user)
|
| 58 |
+
return user
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _bearer(token: str) -> dict[str, str]:
|
| 62 |
+
return {"Authorization": f"Bearer {token}"}
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
# ─── The core property ──────────────────────────────────────────────────────
|
| 66 |
+
|
| 67 |
+
def test_token_is_accepted_while_the_version_matches(client, db_session):
|
| 68 |
+
user = _make_email_user(db_session, email="tv1@test.local")
|
| 69 |
+
|
| 70 |
+
token = create_access_token(user.id, user.token_version)
|
| 71 |
+
|
| 72 |
+
assert client.get("/api/auth/me", headers=_bearer(token)).status_code == 200
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def test_bumping_the_version_invalidates_an_existing_token(client, db_session):
|
| 76 |
+
user = _make_email_user(db_session, email="tv2@test.local")
|
| 77 |
+
token = create_access_token(user.id, user.token_version)
|
| 78 |
+
assert client.get("/api/auth/me", headers=_bearer(token)).status_code == 200
|
| 79 |
+
|
| 80 |
+
user.token_version = (user.token_version or 0) + 1
|
| 81 |
+
db_session.commit()
|
| 82 |
+
|
| 83 |
+
res = client.get("/api/auth/me", headers=_bearer(token))
|
| 84 |
+
assert res.status_code == 401
|
| 85 |
+
# Same body as an expired token: telling a holder of a stale token that it
|
| 86 |
+
# was deliberately revoked confirms the account exists.
|
| 87 |
+
assert res.json()["detail"] == "Invalid or expired token"
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def test_legacy_token_without_the_claim_still_works(client, db_session):
|
| 91 |
+
"""A token minted before `tv` existed reads as version 0 — deploying this
|
| 92 |
+
must not sign the entire userbase out."""
|
| 93 |
+
user = _make_email_user(db_session, email="tv3@test.local")
|
| 94 |
+
assert (user.token_version or 0) == 0
|
| 95 |
+
|
| 96 |
+
legacy = pyjwt.encode(
|
| 97 |
+
{"sub": str(user.id), "exp": 9999999999, "iat": 0, "typ": "access"},
|
| 98 |
+
settings.JWT_SECRET,
|
| 99 |
+
algorithm=settings.JWT_ALGORITHM,
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
assert client.get("/api/auth/me", headers=_bearer(legacy)).status_code == 200
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def test_legacy_token_dies_once_the_account_revokes_once(client, db_session):
|
| 106 |
+
user = _make_email_user(db_session, email="tv4@test.local")
|
| 107 |
+
legacy = pyjwt.encode(
|
| 108 |
+
{"sub": str(user.id), "exp": 9999999999, "iat": 0, "typ": "access"},
|
| 109 |
+
settings.JWT_SECRET,
|
| 110 |
+
algorithm=settings.JWT_ALGORITHM,
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
user.token_version = 1
|
| 114 |
+
db_session.commit()
|
| 115 |
+
|
| 116 |
+
assert client.get("/api/auth/me", headers=_bearer(legacy)).status_code == 401
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def test_new_users_start_at_version_zero(client, db_session):
|
| 120 |
+
user = _make_email_user(db_session, email="tv5@test.local")
|
| 121 |
+
assert user.token_version == 0
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
# ─── Revocation triggers ────────────────────────────────────────────────────
|
| 125 |
+
|
| 126 |
+
def test_logout_revokes_the_token_it_was_called_with(client, db_session):
|
| 127 |
+
user = _make_email_user(db_session, email="out@test.local")
|
| 128 |
+
token = create_access_token(user.id, user.token_version)
|
| 129 |
+
|
| 130 |
+
assert client.post("/api/auth/logout", headers=_bearer(token)).status_code == 200
|
| 131 |
+
|
| 132 |
+
# The very token that authorized the logout is now dead — the whole point on
|
| 133 |
+
# a shared machine, where the copy left behind is the threat.
|
| 134 |
+
assert client.get("/api/auth/me", headers=_bearer(token)).status_code == 401
|
| 135 |
+
db_session.refresh(user)
|
| 136 |
+
assert user.token_version == 1
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def test_password_reset_revokes_tokens_issued_under_the_old_password(
|
| 140 |
+
client, db_session, sent
|
| 141 |
+
):
|
| 142 |
+
"""The reset is meant to evict whoever knew the old password."""
|
| 143 |
+
user = _make_email_user(db_session, email="reset@test.local")
|
| 144 |
+
stolen = create_access_token(user.id, user.token_version)
|
| 145 |
+
assert client.get("/api/auth/me", headers=_bearer(stolen)).status_code == 200
|
| 146 |
+
|
| 147 |
+
assert client.post(
|
| 148 |
+
"/api/auth/password/forgot/start", json={"email": "reset@test.local"}
|
| 149 |
+
).status_code == 200
|
| 150 |
+
res = client.post(
|
| 151 |
+
"/api/auth/password/forgot/complete",
|
| 152 |
+
json={
|
| 153 |
+
"email": "reset@test.local",
|
| 154 |
+
"code": CODE,
|
| 155 |
+
"new_password": "Brand-New-Password1",
|
| 156 |
+
},
|
| 157 |
+
)
|
| 158 |
+
assert res.status_code == 200
|
| 159 |
+
|
| 160 |
+
# The attacker's token is dead...
|
| 161 |
+
assert client.get("/api/auth/me", headers=_bearer(stolen)).status_code == 401
|
| 162 |
+
# ...while the token handed back by the reset works, so the legitimate user
|
| 163 |
+
# is not bounced out of the browser they just reset from.
|
| 164 |
+
fresh = res.json()["access_token"]
|
| 165 |
+
assert client.get("/api/auth/me", headers=_bearer(fresh)).status_code == 200
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def test_login_issues_a_token_carrying_the_current_version(client, db_session):
|
| 169 |
+
"""After a revocation, signing in again must work — the new token has to be
|
| 170 |
+
minted against the bumped counter, not a stale one."""
|
| 171 |
+
user = _make_email_user(db_session, email="again@test.local")
|
| 172 |
+
user.token_version = 7
|
| 173 |
+
db_session.commit()
|
| 174 |
+
|
| 175 |
+
res = client.post(
|
| 176 |
+
"/api/auth/email/login",
|
| 177 |
+
json={"email": "again@test.local", "password": PASSWORD},
|
| 178 |
+
)
|
| 179 |
+
assert res.status_code == 200
|
| 180 |
+
|
| 181 |
+
token = res.json()["access_token"]
|
| 182 |
+
assert client.get("/api/auth/me", headers=_bearer(token)).status_code == 200
|
| 183 |
+
assert pyjwt.decode(
|
| 184 |
+
token, settings.JWT_SECRET, algorithms=[settings.JWT_ALGORITHM]
|
| 185 |
+
)["tv"] == 7
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def test_signup_issues_a_token_that_works(client, db_session, monkeypatch):
|
| 189 |
+
monkeypatch.setattr(
|
| 190 |
+
auth_router.email_service, "send_verification_code_email",
|
| 191 |
+
lambda to, code: None, raising=True,
|
| 192 |
+
)
|
| 193 |
+
assert client.post(
|
| 194 |
+
"/api/auth/email/register/start",
|
| 195 |
+
json={"email": "fresh@test.local", "password": PASSWORD},
|
| 196 |
+
).status_code == 200
|
| 197 |
+
res = client.post(
|
| 198 |
+
"/api/auth/email/register/verify",
|
| 199 |
+
json={"email": "fresh@test.local", "code": CODE},
|
| 200 |
+
)
|
| 201 |
+
|
| 202 |
+
assert res.status_code == 200
|
| 203 |
+
token = res.json()["access_token"]
|
| 204 |
+
assert client.get("/api/auth/me", headers=_bearer(token)).status_code == 200
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
# ─── MCP refresh tokens ─────────────────────────────────────────────────────
|
| 208 |
+
|
| 209 |
+
async def test_revoked_refresh_token_cannot_mint_a_new_pair(db_session, monkeypatch):
|
| 210 |
+
"""Otherwise revocation undoes itself: the 30-day MCP credential would
|
| 211 |
+
quietly reissue past a password change."""
|
| 212 |
+
from mcp.server.auth.provider import RefreshToken
|
| 213 |
+
|
| 214 |
+
import app.services.mcp_provider as mcp_provider
|
| 215 |
+
|
| 216 |
+
user = _make_email_user(db_session, email="mcp@test.local")
|
| 217 |
+
stale = create_refresh_token(user.id, user.token_version)
|
| 218 |
+
|
| 219 |
+
user.token_version = (user.token_version or 0) + 1
|
| 220 |
+
db_session.commit()
|
| 221 |
+
|
| 222 |
+
# The provider opens its own SessionLocal(), which under the suite's
|
| 223 |
+
# rolled-back outer transaction would see an empty database. Point it at the
|
| 224 |
+
# test session so it reads the row we just bumped.
|
| 225 |
+
monkeypatch.setattr(
|
| 226 |
+
mcp_provider, "SessionLocal", lambda: _NonClosing(db_session), raising=True
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
provider = mcp_provider.BlogVideoOAuthProvider()
|
| 230 |
+
with pytest.raises(ValueError):
|
| 231 |
+
await provider.exchange_refresh_token(
|
| 232 |
+
client=None,
|
| 233 |
+
refresh_token=RefreshToken(
|
| 234 |
+
token=stale, client_id="c1", scopes=[], expires_at=9999999999
|
| 235 |
+
),
|
| 236 |
+
scopes=[],
|
| 237 |
+
)
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
async def test_current_refresh_token_still_mints_a_new_pair(db_session, monkeypatch):
|
| 241 |
+
"""The guard must not break ordinary refreshes — claude.ai renews on a timer,
|
| 242 |
+
so a false rejection here silently disconnects the integration."""
|
| 243 |
+
from mcp.server.auth.provider import RefreshToken
|
| 244 |
+
|
| 245 |
+
import app.services.mcp_provider as mcp_provider
|
| 246 |
+
|
| 247 |
+
user = _make_email_user(db_session, email="mcp-ok@test.local")
|
| 248 |
+
good = create_refresh_token(user.id, user.token_version)
|
| 249 |
+
|
| 250 |
+
monkeypatch.setattr(
|
| 251 |
+
mcp_provider, "SessionLocal", lambda: _NonClosing(db_session), raising=True
|
| 252 |
+
)
|
| 253 |
+
|
| 254 |
+
provider = mcp_provider.BlogVideoOAuthProvider()
|
| 255 |
+
out = await provider.exchange_refresh_token(
|
| 256 |
+
client=None,
|
| 257 |
+
refresh_token=RefreshToken(
|
| 258 |
+
token=good, client_id="c1", scopes=[], expires_at=9999999999
|
| 259 |
+
),
|
| 260 |
+
scopes=[],
|
| 261 |
+
)
|
| 262 |
+
assert out.access_token and out.refresh_token
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
class _NonClosing:
|
| 266 |
+
"""Wrap the test session so provider code calling .close() doesn't end it."""
|
| 267 |
+
|
| 268 |
+
def __init__(self, session):
|
| 269 |
+
self._session = session
|
| 270 |
+
|
| 271 |
+
def __getattr__(self, name):
|
| 272 |
+
return getattr(self._session, name)
|
| 273 |
+
|
| 274 |
+
def close(self):
|
| 275 |
+
pass
|
frontend/package-lock.json
CHANGED
|
@@ -8,7 +8,6 @@
|
|
| 8 |
"name": "blog2video-frontend",
|
| 9 |
"version": "0.1.0",
|
| 10 |
"dependencies": {
|
| 11 |
-
"@azure/msal-browser": "^5.21.0",
|
| 12 |
"@babel/standalone": "^7.29.1",
|
| 13 |
"@fontsource/archivo-black": "^5.2.8",
|
| 14 |
"@fontsource/arimo": "^5.2.8",
|
|
@@ -103,27 +102,6 @@
|
|
| 103 |
"url": "https://github.com/sponsors/sindresorhus"
|
| 104 |
}
|
| 105 |
},
|
| 106 |
-
"node_modules/@azure/msal-browser": {
|
| 107 |
-
"version": "5.21.0",
|
| 108 |
-
"resolved": "https://registry.npmjs.org/@azure/msal-browser/-/msal-browser-5.21.0.tgz",
|
| 109 |
-
"integrity": "sha512-80OcuXDErmcEDAIH9pBtSqBsed2sPT/IWmbG3xHLoPMl5zc8TINd6SlJAbVSmN5huGa3xGAg5qR7VnpaIEK0Zw==",
|
| 110 |
-
"license": "MIT",
|
| 111 |
-
"dependencies": {
|
| 112 |
-
"@azure/msal-common": "16.14.0"
|
| 113 |
-
},
|
| 114 |
-
"engines": {
|
| 115 |
-
"node": ">=0.8.0"
|
| 116 |
-
}
|
| 117 |
-
},
|
| 118 |
-
"node_modules/@azure/msal-common": {
|
| 119 |
-
"version": "16.14.0",
|
| 120 |
-
"resolved": "https://registry.npmjs.org/@azure/msal-common/-/msal-common-16.14.0.tgz",
|
| 121 |
-
"integrity": "sha512-A4rb55hI86Q9tBl/+jBj7TMz7iX2RFgQs/nExFzcAtoI/BFRVdaH5SL/MivrYD7qvweMpN8AgVvVMHV8UBYxew==",
|
| 122 |
-
"license": "MIT",
|
| 123 |
-
"engines": {
|
| 124 |
-
"node": ">=0.8.0"
|
| 125 |
-
}
|
| 126 |
-
},
|
| 127 |
"node_modules/@babel/code-frame": {
|
| 128 |
"version": "7.29.0",
|
| 129 |
"resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.0.tgz",
|
|
|
|
| 8 |
"name": "blog2video-frontend",
|
| 9 |
"version": "0.1.0",
|
| 10 |
"dependencies": {
|
|
|
|
| 11 |
"@babel/standalone": "^7.29.1",
|
| 12 |
"@fontsource/archivo-black": "^5.2.8",
|
| 13 |
"@fontsource/arimo": "^5.2.8",
|
|
|
|
| 102 |
"url": "https://github.com/sponsors/sindresorhus"
|
| 103 |
}
|
| 104 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
"node_modules/@babel/code-frame": {
|
| 106 |
"version": "7.29.0",
|
| 107 |
"resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.0.tgz",
|
frontend/package.json
CHANGED
|
@@ -17,7 +17,6 @@
|
|
| 17 |
"kit:check": "node ../scripts/sync-generated-kit.mjs --check"
|
| 18 |
},
|
| 19 |
"dependencies": {
|
| 20 |
-
"@azure/msal-browser": "^5.21.0",
|
| 21 |
"@babel/standalone": "^7.29.1",
|
| 22 |
"@fontsource/archivo-black": "^5.2.8",
|
| 23 |
"@fontsource/arimo": "^5.2.8",
|
|
|
|
| 17 |
"kit:check": "node ../scripts/sync-generated-kit.mjs --check"
|
| 18 |
},
|
| 19 |
"dependencies": {
|
|
|
|
| 20 |
"@babel/standalone": "^7.29.1",
|
| 21 |
"@fontsource/archivo-black": "^5.2.8",
|
| 22 |
"@fontsource/arimo": "^5.2.8",
|
frontend/src/App.tsx
CHANGED
|
@@ -13,6 +13,7 @@ import Landing from "./pages/Landing";
|
|
| 13 |
import PdfLanding from "./pages/PdfLanding";
|
| 14 |
import { applyFavicon, isPdfBrand, useBrand, markPdfOrigin } from "./brand/brand";
|
| 15 |
import Pricing from "./pages/Pricing";
|
|
|
|
| 16 |
import Dashboard from "./pages/Dashboard";
|
| 17 |
import ProjectView from "./pages/ProjectView";
|
| 18 |
import Subscription from "./pages/Subscription";
|
|
@@ -189,6 +190,10 @@ function AppRoutes() {
|
|
| 189 |
(corePages.ts) with inbound links from several others. */}
|
| 190 |
<Route path="/pdf2video" element={<PdfLanding />} />
|
| 191 |
<Route path="/pricing" element={<Pricing />} />
|
|
|
|
|
|
|
|
|
|
|
|
|
| 192 |
<Route path="/contact" element={<Contact />} />
|
| 193 |
<Route path="/blogs" element={<Blog />} />
|
| 194 |
<Route path="/blogs/:slug" element={<BlogPostPage />} />
|
|
|
|
| 13 |
import PdfLanding from "./pages/PdfLanding";
|
| 14 |
import { applyFavicon, isPdfBrand, useBrand, markPdfOrigin } from "./brand/brand";
|
| 15 |
import Pricing from "./pages/Pricing";
|
| 16 |
+
import AuthPage from "./pages/AuthPage";
|
| 17 |
import Dashboard from "./pages/Dashboard";
|
| 18 |
import ProjectView from "./pages/ProjectView";
|
| 19 |
import Subscription from "./pages/Subscription";
|
|
|
|
| 190 |
(corePages.ts) with inbound links from several others. */}
|
| 191 |
<Route path="/pdf2video" element={<PdfLanding />} />
|
| 192 |
<Route path="/pricing" element={<Pricing />} />
|
| 193 |
+
{/* Full-page sign-in / sign-up. Two paths, one component, so "Sign up"
|
| 194 |
+
is directly linkable rather than reachable only via a toggle. */}
|
| 195 |
+
<Route path="/signin" element={<AuthPage mode="signin" />} />
|
| 196 |
+
<Route path="/signup" element={<AuthPage mode="signup" />} />
|
| 197 |
<Route path="/contact" element={<Contact />} />
|
| 198 |
<Route path="/blogs" element={<Blog />} />
|
| 199 |
<Route path="/blogs/:slug" element={<BlogPostPage />} />
|
frontend/src/api/client.ts
CHANGED
|
@@ -479,36 +479,69 @@ export const googleLogin = (credential: string, reactivate = false, refCode?: st
|
|
| 479 |
return api.post<AuthResponse>("/auth/google", { credential }, { params });
|
| 480 |
};
|
| 481 |
|
| 482 |
-
/
|
| 483 |
-
|
| 484 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 485 |
}
|
| 486 |
|
| 487 |
-
export const
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
)
|
| 493 |
-
const params: Record<string, unknown> = { reactivate };
|
| 494 |
-
if (refCode) params.ref_code = refCode;
|
| 495 |
-
return api.post<AuthResponse>(
|
| 496 |
-
"/auth/apple",
|
| 497 |
-
{ identity_token: identityToken, user: user ?? null },
|
| 498 |
-
{ params }
|
| 499 |
-
);
|
| 500 |
-
};
|
| 501 |
|
| 502 |
-
export const
|
| 503 |
-
|
| 504 |
-
reactivate = false,
|
| 505 |
-
refCode?: string | null
|
| 506 |
-
) => {
|
| 507 |
-
const params: Record<string, unknown> = { reactivate };
|
| 508 |
if (refCode) params.ref_code = refCode;
|
| 509 |
-
return
|
| 510 |
};
|
| 511 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 512 |
// Share B2V (referral/invite) disabled
|
| 513 |
// export const getAffiliateStats = () => api.get<AffiliateStats>("/affiliate/stats");
|
| 514 |
// export const sendAffiliateInvites = (emails: string[]) =>
|
|
|
|
| 479 |
return api.post<AuthResponse>("/auth/google", { credential }, { params });
|
| 480 |
};
|
| 481 |
|
| 482 |
+
// ─── Email + password auth ────────────────────────────────
|
| 483 |
+
// Built-in provider. Registration proves the mailbox with a one-time code before
|
| 484 |
+
// the account exists; every later sign-in is password-only.
|
| 485 |
+
//
|
| 486 |
+
// These use `publicApi`, NOT `api`: the authed client's interceptor treats any
|
| 487 |
+
// 401 as an expired session — it clears the stored token and hard-redirects to
|
| 488 |
+
// "/". A mistyped password returns 401 by design, so on `api` it would log an
|
| 489 |
+
// already-signed-in user out and reload the page out from under the modal,
|
| 490 |
+
// and the redirect would race the error the form needs to display.
|
| 491 |
+
|
| 492 |
+
/** Acknowledges a one-time code was issued. Carries no account information. */
|
| 493 |
+
export interface CodeSentResponse {
|
| 494 |
+
status: string;
|
| 495 |
+
/** Seconds until the code expires. */
|
| 496 |
+
expires_in: number;
|
| 497 |
+
/** Seconds before a resend is allowed. */
|
| 498 |
+
resend_in: number;
|
| 499 |
}
|
| 500 |
|
| 501 |
+
export const emailRegisterStart = (email: string, password: string, name?: string | null) =>
|
| 502 |
+
publicApi.post<CodeSentResponse>("/auth/email/register/start", {
|
| 503 |
+
email,
|
| 504 |
+
password,
|
| 505 |
+
name: name ?? null,
|
| 506 |
+
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 507 |
|
| 508 |
+
export const emailRegisterVerify = (email: string, code: string, refCode?: string | null) => {
|
| 509 |
+
const params: Record<string, unknown> = {};
|
|
|
|
|
|
|
|
|
|
|
|
|
| 510 |
if (refCode) params.ref_code = refCode;
|
| 511 |
+
return publicApi.post<AuthResponse>("/auth/email/register/verify", { email, code }, { params });
|
| 512 |
};
|
| 513 |
|
| 514 |
+
export const emailRegisterResend = (email: string) =>
|
| 515 |
+
publicApi.post<CodeSentResponse>("/auth/email/register/resend", { email });
|
| 516 |
+
|
| 517 |
+
export const emailLogin = (email: string, password: string, reactivate = false) =>
|
| 518 |
+
publicApi.post<AuthResponse>(
|
| 519 |
+
"/auth/email/login",
|
| 520 |
+
{ email, password },
|
| 521 |
+
{ params: { reactivate } }
|
| 522 |
+
);
|
| 523 |
+
|
| 524 |
+
/** `reactivate` confirms revival of a soft-deleted account. It still only emails
|
| 525 |
+
* a code — no token is issued, so the reset must be completed to get a session. */
|
| 526 |
+
export const forgotPasswordStart = (email: string, reactivate = false) =>
|
| 527 |
+
publicApi.post<CodeSentResponse>(
|
| 528 |
+
"/auth/password/forgot/start",
|
| 529 |
+
{ email },
|
| 530 |
+
{ params: { reactivate } }
|
| 531 |
+
);
|
| 532 |
+
|
| 533 |
+
/** Validate a reset code without spending it, so the UI can reject a wrong
|
| 534 |
+
* code before advancing to the new-password step. */
|
| 535 |
+
export const forgotPasswordCheck = (email: string, code: string) =>
|
| 536 |
+
publicApi.post<{ status: string }>("/auth/password/forgot/check", { email, code });
|
| 537 |
+
|
| 538 |
+
export const forgotPasswordComplete = (email: string, code: string, newPassword: string) =>
|
| 539 |
+
publicApi.post<AuthResponse>("/auth/password/forgot/complete", {
|
| 540 |
+
email,
|
| 541 |
+
code,
|
| 542 |
+
new_password: newPassword,
|
| 543 |
+
});
|
| 544 |
+
|
| 545 |
// Share B2V (referral/invite) disabled
|
| 546 |
// export const getAffiliateStats = () => api.get<AffiliateStats>("/affiliate/stats");
|
| 547 |
// export const sendAffiliateInvites = (emails: string[]) =>
|
frontend/src/api/types.ts
CHANGED
|
@@ -80,8 +80,12 @@ export const AVATAR_BG_PRESETS: { value: string; label: string }[] = [
|
|
| 80 |
{ value: "#F1F5F9", label: "Paper" },
|
| 81 |
];
|
| 82 |
|
| 83 |
-
/**
|
| 84 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
|
| 86 |
/**
|
| 87 |
* Human-facing provider names. An explicit map rather than a ternary: this
|
|
@@ -90,10 +94,38 @@ export type AuthProvider = "google" | "apple" | "microsoft";
|
|
| 90 |
*/
|
| 91 |
export const AUTH_PROVIDER_LABELS: Record<AuthProvider, string> = {
|
| 92 |
google: "Google",
|
| 93 |
-
|
| 94 |
-
microsoft: "Microsoft",
|
| 95 |
};
|
| 96 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
export interface UserInfo {
|
| 98 |
id: number;
|
| 99 |
email: string;
|
|
|
|
| 80 |
{ value: "#F1F5F9", label: "Paper" },
|
| 81 |
];
|
| 82 |
|
| 83 |
+
/**
|
| 84 |
+
* The sign-in provider an account is permanently bound to. "email" is our own
|
| 85 |
+
* built-in provider (email + password), the only one with no external identity
|
| 86 |
+
* provider behind it.
|
| 87 |
+
*/
|
| 88 |
+
export type AuthProvider = "google" | "email";
|
| 89 |
|
| 90 |
/**
|
| 91 |
* Human-facing provider names. An explicit map rather than a ternary: this
|
|
|
|
| 94 |
*/
|
| 95 |
export const AUTH_PROVIDER_LABELS: Record<AuthProvider, string> = {
|
| 96 |
google: "Google",
|
| 97 |
+
email: "Email",
|
|
|
|
| 98 |
};
|
| 99 |
|
| 100 |
+
/**
|
| 101 |
+
* Minimum password length, mirroring MIN_PASSWORD_LENGTH in the backend's
|
| 102 |
+
* services/password.py. Used for instant feedback only — the server is
|
| 103 |
+
* authoritative, and sign-in must never be blocked on it client-side, or a
|
| 104 |
+
* password predating a policy change would become unusable.
|
| 105 |
+
*/
|
| 106 |
+
export const MIN_PASSWORD_LENGTH = 8;
|
| 107 |
+
|
| 108 |
+
/**
|
| 109 |
+
* The password policy, mirroring validate_password() in the backend's
|
| 110 |
+
* services/password.py. Shown as a live checklist while choosing a password.
|
| 111 |
+
*
|
| 112 |
+
* Feedback only, and only where a password is being SET (signup, reset). The
|
| 113 |
+
* login form must never apply these — an existing password that predates a rule
|
| 114 |
+
* still has to reach the server, which decides.
|
| 115 |
+
*/
|
| 116 |
+
export const PASSWORD_RULES: { test: (p: string) => boolean; label: string }[] = [
|
| 117 |
+
{
|
| 118 |
+
test: (p) => p.length >= MIN_PASSWORD_LENGTH,
|
| 119 |
+
label: `At least ${MIN_PASSWORD_LENGTH} characters`,
|
| 120 |
+
},
|
| 121 |
+
{ test: (p) => /[A-Z]/.test(p), label: "One capital letter" },
|
| 122 |
+
// Matches the backend's deliberately broad definition: anything that is not a
|
| 123 |
+
// letter or digit, so non-ASCII punctuation counts too.
|
| 124 |
+
{ test: (p) => /[^A-Za-z0-9]/.test(p), label: "One special character" },
|
| 125 |
+
];
|
| 126 |
+
|
| 127 |
+
export const passwordMeetsPolicy = (p: string) => PASSWORD_RULES.every((r) => r.test(p));
|
| 128 |
+
|
| 129 |
export interface UserInfo {
|
| 130 |
id: number;
|
| 131 |
email: string;
|
frontend/src/components/auth/AuthFlow.tsx
ADDED
|
@@ -0,0 +1,1173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { useCallback, useEffect, useRef, useState } from "react";
|
| 2 |
+
import ReactDOM from "react-dom";
|
| 3 |
+
import { GoogleLogin } from "@react-oauth/google";
|
| 4 |
+
|
| 5 |
+
import { useSocialLogin, type LoginError } from "../../hooks/useSocialLogin";
|
| 6 |
+
import { useEmailAuth } from "../../hooks/useEmailAuth";
|
| 7 |
+
import { PASSWORD_RULES, passwordMeetsPolicy } from "../../api/types";
|
| 8 |
+
import {
|
| 9 |
+
copyLink,
|
| 10 |
+
detectInAppBrowser,
|
| 11 |
+
escapeToSystemBrowser,
|
| 12 |
+
} from "../../lib/inAppBrowser";
|
| 13 |
+
|
| 14 |
+
export interface LoginModalCopy {
|
| 15 |
+
title?: string;
|
| 16 |
+
subtitle?: string;
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
interface LoginModalProps extends LoginModalCopy {
|
| 20 |
+
open: boolean;
|
| 21 |
+
onClose: () => void;
|
| 22 |
+
/** Runs on a successful sign-in; the provider uses it to close the modal. */
|
| 23 |
+
onSuccess?: () => void;
|
| 24 |
+
/** Suppresses the default post-login redirect (see LoginModalContext). */
|
| 25 |
+
skipRedirect?: boolean;
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
/** Fallback copy when a call site supplies none. Keyed to the opening mode so a
|
| 29 |
+
* surface that defaults to the sign-up form is not headed "Sign in". */
|
| 30 |
+
const DEFAULT_COPY = {
|
| 31 |
+
login: {
|
| 32 |
+
title: "Sign in to Blog2Video",
|
| 33 |
+
subtitle: "Choose how you'd like to continue.",
|
| 34 |
+
},
|
| 35 |
+
signup: {
|
| 36 |
+
title: "Create your Blog2Video account",
|
| 37 |
+
subtitle: "Choose how you'd like to get started.",
|
| 38 |
+
},
|
| 39 |
+
} as const;
|
| 40 |
+
|
| 41 |
+
/**
|
| 42 |
+
* Per-stage heading. The first stage keeps whatever copy the call site passed —
|
| 43 |
+
* the ~11 CTAs that open this modal each set their own — while the later stages
|
| 44 |
+
* describe the step the user is actually on.
|
| 45 |
+
*/
|
| 46 |
+
const STAGE_COPY: Record<string, { title: string; subtitle: string } | undefined> = {
|
| 47 |
+
otp: {
|
| 48 |
+
title: "Check your email",
|
| 49 |
+
subtitle: "We sent you a 6-digit code. Enter it below to finish signing up.",
|
| 50 |
+
},
|
| 51 |
+
forgot_email: {
|
| 52 |
+
title: "Reset your password",
|
| 53 |
+
subtitle: "We'll email you a code to set a new password.",
|
| 54 |
+
},
|
| 55 |
+
forgot_code: { title: "Check your email", subtitle: "Enter the 6-digit code we sent you." },
|
| 56 |
+
forgot_password: { title: "Choose a new password", subtitle: "Pick something you'll remember." },
|
| 57 |
+
};
|
| 58 |
+
|
| 59 |
+
/**
|
| 60 |
+
* Errors that belong under a specific input rather than in the modal's banner.
|
| 61 |
+
*
|
| 62 |
+
* These are all "what you typed was wrong" — the message is only useful next to
|
| 63 |
+
* the field you retype. The banner is reserved for errors about the modal as a
|
| 64 |
+
* whole, which is also why account_deleted is excluded: it carries a Reactivate
|
| 65 |
+
* button that needs the box to read as one unit.
|
| 66 |
+
*/
|
| 67 |
+
const FIELD_LEVEL_ERRORS = new Set<LoginError["kind"]>([
|
| 68 |
+
"invalid_credentials",
|
| 69 |
+
"password_policy",
|
| 70 |
+
"code_invalid",
|
| 71 |
+
"code_expired",
|
| 72 |
+
"code_burned",
|
| 73 |
+
"resend_cooldown",
|
| 74 |
+
]);
|
| 75 |
+
|
| 76 |
+
const isFieldLevelError = (e: LoginError | null) =>
|
| 77 |
+
e !== null && FIELD_LEVEL_ERRORS.has(e.kind);
|
| 78 |
+
|
| 79 |
+
/**
|
| 80 |
+
* "This address already has a password account", in either of the two shapes the
|
| 81 |
+
* backend sends it. Mirrors isExistingEmailAccount in useEmailAuth — both must
|
| 82 |
+
* agree, or the hook would route the user to the sign-in form while the banner
|
| 83 |
+
* kept claiming something else.
|
| 84 |
+
*/
|
| 85 |
+
const isExistingAccountError = (e: LoginError | null) =>
|
| 86 |
+
e !== null &&
|
| 87 |
+
(e.kind === "email_already_registered" ||
|
| 88 |
+
(e.kind === "wrong_provider" && e.provider === "email"));
|
| 89 |
+
|
| 90 |
+
/** Inline validation message: red text, no box, sits under its field. */
|
| 91 |
+
function FieldError({ children }: { children: React.ReactNode }) {
|
| 92 |
+
return <p className="text-left text-xs text-red-600">{children}</p>;
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
/**
|
| 96 |
+
* Width of the sign-in column, shared by the provider rows, the divider and
|
| 97 |
+
* every stage form. Set once per render by the variant: the page has a wider
|
| 98 |
+
* card to fill, the modal keeps its original 300px. A module-level value rather
|
| 99 |
+
* than a prop because EmailAuthForm/CodeForm would otherwise have to forward it
|
| 100 |
+
* through every stage purely to change one number.
|
| 101 |
+
*/
|
| 102 |
+
let COLUMN_WIDTH_CLASS = "w-[300px]";
|
| 103 |
+
|
| 104 |
+
const INPUT_CLASS =
|
| 105 |
+
"w-full rounded-lg border border-gray-300 px-3 py-2 text-sm text-gray-900 outline-none transition placeholder:text-gray-400 focus:border-purple-500 focus:ring-2 focus:ring-purple-100";
|
| 106 |
+
const PRIMARY_BUTTON_CLASS =
|
| 107 |
+
"w-full rounded-lg bg-purple-600 px-4 py-2.5 text-sm font-medium text-white transition hover:bg-purple-700 disabled:cursor-not-allowed disabled:opacity-50";
|
| 108 |
+
|
| 109 |
+
/**
|
| 110 |
+
* The sign-in surface itself — everything inside the modal's box.
|
| 111 |
+
*
|
| 112 |
+
* Extracted so the dialog (LoginModal) and the full page (AuthPage) render the
|
| 113 |
+
* SAME flow rather than two copies. A fork here would drift exactly the way a
|
| 114 |
+
* second copy of parseLoginError would: one surface would quietly stop handling
|
| 115 |
+
* a 409, a burned code, or the reactivation prompt.
|
| 116 |
+
*
|
| 117 |
+
* `variant` only affects chrome-adjacent details (heading size, the terms
|
| 118 |
+
* footer); every behaviour — staging, error placement, provider narrowing — is
|
| 119 |
+
* identical on both.
|
| 120 |
+
*/
|
| 121 |
+
export interface AuthFlowProps extends LoginModalCopy {
|
| 122 |
+
/** False while a modal is closed, so the reset effect does not run. */
|
| 123 |
+
active?: boolean;
|
| 124 |
+
variant?: "modal" | "page";
|
| 125 |
+
/** Opening intent. Defaults to "signup" so every surface that does not say
|
| 126 |
+
* otherwise (the modal, the in-place tool gates) opens on the sign-up form;
|
| 127 |
+
* /signin passes "login" explicitly. */
|
| 128 |
+
mode?: "login" | "signup";
|
| 129 |
+
onSuccess?: () => void;
|
| 130 |
+
skipRedirect?: boolean;
|
| 131 |
+
/** Modal only: renders the back chevron beside the heading. */
|
| 132 |
+
onClose?: () => void;
|
| 133 |
+
}
|
| 134 |
+
|
| 135 |
+
export default function AuthFlow({
|
| 136 |
+
active = true,
|
| 137 |
+
variant = "modal",
|
| 138 |
+
mode = "signup",
|
| 139 |
+
onSuccess,
|
| 140 |
+
skipRedirect,
|
| 141 |
+
title,
|
| 142 |
+
subtitle,
|
| 143 |
+
}: AuthFlowProps) {
|
| 144 |
+
const {
|
| 145 |
+
signInWithGoogle,
|
| 146 |
+
onGoogleError,
|
| 147 |
+
signingIn,
|
| 148 |
+
error,
|
| 149 |
+
reactivate,
|
| 150 |
+
reactivating,
|
| 151 |
+
dismissError,
|
| 152 |
+
reset,
|
| 153 |
+
} = useSocialLogin({ onSuccess, skipRedirect });
|
| 154 |
+
|
| 155 |
+
const emailAuth = useEmailAuth({ onSuccess, skipRedirect, initialMode: mode });
|
| 156 |
+
|
| 157 |
+
// Keyed to the LIVE stage mode, not the mount-time prop: the "Already have an
|
| 158 |
+
// account? Sign in" toggle flips stage.mode, and a heading frozen at mount
|
| 159 |
+
// would keep saying "Create your account" over a sign-in form.
|
| 160 |
+
const activeMode =
|
| 161 |
+
"mode" in emailAuth.stage ? emailAuth.stage.mode : mode;
|
| 162 |
+
const fallback = DEFAULT_COPY[activeMode];
|
| 163 |
+
const resolvedTitle = title ?? fallback.title;
|
| 164 |
+
const resolvedSubtitle = subtitle ?? fallback.subtitle;
|
| 165 |
+
|
| 166 |
+
// Only consult the UA once the modal opens; the result never changes for a
|
| 167 |
+
// given page load, but this keeps the check out of the render path.
|
| 168 |
+
const [inApp, setInApp] = useState(false);
|
| 169 |
+
const [showInstructions, setShowInstructions] = useState(false);
|
| 170 |
+
const [copied, setCopied] = useState(false);
|
| 171 |
+
|
| 172 |
+
const resetEmail = emailAuth.reset;
|
| 173 |
+
useEffect(() => {
|
| 174 |
+
if (!active) return;
|
| 175 |
+
setInApp(detectInAppBrowser().isInApp);
|
| 176 |
+
setShowInstructions(false);
|
| 177 |
+
setCopied(false);
|
| 178 |
+
reset();
|
| 179 |
+
resetEmail();
|
| 180 |
+
}, [active, reset, resetEmail]);
|
| 181 |
+
|
| 182 |
+
// Either path can be mid-flight; the modal must stay inert for both.
|
| 183 |
+
const busy = signingIn || emailAuth.busy;
|
| 184 |
+
|
| 185 |
+
/* Which hook failed MOST RECENTLY.
|
| 186 |
+
*
|
| 187 |
+
* Two independent error states feed one banner, and the surface lets a user
|
| 188 |
+
* move between them without leaving it: a Google attempt rejected because the
|
| 189 |
+
* address is an email account, then an email attempt rejected because a
|
| 190 |
+
* different address is a Google account. This used to be `error ??
|
| 191 |
+
* emailAuth.error`, which is not "whichever hook just failed" but "the social
|
| 192 |
+
* hook wins if it EVER failed" — the social error is never cleared by the
|
| 193 |
+
* email flow (the hooks are isolated; useEmailAuth can only clear its own),
|
| 194 |
+
* so the first rejection masked every later one. The banner kept naming the
|
| 195 |
+
* wrong provider, and `onlyProvider` below inherited the same stale value, so
|
| 196 |
+
* the UI also failed to narrow to the provider that would actually work.
|
| 197 |
+
*
|
| 198 |
+
* Tracked by REFERENCE, not by value: parseLoginError builds a fresh object
|
| 199 |
+
* on every call, so a repeat of the same failure still registers as new. */
|
| 200 |
+
const [lastErrorSource, setLastErrorSource] = useState<"social" | "email" | null>(null);
|
| 201 |
+
const prevErrors = useRef<{ social: LoginError | null; email: LoginError | null }>({
|
| 202 |
+
social: null,
|
| 203 |
+
email: null,
|
| 204 |
+
});
|
| 205 |
+
const emailError = emailAuth.error;
|
| 206 |
+
useEffect(() => {
|
| 207 |
+
const prev = prevErrors.current;
|
| 208 |
+
prevErrors.current = { social: error, email: emailError };
|
| 209 |
+
// A newly-set error claims the banner. Checked independently so that a
|
| 210 |
+
// render where one is set while the other is cleared still resolves.
|
| 211 |
+
if (error !== prev.social && error !== null) setLastErrorSource("social");
|
| 212 |
+
else if (emailError !== prev.email && emailError !== null) setLastErrorSource("email");
|
| 213 |
+
else if (error === null && emailError === null) setLastErrorSource(null);
|
| 214 |
+
}, [error, emailError]);
|
| 215 |
+
|
| 216 |
+
/** The error the UI should speak for: the most recent one, with the other as
|
| 217 |
+
* a fallback so clearing one never blanks a banner the other still owns. */
|
| 218 |
+
const activeError =
|
| 219 |
+
lastErrorSource === "email" ? (emailError ?? error) : (error ?? emailError);
|
| 220 |
+
|
| 221 |
+
// A soft-deleted account asks for confirmation in its own dialog rather than
|
| 222 |
+
// offering a button inside the error banner — see ReactivateConfirm.
|
| 223 |
+
// Three routes, because reactivating from the forgot-password step reactivates
|
| 224 |
+
// WITHOUT signing in — it emails a reset code instead — so it needs its own
|
| 225 |
+
// confirm copy and its own retry.
|
| 226 |
+
// Never on the SIGNUP form: reactivation is a decision about an account you
|
| 227 |
+
// are signing in to, and "Reactivate your account?" over "Create your account"
|
| 228 |
+
// reads as a non-sequitur. The backend already answers signup with
|
| 229 |
+
// `email_already_registered` for a deleted account, so this is belt and
|
| 230 |
+
// braces — and it also guarantees the dialog is only rendered where a pending
|
| 231 |
+
// retry exists, since useEmailAuth holds one only in login mode. A dialog
|
| 232 |
+
// whose confirm button silently does nothing is worse than no dialog.
|
| 233 |
+
const emailStageIsSignupPassword =
|
| 234 |
+
emailAuth.stage.name === "password" && emailAuth.stage.mode === "signup";
|
| 235 |
+
//
|
| 236 |
+
// Routed off the SAME most-recent-error rule as the banner. It used to check
|
| 237 |
+
// emailAuth.error first and fall back to the social one — the exact opposite
|
| 238 |
+
// precedence — so the dialog and the banner could disagree about which hook
|
| 239 |
+
// had won and describe two different accounts at once.
|
| 240 |
+
const deletedIsFromEmailHook =
|
| 241 |
+
activeError === emailError && emailError?.kind === "account_deleted";
|
| 242 |
+
const deletedError =
|
| 243 |
+
deletedIsFromEmailHook && !emailStageIsSignupPassword
|
| 244 |
+
? emailAuth.stage.name === "forgot_email" || emailAuth.stage.name === "forgot_code"
|
| 245 |
+
? ("forgot" as const)
|
| 246 |
+
: ("email" as const)
|
| 247 |
+
: activeError === error && error?.kind === "account_deleted"
|
| 248 |
+
? ("social" as const)
|
| 249 |
+
: null;
|
| 250 |
+
// The email form is showing its own persistent "already registered" notice,
|
| 251 |
+
// so the banner must not duplicate it. See the render site below.
|
| 252 |
+
const switchedToLoginNotice =
|
| 253 |
+
emailAuth.stage.name === "password" &&
|
| 254 |
+
emailAuth.stage.switchedFromSignup === true;
|
| 255 |
+
|
| 256 |
+
/* A social sign-in rejected because the address is an email+password account
|
| 257 |
+
("Your account is registered with an email and password. Sign in below").
|
| 258 |
+
The email flow is the way forward, so switch it to the SIGN-IN form — the
|
| 259 |
+
surface otherwise sat on the sign-up form, telling the user to sign in
|
| 260 |
+
below while showing them a registration form and an empty address box.
|
| 261 |
+
|
| 262 |
+
useEmailAuth already does this for its own failures (recoverToLogin), but a
|
| 263 |
+
Google rejection comes from useSocialLogin, which knows nothing about the
|
| 264 |
+
email stage machine. AuthFlow is the only place that sees both.
|
| 265 |
+
|
| 266 |
+
Note it can only flip the mode, not prefill the address: the social error
|
| 267 |
+
carries no email — that lives inside the provider token. */
|
| 268 |
+
const setEmailMode = emailAuth.setMode;
|
| 269 |
+
const socialWrongProviderIsEmail =
|
| 270 |
+
error?.kind === "wrong_provider" && error.provider === "email";
|
| 271 |
+
/* Fire ONCE per rejection, not on every render while the error is up.
|
| 272 |
+
Keying this on the live stage mode made it a lock instead of a correction:
|
| 273 |
+
the error lives in useSocialLogin, so emailAuth.setMode cannot clear it, and
|
| 274 |
+
every attempt to switch back to "Sign up" was immediately undone by this
|
| 275 |
+
effect on the next render — the toggle looked dead. The ref lets us steer
|
| 276 |
+
the user once and then leave the choice to them. */
|
| 277 |
+
const correctedForWrongProvider = useRef(false);
|
| 278 |
+
useEffect(() => {
|
| 279 |
+
if (!socialWrongProviderIsEmail) {
|
| 280 |
+
correctedForWrongProvider.current = false;
|
| 281 |
+
return;
|
| 282 |
+
}
|
| 283 |
+
if (!correctedForWrongProvider.current) {
|
| 284 |
+
correctedForWrongProvider.current = true;
|
| 285 |
+
setEmailMode("login");
|
| 286 |
+
}
|
| 287 |
+
}, [socialWrongProviderIsEmail, setEmailMode]);
|
| 288 |
+
|
| 289 |
+
const handleEscape = useCallback(() => {
|
| 290 |
+
// Android can hand off to Chrome; iOS cannot, so fall back to instructions.
|
| 291 |
+
if (!escapeToSystemBrowser(window.location.href)) setShowInstructions(true);
|
| 292 |
+
}, []);
|
| 293 |
+
|
| 294 |
+
const handleCopy = useCallback(async () => {
|
| 295 |
+
const ok = await copyLink(window.location.href);
|
| 296 |
+
setCopied(ok);
|
| 297 |
+
if (ok) setTimeout(() => setCopied(false), 2000);
|
| 298 |
+
}, []);
|
| 299 |
+
|
| 300 |
+
/* After a wrong-provider rejection we know exactly which provider owns the
|
| 301 |
+
email, so offer only that one — recovery becomes a single click instead of
|
| 302 |
+
another guess between several buttons.
|
| 303 |
+
|
| 304 |
+
"email" is deliberately NOT a narrowing. The narrowing exists to reduce a
|
| 305 |
+
row of social buttons down to the one that works; when the answer is our own
|
| 306 |
+
email/password provider there is nothing to reduce — that form is already
|
| 307 |
+
the screen. Treating it as one suppressed the back chevron and the stage
|
| 308 |
+
heading, which is how the user ended up on a dead-end screen with an empty
|
| 309 |
+
address box and no way out. */
|
| 310 |
+
const onlyProvider =
|
| 311 |
+
activeError?.kind === "wrong_provider" && activeError.provider !== "email"
|
| 312 |
+
? activeError.provider
|
| 313 |
+
: null;
|
| 314 |
+
|
| 315 |
+
const stage = emailAuth.stage;
|
| 316 |
+
// Past the first step the user is inside a flow, so provider buttons are just
|
| 317 |
+
// noise — EXCEPT after a wrong-provider rejection, where the named provider is
|
| 318 |
+
// the only way forward and hiding it would strand the user on an error they
|
| 319 |
+
// cannot act on.
|
| 320 |
+
const midEmailFlow = stage.name !== "email" && onlyProvider === null;
|
| 321 |
+
// The email form hides for the mirror-image reason: once we know the account
|
| 322 |
+
// belongs to a social provider, a password is not a way in. (onlyProvider is
|
| 323 |
+
// never "email" — see above — so a narrowing always means "hide this form".)
|
| 324 |
+
const showEmailForm = onlyProvider === null;
|
| 325 |
+
// The password step reads differently depending on intent, so it is resolved
|
| 326 |
+
// here rather than from the static map.
|
| 327 |
+
const stageCopy =
|
| 328 |
+
onlyProvider !== null
|
| 329 |
+
? undefined
|
| 330 |
+
: stage.name === "password"
|
| 331 |
+
? stage.mode === "signup"
|
| 332 |
+
? { title: "Create your account", subtitle: "Choose a password to finish signing up." }
|
| 333 |
+
: { title: "Enter your password", subtitle: "Sign in with your email and password." }
|
| 334 |
+
: STAGE_COPY[stage.name];
|
| 335 |
+
|
| 336 |
+
// One list so adding a provider back is a single entry. Google is the only
|
| 337 |
+
// social provider now (Apple and Microsoft were removed), but the list shape
|
| 338 |
+
// is what drives the divider, the narrowing below and the row layout, so it
|
| 339 |
+
// stays a list rather than a hardcoded button.
|
| 340 |
+
const providers = [
|
| 341 |
+
{
|
| 342 |
+
id: "google",
|
| 343 |
+
enabled: true,
|
| 344 |
+
render: () => (
|
| 345 |
+
/* GIS renders a Google-hosted iframe, so it must mount only once this
|
| 346 |
+
container is laid out — i.e. after the modal is open. */
|
| 347 |
+
<GoogleLogin
|
| 348 |
+
onSuccess={signInWithGoogle}
|
| 349 |
+
onError={onGoogleError}
|
| 350 |
+
size="large"
|
| 351 |
+
shape="pill"
|
| 352 |
+
text="continue_with"
|
| 353 |
+
theme="outline"
|
| 354 |
+
width="300"
|
| 355 |
+
/>
|
| 356 |
+
),
|
| 357 |
+
},
|
| 358 |
+
].filter(
|
| 359 |
+
(p) =>
|
| 360 |
+
p.enabled &&
|
| 361 |
+
!midEmailFlow &&
|
| 362 |
+
(onlyProvider === null || onlyProvider === p.id)
|
| 363 |
+
);
|
| 364 |
+
|
| 365 |
+
const isPage = variant === "page";
|
| 366 |
+
COLUMN_WIDTH_CLASS = isPage ? "w-[340px]" : "w-[300px]";
|
| 367 |
+
|
| 368 |
+
return (
|
| 369 |
+
<>
|
| 370 |
+
{/* After a wrong-provider rejection the stage heading ("Enter your
|
| 371 |
+
password") contradicts what is on screen, so fall back to the
|
| 372 |
+
call site's own copy. */}
|
| 373 |
+
<div className={`relative flex items-center gap-2 ${isPage ? "justify-center" : ""}`}>
|
| 374 |
+
{midEmailFlow && (
|
| 375 |
+
<button
|
| 376 |
+
type="button"
|
| 377 |
+
onClick={emailAuth.back}
|
| 378 |
+
disabled={busy}
|
| 379 |
+
aria-label="Back"
|
| 380 |
+
className="absolute left-0 top-1/2 -translate-y-1/2 rounded-full p-1 text-gray-400 transition hover:bg-gray-100 hover:text-gray-600 disabled:opacity-40"
|
| 381 |
+
>
|
| 382 |
+
<svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden>
|
| 383 |
+
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
|
| 384 |
+
</svg>
|
| 385 |
+
</button>
|
| 386 |
+
)}
|
| 387 |
+
<h2
|
| 388 |
+
id={isPage ? "auth-page-title" : "login-modal-title"}
|
| 389 |
+
className={`font-semibold text-gray-900 ${isPage ? "text-2xl" : "text-lg"}`}
|
| 390 |
+
>
|
| 391 |
+
{stageCopy?.title ?? resolvedTitle}
|
| 392 |
+
</h2>
|
| 393 |
+
</div>
|
| 394 |
+
<p className={`mt-1 text-sm text-gray-600 ${isPage ? "text-center" : ""}`}>
|
| 395 |
+
{stageCopy?.subtitle ?? resolvedSubtitle}
|
| 396 |
+
</p>
|
| 397 |
+
|
| 398 |
+
<div className="mt-6">
|
| 399 |
+
{/* The spinner REPLACES the body only for social sign-in. Swapping the
|
| 400 |
+
email form out would unmount it, and remounting resets its field
|
| 401 |
+
state — so a rejected password would come back to an empty box and
|
| 402 |
+
the user could not act on the error they were just shown. During an
|
| 403 |
+
email request the form stays mounted and disables itself instead. */}
|
| 404 |
+
{signingIn ? (
|
| 405 |
+
<div className="flex flex-col items-center gap-4 py-6">
|
| 406 |
+
<div className="h-7 w-7 animate-spin rounded-full border-2 border-gray-200 border-t-purple-600" />
|
| 407 |
+
<p className="text-sm text-gray-600">
|
| 408 |
+
{reactivating ? "Reactivating your account…" : "Signing you in…"}
|
| 409 |
+
</p>
|
| 410 |
+
</div>
|
| 411 |
+
) : (
|
| 412 |
+
<div className="flex flex-col items-center gap-4">
|
| 413 |
+
{/* In-app browsers block OAuth popups, so the provider buttons are
|
| 414 |
+
useless there — but email/password needs no popup and works
|
| 415 |
+
fine, so the escape notice now sits ABOVE the email form
|
| 416 |
+
rather than replacing every way in. */}
|
| 417 |
+
{inApp && (
|
| 418 |
+
<InAppEscape
|
| 419 |
+
showInstructions={showInstructions}
|
| 420 |
+
copied={copied}
|
| 421 |
+
onEscape={handleEscape}
|
| 422 |
+
onCopy={handleCopy}
|
| 423 |
+
/>
|
| 424 |
+
)}
|
| 425 |
+
|
| 426 |
+
{/* Field-level failures render under the field they belong to, so
|
| 427 |
+
the message sits where the user is looking and where the fix
|
| 428 |
+
is. Only errors that are about the whole modal — the wrong
|
| 429 |
+
provider, a deleted account and its Reactivate button — stay up
|
| 430 |
+
here as a banner.
|
| 431 |
+
|
| 432 |
+
"Already registered" is excluded while the form is showing its
|
| 433 |
+
own persistent notice for it: the banner would say the same
|
| 434 |
+
thing twice, and would then vanish on the next submit while the
|
| 435 |
+
inline one (the accurate, lasting explanation) remains. */}
|
| 436 |
+
{activeError &&
|
| 437 |
+
!isFieldLevelError(activeError) &&
|
| 438 |
+
activeError.kind !== "account_deleted" &&
|
| 439 |
+
!(switchedToLoginNotice && isExistingAccountError(activeError)) && (
|
| 440 |
+
<LoginErrorNotice error={activeError} />
|
| 441 |
+
)}
|
| 442 |
+
|
| 443 |
+
{/* One fixed-width row per provider. Google Identity Services
|
| 444 |
+
renders its own iframe and does not honour `width` exactly, so
|
| 445 |
+
the row — not the button — defines the box; our own buttons
|
| 446 |
+
stretch to fill it and GIS is centred inside it. That keeps all
|
| 447 |
+
three the same width even though one is not ours to style. */}
|
| 448 |
+
{!inApp &&
|
| 449 |
+
providers.map((p) => (
|
| 450 |
+
<div key={p.id} className={`flex ${COLUMN_WIDTH_CLASS} max-w-full justify-center`}>
|
| 451 |
+
{p.render()}
|
| 452 |
+
</div>
|
| 453 |
+
))}
|
| 454 |
+
|
| 455 |
+
{showEmailForm && (
|
| 456 |
+
<>
|
| 457 |
+
{!inApp && !midEmailFlow && providers.length > 0 && (
|
| 458 |
+
<div className={`flex ${COLUMN_WIDTH_CLASS} max-w-full items-center gap-3 py-1`}>
|
| 459 |
+
<span className="h-px flex-1 bg-gray-200" />
|
| 460 |
+
<span className="text-xs uppercase tracking-wide text-gray-400">
|
| 461 |
+
or
|
| 462 |
+
</span>
|
| 463 |
+
<span className="h-px flex-1 bg-gray-200" />
|
| 464 |
+
</div>
|
| 465 |
+
)}
|
| 466 |
+
<EmailAuthForm
|
| 467 |
+
auth={emailAuth}
|
| 468 |
+
busy={emailAuth.busy}
|
| 469 |
+
onDismissSocialError={dismissError}
|
| 470 |
+
/>
|
| 471 |
+
</>
|
| 472 |
+
)}
|
| 473 |
+
</div>
|
| 474 |
+
)}
|
| 475 |
+
</div>
|
| 476 |
+
|
| 477 |
+
{!inApp && (
|
| 478 |
+
<p className="mt-6 text-center text-xs leading-relaxed text-gray-400">
|
| 479 |
+
By continuing you agree to our{" "}
|
| 480 |
+
<a href="/terms" className="underline hover:text-gray-600">Terms</a> and{" "}
|
| 481 |
+
<a href="/privacy" className="underline hover:text-gray-600">Privacy Policy</a>.
|
| 482 |
+
</p>
|
| 483 |
+
)}
|
| 484 |
+
|
| 485 |
+
{/* Asks the one question the 403 raises. The email flow holds the typed
|
| 486 |
+
credential for the retry; the social flow holds the provider token. */}
|
| 487 |
+
{deletedError && (
|
| 488 |
+
<ReactivateConfirm
|
| 489 |
+
busy={busy}
|
| 490 |
+
body={
|
| 491 |
+
deletedError === "forgot"
|
| 492 |
+
? "Your account was deleted. Reactivating will email you a code so you can set a new password and sign in."
|
| 493 |
+
: "Your account was deleted. Do you want to proceed with reactivating?"
|
| 494 |
+
}
|
| 495 |
+
onConfirm={deletedError === "social" ? reactivate : emailAuth.reactivate}
|
| 496 |
+
onCancel={deletedError === "social" ? dismissError : emailAuth.dismissError}
|
| 497 |
+
/>
|
| 498 |
+
)}
|
| 499 |
+
</>
|
| 500 |
+
);
|
| 501 |
+
}
|
| 502 |
+
|
| 503 |
+
/**
|
| 504 |
+
* The staged email + password form.
|
| 505 |
+
*
|
| 506 |
+
* Every stage is a plain controlled form — no zod, no react-hook-form, matching
|
| 507 |
+
* the rest of the app (see ContactModal). The address is never probed for
|
| 508 |
+
* existence before the password step: an "is this registered?" endpoint would be
|
| 509 |
+
* an enumeration oracle with no other purpose, so instead everyone reaches the
|
| 510 |
+
* password step and the sign-in result disambiguates.
|
| 511 |
+
*/
|
| 512 |
+
function EmailAuthForm({
|
| 513 |
+
auth,
|
| 514 |
+
busy,
|
| 515 |
+
onDismissSocialError,
|
| 516 |
+
}: {
|
| 517 |
+
auth: ReturnType<typeof useEmailAuth>;
|
| 518 |
+
busy: boolean;
|
| 519 |
+
/** Clears useSocialLogin's error, which auth.setMode cannot reach. */
|
| 520 |
+
onDismissSocialError?: () => void;
|
| 521 |
+
}) {
|
| 522 |
+
const { stage } = auth;
|
| 523 |
+
// The address lives on the stage, not in local state: an error can route the
|
| 524 |
+
// user between stages, and a remount would wipe a local copy — which is how
|
| 525 |
+
// they ended up staring at an empty box under "sign in with your password".
|
| 526 |
+
const email = stage.name === "email" ? stage.email : "";
|
| 527 |
+
const setEmail = auth.setEmailValue;
|
| 528 |
+
const [password, setPassword] = useState("");
|
| 529 |
+
const [confirmPassword, setConfirmPassword] = useState("");
|
| 530 |
+
const [code, setCode] = useState("");
|
| 531 |
+
const [newPassword, setNewPassword] = useState("");
|
| 532 |
+
const [showPassword, setShowPassword] = useState(false);
|
| 533 |
+
|
| 534 |
+
// Clear the step-local fields on a stage CHANGE, so a code typed for a burned
|
| 535 |
+
// attempt doesn't linger into the next step. Deliberately keyed on the stage
|
| 536 |
+
// name only: a failed request leaves the stage unchanged, so the password the
|
| 537 |
+
// user just typed survives for them to correct or to register with.
|
| 538 |
+
const stageName = stage.name;
|
| 539 |
+
useEffect(() => {
|
| 540 |
+
setCode("");
|
| 541 |
+
setNewPassword("");
|
| 542 |
+
setConfirmPassword("");
|
| 543 |
+
setShowPassword(false);
|
| 544 |
+
if (stageName === "email" || stageName === "password") setPassword("");
|
| 545 |
+
}, [stageName]);
|
| 546 |
+
|
| 547 |
+
// The signup -> sign-in flip is the one transition that does NOT change
|
| 548 |
+
// stage.name, so the effect above cannot catch it and the password the user
|
| 549 |
+
// chose for a NEW account would stay in the box under a "Sign in" button.
|
| 550 |
+
// Submitting that is either a confusing "email and password don't match" that
|
| 551 |
+
// buries the real reason, or — if the two happen to match — an unrequested
|
| 552 |
+
// sign-in. Clear it and make them type the password for the account that
|
| 553 |
+
// actually exists.
|
| 554 |
+
const switchedFromSignup =
|
| 555 |
+
stage.name === "password" && stage.switchedFromSignup === true;
|
| 556 |
+
useEffect(() => {
|
| 557 |
+
if (switchedFromSignup) {
|
| 558 |
+
setPassword("");
|
| 559 |
+
setConfirmPassword("");
|
| 560 |
+
}
|
| 561 |
+
}, [switchedFromSignup]);
|
| 562 |
+
|
| 563 |
+
const stageEmail = "email" in stage ? stage.email : "";
|
| 564 |
+
|
| 565 |
+
switch (stage.name) {
|
| 566 |
+
case "email": {
|
| 567 |
+
const signup = stage.mode === "signup";
|
| 568 |
+
return (
|
| 569 |
+
<form
|
| 570 |
+
className={`${COLUMN_WIDTH_CLASS} max-w-full space-y-3`}
|
| 571 |
+
onSubmit={(e) => {
|
| 572 |
+
e.preventDefault();
|
| 573 |
+
if (email.trim()) auth.submitEmail(email, stage.mode);
|
| 574 |
+
}}
|
| 575 |
+
>
|
| 576 |
+
<input
|
| 577 |
+
id="login-email"
|
| 578 |
+
type="email"
|
| 579 |
+
required
|
| 580 |
+
autoComplete="email"
|
| 581 |
+
placeholder="you@example.com"
|
| 582 |
+
value={email}
|
| 583 |
+
onChange={(e) => setEmail(e.target.value)}
|
| 584 |
+
className={INPUT_CLASS}
|
| 585 |
+
aria-label="Email address"
|
| 586 |
+
/>
|
| 587 |
+
<button
|
| 588 |
+
type="submit"
|
| 589 |
+
disabled={busy || !email.trim()}
|
| 590 |
+
className={PRIMARY_BUTTON_CLASS}
|
| 591 |
+
>
|
| 592 |
+
{/* Both modes read "Continue": this step only collects the address,
|
| 593 |
+
and the mode is already stated by the toggle below. The specific
|
| 594 |
+
verb belongs on the next step, where the action actually happens. */}
|
| 595 |
+
Continue
|
| 596 |
+
</button>
|
| 597 |
+
{/* Both intents are offered up front. The mode only decides which
|
| 598 |
+
request the next step fires — getting it wrong is recoverable in
|
| 599 |
+
one click, so this is a convenience, not a gate. */}
|
| 600 |
+
<p className="pt-1 text-center text-sm text-gray-500">
|
| 601 |
+
{signup ? "Already have an account?" : "Don't have an account?"}{" "}
|
| 602 |
+
<button
|
| 603 |
+
type="button"
|
| 604 |
+
onClick={() => {
|
| 605 |
+
// Clear BOTH hooks' errors. auth.setMode only clears the email
|
| 606 |
+
// hook's; a social wrong-provider rejection lives in the other
|
| 607 |
+
// one, and leaving it up would keep the banner, keep the
|
| 608 |
+
// provider list narrowed, and keep the back chevron hidden on a
|
| 609 |
+
// screen the user has deliberately moved away from.
|
| 610 |
+
onDismissSocialError?.();
|
| 611 |
+
auth.setMode(signup ? "login" : "signup");
|
| 612 |
+
}}
|
| 613 |
+
className="font-medium text-purple-600 underline hover:text-purple-700"
|
| 614 |
+
>
|
| 615 |
+
{signup ? "Sign in" : "Sign up"}
|
| 616 |
+
</button>
|
| 617 |
+
</p>
|
| 618 |
+
</form>
|
| 619 |
+
);
|
| 620 |
+
}
|
| 621 |
+
|
| 622 |
+
case "password": {
|
| 623 |
+
const signup = stage.mode === "signup";
|
| 624 |
+
// Only complain about a mismatch once they've actually started the second
|
| 625 |
+
// field — flagging one they haven't reached yet reads as an error.
|
| 626 |
+
const mismatch = signup && confirmPassword.length > 0 && confirmPassword !== password;
|
| 627 |
+
// Deliberately NOT gated on the password policy or the confirm match.
|
| 628 |
+
//
|
| 629 |
+
// The live checklist and the mismatch hint already guide someone writing a
|
| 630 |
+
// real new password. But when the address ALREADY has an account, none of
|
| 631 |
+
// that is the point: blocking submit means the request is never made, so
|
| 632 |
+
// the one thing the user needs to hear — "this account exists, sign in" —
|
| 633 |
+
// can never be said, and pressing the button appears to do nothing. Let it
|
| 634 |
+
// through and let the server answer; a genuine policy violation comes back
|
| 635 |
+
// as a 422 and renders inline under the field, which is the same place the
|
| 636 |
+
// checklist already points.
|
| 637 |
+
const canSubmit = !busy && Boolean(password);
|
| 638 |
+
return (
|
| 639 |
+
<form
|
| 640 |
+
className={`${COLUMN_WIDTH_CLASS} max-w-full space-y-3`}
|
| 641 |
+
onSubmit={(e) => {
|
| 642 |
+
e.preventDefault();
|
| 643 |
+
if (canSubmit) auth.submitPassword(stageEmail, password, stage.mode);
|
| 644 |
+
}}
|
| 645 |
+
>
|
| 646 |
+
<p className="truncate text-sm text-gray-500">{stageEmail}</p>
|
| 647 |
+
{/* Why the form changed under them. The error banner cannot carry this:
|
| 648 |
+
it is cleared by the next submit, so the moment they try the password
|
| 649 |
+
the reason they were moved here disappears — and if that submit fails
|
| 650 |
+
it is replaced by "email and password don't match", which explains
|
| 651 |
+
nothing. This is part of the form, so it stays until they leave. */}
|
| 652 |
+
{switchedFromSignup && (
|
| 653 |
+
<p className="text-left text-xs leading-relaxed text-amber-600">
|
| 654 |
+
This email already has an account. Enter its password to sign in, or{" "}
|
| 655 |
+
<button
|
| 656 |
+
type="button"
|
| 657 |
+
onClick={() => auth.startForgot(stageEmail)}
|
| 658 |
+
className="font-medium underline hover:text-amber-700"
|
| 659 |
+
>
|
| 660 |
+
reset your password
|
| 661 |
+
</button>
|
| 662 |
+
.
|
| 663 |
+
</p>
|
| 664 |
+
)}
|
| 665 |
+
<PasswordInput
|
| 666 |
+
id="login-password"
|
| 667 |
+
label="Password"
|
| 668 |
+
placeholder={signup ? "Choose a password" : "Enter your password"}
|
| 669 |
+
value={password}
|
| 670 |
+
onChange={setPassword}
|
| 671 |
+
autoComplete={signup ? "new-password" : "current-password"}
|
| 672 |
+
autoFocus
|
| 673 |
+
visible={showPassword}
|
| 674 |
+
onToggleVisible={() => setShowPassword((v) => !v)}
|
| 675 |
+
invalid={isFieldLevelError(auth.error)}
|
| 676 |
+
/>
|
| 677 |
+
{/* A rejected credential belongs here, beneath the box the user has to
|
| 678 |
+
retype — not in a banner above the heading. */}
|
| 679 |
+
{isFieldLevelError(auth.error) && <FieldError>{auth.error?.message}</FieldError>}
|
| 680 |
+
{signup && (
|
| 681 |
+
<>
|
| 682 |
+
<PasswordInput
|
| 683 |
+
id="login-password-confirm"
|
| 684 |
+
label="Confirm password"
|
| 685 |
+
placeholder="Re-enter your password"
|
| 686 |
+
value={confirmPassword}
|
| 687 |
+
onChange={setConfirmPassword}
|
| 688 |
+
autoComplete="new-password"
|
| 689 |
+
visible={showPassword}
|
| 690 |
+
onToggleVisible={() => setShowPassword((v) => !v)}
|
| 691 |
+
invalid={mismatch}
|
| 692 |
+
/>
|
| 693 |
+
{mismatch && <FieldError>Passwords don't match.</FieldError>}
|
| 694 |
+
{/* A live checklist rather than a sentence: with three rules, being
|
| 695 |
+
told what was wrong only after submitting is the frustrating
|
| 696 |
+
version of this. */}
|
| 697 |
+
<ul className="space-y-0.5 pt-0.5">
|
| 698 |
+
{PASSWORD_RULES.map((rule) => {
|
| 699 |
+
const ok = rule.test(password);
|
| 700 |
+
return (
|
| 701 |
+
<li
|
| 702 |
+
key={rule.label}
|
| 703 |
+
className={`flex items-center gap-1.5 text-xs ${
|
| 704 |
+
ok ? "text-green-600" : "text-gray-400"
|
| 705 |
+
}`}
|
| 706 |
+
>
|
| 707 |
+
<span aria-hidden>{ok ? "✓" : "○"}</span>
|
| 708 |
+
{rule.label}
|
| 709 |
+
</li>
|
| 710 |
+
);
|
| 711 |
+
})}
|
| 712 |
+
</ul>
|
| 713 |
+
</>
|
| 714 |
+
)}
|
| 715 |
+
<button type="submit" disabled={!canSubmit} className={PRIMARY_BUTTON_CLASS}>
|
| 716 |
+
{/* A reactivation runs through the same login request, so `busy`
|
| 717 |
+
alone would mislabel it "Signing in…" while the confirm dialog
|
| 718 |
+
above says "Reactivating…". */}
|
| 719 |
+
{busy
|
| 720 |
+
? auth.reactivating
|
| 721 |
+
? "Reactivating…"
|
| 722 |
+
: signup
|
| 723 |
+
? "Sending code…"
|
| 724 |
+
: "Signing in…"
|
| 725 |
+
: signup
|
| 726 |
+
? "Sign up"
|
| 727 |
+
: "Sign in"}
|
| 728 |
+
</button>
|
| 729 |
+
{/* No mode toggle here: the intent was chosen on step one and the back
|
| 730 |
+
chevron returns there, so repeating the choice is noise. Forgot
|
| 731 |
+
password stays — it's a different action, not a restatement. */}
|
| 732 |
+
{!signup && (
|
| 733 |
+
<button
|
| 734 |
+
type="button"
|
| 735 |
+
onClick={() => auth.startForgot(stageEmail)}
|
| 736 |
+
className="text-sm text-gray-500 underline hover:text-gray-700"
|
| 737 |
+
>
|
| 738 |
+
Forgot password?
|
| 739 |
+
</button>
|
| 740 |
+
)}
|
| 741 |
+
</form>
|
| 742 |
+
);
|
| 743 |
+
}
|
| 744 |
+
|
| 745 |
+
case "otp":
|
| 746 |
+
return (
|
| 747 |
+
<CodeForm
|
| 748 |
+
email={stageEmail}
|
| 749 |
+
code={code}
|
| 750 |
+
setCode={setCode}
|
| 751 |
+
resendAt={stage.resendAt}
|
| 752 |
+
busy={busy}
|
| 753 |
+
error={auth.error}
|
| 754 |
+
onSubmit={() => auth.submitCode(stageEmail, code)}
|
| 755 |
+
onResend={() => auth.resendCode(stageEmail)}
|
| 756 |
+
/>
|
| 757 |
+
);
|
| 758 |
+
|
| 759 |
+
case "forgot_email":
|
| 760 |
+
return (
|
| 761 |
+
<form
|
| 762 |
+
className={`${COLUMN_WIDTH_CLASS} max-w-full space-y-3`}
|
| 763 |
+
onSubmit={(e) => {
|
| 764 |
+
e.preventDefault();
|
| 765 |
+
if (stageEmail) auth.requestResetCode(stageEmail);
|
| 766 |
+
}}
|
| 767 |
+
>
|
| 768 |
+
<p className="truncate text-sm text-gray-500">{stageEmail}</p>
|
| 769 |
+
<button type="submit" disabled={busy} className={PRIMARY_BUTTON_CLASS}>
|
| 770 |
+
{busy ? "Sending…" : "Email me a reset code"}
|
| 771 |
+
</button>
|
| 772 |
+
</form>
|
| 773 |
+
);
|
| 774 |
+
|
| 775 |
+
case "forgot_code":
|
| 776 |
+
return (
|
| 777 |
+
<CodeForm
|
| 778 |
+
email={stageEmail}
|
| 779 |
+
code={code}
|
| 780 |
+
setCode={setCode}
|
| 781 |
+
resendAt={stage.resendAt}
|
| 782 |
+
busy={busy}
|
| 783 |
+
error={auth.error}
|
| 784 |
+
submitLabel="Continue"
|
| 785 |
+
onSubmit={() => auth.submitResetCode(stageEmail, code)}
|
| 786 |
+
onResend={() => auth.requestResetCode(stageEmail)}
|
| 787 |
+
/>
|
| 788 |
+
);
|
| 789 |
+
|
| 790 |
+
case "forgot_password": {
|
| 791 |
+
// Setting a password, so it gets the same rules and the same confirmation
|
| 792 |
+
// as signup — the server enforces them here either way.
|
| 793 |
+
const resetMismatch = confirmPassword.length > 0 && confirmPassword !== newPassword;
|
| 794 |
+
const resetOk =
|
| 795 |
+
!busy && passwordMeetsPolicy(newPassword) && confirmPassword === newPassword;
|
| 796 |
+
return (
|
| 797 |
+
<form
|
| 798 |
+
className={`${COLUMN_WIDTH_CLASS} max-w-full space-y-3`}
|
| 799 |
+
onSubmit={(e) => {
|
| 800 |
+
e.preventDefault();
|
| 801 |
+
if (resetOk) auth.completeReset(stageEmail, stage.code, newPassword);
|
| 802 |
+
}}
|
| 803 |
+
>
|
| 804 |
+
<PasswordInput
|
| 805 |
+
id="reset-password"
|
| 806 |
+
label="New password"
|
| 807 |
+
placeholder="Choose a new password"
|
| 808 |
+
value={newPassword}
|
| 809 |
+
onChange={setNewPassword}
|
| 810 |
+
autoComplete="new-password"
|
| 811 |
+
autoFocus
|
| 812 |
+
visible={showPassword}
|
| 813 |
+
onToggleVisible={() => setShowPassword((v) => !v)}
|
| 814 |
+
invalid={isFieldLevelError(auth.error)}
|
| 815 |
+
/>
|
| 816 |
+
{isFieldLevelError(auth.error) && <FieldError>{auth.error?.message}</FieldError>}
|
| 817 |
+
<PasswordInput
|
| 818 |
+
id="reset-password-confirm"
|
| 819 |
+
label="Confirm new password"
|
| 820 |
+
placeholder="Re-enter your new password"
|
| 821 |
+
value={confirmPassword}
|
| 822 |
+
onChange={setConfirmPassword}
|
| 823 |
+
autoComplete="new-password"
|
| 824 |
+
visible={showPassword}
|
| 825 |
+
onToggleVisible={() => setShowPassword((v) => !v)}
|
| 826 |
+
invalid={resetMismatch}
|
| 827 |
+
/>
|
| 828 |
+
{resetMismatch && <FieldError>Passwords don't match.</FieldError>}
|
| 829 |
+
<ul className="space-y-0.5 pt-0.5">
|
| 830 |
+
{PASSWORD_RULES.map((rule) => {
|
| 831 |
+
const ok = rule.test(newPassword);
|
| 832 |
+
return (
|
| 833 |
+
<li
|
| 834 |
+
key={rule.label}
|
| 835 |
+
className={`flex items-center gap-1.5 text-xs ${
|
| 836 |
+
ok ? "text-green-600" : "text-gray-400"
|
| 837 |
+
}`}
|
| 838 |
+
>
|
| 839 |
+
<span aria-hidden>{ok ? "✓" : "○"}</span>
|
| 840 |
+
{rule.label}
|
| 841 |
+
</li>
|
| 842 |
+
);
|
| 843 |
+
})}
|
| 844 |
+
</ul>
|
| 845 |
+
<button type="submit" disabled={!resetOk} className={PRIMARY_BUTTON_CLASS}>
|
| 846 |
+
Set password and sign in
|
| 847 |
+
</button>
|
| 848 |
+
</form>
|
| 849 |
+
);
|
| 850 |
+
}
|
| 851 |
+
|
| 852 |
+
default:
|
| 853 |
+
return null;
|
| 854 |
+
}
|
| 855 |
+
}
|
| 856 |
+
|
| 857 |
+
/**
|
| 858 |
+
* Password field with a reveal toggle.
|
| 859 |
+
*
|
| 860 |
+
* The toggle is icon-only, so it carries an aria-label that flips with the state
|
| 861 |
+
* — without one it is an unlabelled button to a screen reader. type="button"
|
| 862 |
+
* keeps it from submitting the form it sits inside.
|
| 863 |
+
*/
|
| 864 |
+
function PasswordInput({
|
| 865 |
+
id,
|
| 866 |
+
label,
|
| 867 |
+
value,
|
| 868 |
+
onChange,
|
| 869 |
+
placeholder,
|
| 870 |
+
autoComplete,
|
| 871 |
+
autoFocus,
|
| 872 |
+
visible,
|
| 873 |
+
onToggleVisible,
|
| 874 |
+
invalid,
|
| 875 |
+
}: {
|
| 876 |
+
id: string;
|
| 877 |
+
/** The field's accessible name. Not rendered — the design is placeholder-only,
|
| 878 |
+
* so this is what a screen reader announces instead. */
|
| 879 |
+
label: string;
|
| 880 |
+
value: string;
|
| 881 |
+
onChange: (v: string) => void;
|
| 882 |
+
/** Hint inside the box; falls back to the label when omitted. */
|
| 883 |
+
placeholder?: string;
|
| 884 |
+
autoComplete: string;
|
| 885 |
+
autoFocus?: boolean;
|
| 886 |
+
visible: boolean;
|
| 887 |
+
onToggleVisible: () => void;
|
| 888 |
+
invalid?: boolean;
|
| 889 |
+
}) {
|
| 890 |
+
return (
|
| 891 |
+
<div className="relative">
|
| 892 |
+
<input
|
| 893 |
+
id={id}
|
| 894 |
+
type={visible ? "text" : "password"}
|
| 895 |
+
required
|
| 896 |
+
autoFocus={autoFocus}
|
| 897 |
+
autoComplete={autoComplete}
|
| 898 |
+
placeholder={placeholder ?? label}
|
| 899 |
+
value={value}
|
| 900 |
+
onChange={(e) => onChange(e.target.value)}
|
| 901 |
+
className={`${INPUT_CLASS} pr-10 ${invalid ? "border-red-400 focus:border-red-500 focus:ring-red-100" : ""}`}
|
| 902 |
+
aria-label={label}
|
| 903 |
+
aria-invalid={invalid || undefined}
|
| 904 |
+
/>
|
| 905 |
+
<button
|
| 906 |
+
type="button"
|
| 907 |
+
onClick={onToggleVisible}
|
| 908 |
+
aria-label={visible ? "Hide password" : "Show password"}
|
| 909 |
+
className="absolute right-2 top-1/2 -translate-y-1/2 rounded p-1 text-gray-400 transition hover:text-gray-600"
|
| 910 |
+
>
|
| 911 |
+
<svg
|
| 912 |
+
className="h-4 w-4"
|
| 913 |
+
fill="none"
|
| 914 |
+
stroke="currentColor"
|
| 915 |
+
strokeWidth={1.8}
|
| 916 |
+
viewBox="0 0 24 24"
|
| 917 |
+
aria-hidden
|
| 918 |
+
>
|
| 919 |
+
{visible ? (
|
| 920 |
+
<>
|
| 921 |
+
<path
|
| 922 |
+
strokeLinecap="round"
|
| 923 |
+
strokeLinejoin="round"
|
| 924 |
+
d="M3.98 8.223A10.477 10.477 0 001.934 12C3.226 16.338 7.244 19.5 12 19.5c.993 0 1.953-.138 2.863-.395M6.228 6.228A10.45 10.45 0 0112 4.5c4.756 0 8.774 3.162 10.066 7.498a10.523 10.523 0 01-4.293 5.774M6.228 6.228L3 3m3.228 3.228l3.65 3.65m7.894 7.894L21 21m-3.228-3.228l-3.65-3.65m0 0a3 3 0 10-4.243-4.243m4.242 4.242L9.88 9.88"
|
| 925 |
+
/>
|
| 926 |
+
</>
|
| 927 |
+
) : (
|
| 928 |
+
<>
|
| 929 |
+
<path
|
| 930 |
+
strokeLinecap="round"
|
| 931 |
+
strokeLinejoin="round"
|
| 932 |
+
d="M2.036 12.322a1.012 1.012 0 010-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178z"
|
| 933 |
+
/>
|
| 934 |
+
<path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
|
| 935 |
+
</>
|
| 936 |
+
)}
|
| 937 |
+
</svg>
|
| 938 |
+
</button>
|
| 939 |
+
</div>
|
| 940 |
+
);
|
| 941 |
+
}
|
| 942 |
+
|
| 943 |
+
/** Shared 6-digit code entry with a resend countdown. */
|
| 944 |
+
function CodeForm({
|
| 945 |
+
email,
|
| 946 |
+
code,
|
| 947 |
+
setCode,
|
| 948 |
+
resendAt,
|
| 949 |
+
busy,
|
| 950 |
+
error,
|
| 951 |
+
submitLabel = "Verify",
|
| 952 |
+
onSubmit,
|
| 953 |
+
onResend,
|
| 954 |
+
}: {
|
| 955 |
+
email: string;
|
| 956 |
+
code: string;
|
| 957 |
+
setCode: (v: string) => void;
|
| 958 |
+
resendAt: number;
|
| 959 |
+
busy: boolean;
|
| 960 |
+
/** Field-level failure for this code, shown under the input. */
|
| 961 |
+
error?: LoginError | null;
|
| 962 |
+
submitLabel?: string;
|
| 963 |
+
onSubmit: () => void;
|
| 964 |
+
onResend: () => void;
|
| 965 |
+
}) {
|
| 966 |
+
const [secondsLeft, setSecondsLeft] = useState(() =>
|
| 967 |
+
Math.max(0, Math.ceil((resendAt - Date.now()) / 1000))
|
| 968 |
+
);
|
| 969 |
+
|
| 970 |
+
useEffect(() => {
|
| 971 |
+
setSecondsLeft(Math.max(0, Math.ceil((resendAt - Date.now()) / 1000)));
|
| 972 |
+
const t = setInterval(() => {
|
| 973 |
+
setSecondsLeft(Math.max(0, Math.ceil((resendAt - Date.now()) / 1000)));
|
| 974 |
+
}, 1000);
|
| 975 |
+
return () => clearInterval(t);
|
| 976 |
+
}, [resendAt]);
|
| 977 |
+
|
| 978 |
+
return (
|
| 979 |
+
<form
|
| 980 |
+
className={`${COLUMN_WIDTH_CLASS} max-w-full space-y-3`}
|
| 981 |
+
onSubmit={(e) => {
|
| 982 |
+
e.preventDefault();
|
| 983 |
+
if (code.length === 6) onSubmit();
|
| 984 |
+
}}
|
| 985 |
+
>
|
| 986 |
+
<p className="truncate text-sm text-gray-500">{email}</p>
|
| 987 |
+
<input
|
| 988 |
+
// Kept as text, never a number input: codes are zero-padded strings and
|
| 989 |
+
// "039123" would lose its leading zero. inputMode gets the numeric
|
| 990 |
+
// keypad on mobile, and one-time-code lets the OS autofill it.
|
| 991 |
+
type="text"
|
| 992 |
+
inputMode="numeric"
|
| 993 |
+
autoComplete="one-time-code"
|
| 994 |
+
pattern="\d{6}"
|
| 995 |
+
maxLength={6}
|
| 996 |
+
required
|
| 997 |
+
autoFocus
|
| 998 |
+
placeholder="123456"
|
| 999 |
+
value={code}
|
| 1000 |
+
onChange={(e) => setCode(e.target.value.replace(/\D/g, "").slice(0, 6))}
|
| 1001 |
+
className={`${INPUT_CLASS} text-center text-lg tracking-[0.5em] ${
|
| 1002 |
+
isFieldLevelError(error ?? null) ? "border-red-400" : ""
|
| 1003 |
+
}`}
|
| 1004 |
+
aria-label="6-digit code"
|
| 1005 |
+
aria-invalid={isFieldLevelError(error ?? null) || undefined}
|
| 1006 |
+
/>
|
| 1007 |
+
{isFieldLevelError(error ?? null) && <FieldError>{error?.message}</FieldError>}
|
| 1008 |
+
<button
|
| 1009 |
+
type="submit"
|
| 1010 |
+
disabled={busy || code.length !== 6}
|
| 1011 |
+
className={PRIMARY_BUTTON_CLASS}
|
| 1012 |
+
>
|
| 1013 |
+
{busy ? "Checking…" : submitLabel}
|
| 1014 |
+
</button>
|
| 1015 |
+
<button
|
| 1016 |
+
type="button"
|
| 1017 |
+
onClick={onResend}
|
| 1018 |
+
disabled={busy || secondsLeft > 0}
|
| 1019 |
+
className="w-full text-sm text-gray-500 underline hover:text-gray-700 disabled:no-underline disabled:opacity-50"
|
| 1020 |
+
>
|
| 1021 |
+
{secondsLeft > 0 ? `Resend code in ${secondsLeft}s` : "Resend code"}
|
| 1022 |
+
</button>
|
| 1023 |
+
</form>
|
| 1024 |
+
);
|
| 1025 |
+
}
|
| 1026 |
+
|
| 1027 |
+
/** Error banner for failures that concern the whole modal. */
|
| 1028 |
+
function LoginErrorNotice({ error }: { error: LoginError }) {
|
| 1029 |
+
// The wrong-provider case is informational and self-contained, so it reads as
|
| 1030 |
+
// plain amber text; everything else keeps the box.
|
| 1031 |
+
if (error.kind === "wrong_provider") {
|
| 1032 |
+
return (
|
| 1033 |
+
<p className="w-full text-left text-sm text-amber-600">{error.message}</p>
|
| 1034 |
+
);
|
| 1035 |
+
}
|
| 1036 |
+
|
| 1037 |
+
return (
|
| 1038 |
+
<div className="w-full rounded-xl border border-red-200 bg-red-50 p-3 text-left text-sm text-red-700">
|
| 1039 |
+
<p>{error.message}</p>
|
| 1040 |
+
</div>
|
| 1041 |
+
);
|
| 1042 |
+
}
|
| 1043 |
+
|
| 1044 |
+
/**
|
| 1045 |
+
* Confirmation dialog for reactivating a soft-deleted account.
|
| 1046 |
+
*
|
| 1047 |
+
* Its own dialog rather than a button inside an error banner, because this is a
|
| 1048 |
+
* consequential, one-way choice: the backend restores the account as a FREE user
|
| 1049 |
+
* and clears purchased bonuses. A confirm step with an explicit Cancel makes the
|
| 1050 |
+
* trade visible instead of hiding it behind a single click on a red notice.
|
| 1051 |
+
*
|
| 1052 |
+
* Rendered ABOVE the login modal (z-[110] over its z-[100]) so it reads as a
|
| 1053 |
+
* question about the screen behind it, and the backdrop is inert while the
|
| 1054 |
+
* request is in flight to avoid orphaning it.
|
| 1055 |
+
*/
|
| 1056 |
+
function ReactivateConfirm({
|
| 1057 |
+
busy,
|
| 1058 |
+
body,
|
| 1059 |
+
onConfirm,
|
| 1060 |
+
onCancel,
|
| 1061 |
+
}: {
|
| 1062 |
+
busy: boolean;
|
| 1063 |
+
/** What happens on confirm. Differs by route: reactivating from the login step
|
| 1064 |
+
* signs the user straight in, while from the forgot-password step it only
|
| 1065 |
+
* emails a code — saying so avoids promising a session they won't get yet. */
|
| 1066 |
+
body: string;
|
| 1067 |
+
onConfirm: () => void;
|
| 1068 |
+
onCancel: () => void;
|
| 1069 |
+
}) {
|
| 1070 |
+
useEffect(() => {
|
| 1071 |
+
const onKey = (e: KeyboardEvent) => {
|
| 1072 |
+
if (e.key === "Escape" && !busy) onCancel();
|
| 1073 |
+
};
|
| 1074 |
+
document.addEventListener("keydown", onKey);
|
| 1075 |
+
return () => document.removeEventListener("keydown", onKey);
|
| 1076 |
+
}, [busy, onCancel]);
|
| 1077 |
+
|
| 1078 |
+
return ReactDOM.createPortal(
|
| 1079 |
+
<div className="fixed inset-0 z-[110] flex items-center justify-center p-4">
|
| 1080 |
+
<div
|
| 1081 |
+
className="absolute inset-0 bg-black/50 backdrop-blur-sm"
|
| 1082 |
+
onClick={busy ? undefined : onCancel}
|
| 1083 |
+
aria-hidden
|
| 1084 |
+
/>
|
| 1085 |
+
<div
|
| 1086 |
+
className="relative mx-4 w-full max-w-sm rounded-2xl border border-gray-200 bg-white px-6 py-6 shadow-2xl"
|
| 1087 |
+
role="alertdialog"
|
| 1088 |
+
aria-modal="true"
|
| 1089 |
+
aria-labelledby="reactivate-title"
|
| 1090 |
+
aria-describedby="reactivate-body"
|
| 1091 |
+
>
|
| 1092 |
+
<h2 id="reactivate-title" className="text-lg font-semibold text-gray-900">
|
| 1093 |
+
Reactivate your account?
|
| 1094 |
+
</h2>
|
| 1095 |
+
<p id="reactivate-body" className="mt-2 text-sm leading-relaxed text-gray-600">
|
| 1096 |
+
{body}
|
| 1097 |
+
</p>
|
| 1098 |
+
<div className="mt-5 flex gap-2">
|
| 1099 |
+
<button
|
| 1100 |
+
type="button"
|
| 1101 |
+
onClick={onCancel}
|
| 1102 |
+
disabled={busy}
|
| 1103 |
+
className="flex-1 rounded-lg border border-gray-300 px-4 py-2.5 text-sm font-medium text-gray-700 transition hover:bg-gray-50 disabled:opacity-50"
|
| 1104 |
+
>
|
| 1105 |
+
Cancel
|
| 1106 |
+
</button>
|
| 1107 |
+
<button
|
| 1108 |
+
type="button"
|
| 1109 |
+
onClick={onConfirm}
|
| 1110 |
+
disabled={busy}
|
| 1111 |
+
autoFocus
|
| 1112 |
+
className={`flex-1 ${PRIMARY_BUTTON_CLASS}`}
|
| 1113 |
+
>
|
| 1114 |
+
{busy ? "Reactivating…" : "Reactivate"}
|
| 1115 |
+
</button>
|
| 1116 |
+
</div>
|
| 1117 |
+
</div>
|
| 1118 |
+
</div>,
|
| 1119 |
+
document.body
|
| 1120 |
+
);
|
| 1121 |
+
}
|
| 1122 |
+
|
| 1123 |
+
/**
|
| 1124 |
+
* In-app browsers (Instagram, LinkedIn, TikTok…) block OAuth popups, and the
|
| 1125 |
+
* provider buttons fail silently there. We show no sign-in options at all —
|
| 1126 |
+
* only the way out to a real browser.
|
| 1127 |
+
*/
|
| 1128 |
+
function InAppEscape({
|
| 1129 |
+
showInstructions,
|
| 1130 |
+
copied,
|
| 1131 |
+
onEscape,
|
| 1132 |
+
onCopy,
|
| 1133 |
+
}: {
|
| 1134 |
+
showInstructions: boolean;
|
| 1135 |
+
copied: boolean;
|
| 1136 |
+
onEscape: () => void;
|
| 1137 |
+
onCopy: () => void;
|
| 1138 |
+
}) {
|
| 1139 |
+
return (
|
| 1140 |
+
<div className="flex flex-col items-center gap-4">
|
| 1141 |
+
<div className="w-full rounded-xl border border-amber-200 bg-amber-50 p-3 text-left text-sm text-amber-900">
|
| 1142 |
+
<p className="font-medium">Open this page in your browser to sign in</p>
|
| 1143 |
+
<p className="mt-1 text-amber-800">
|
| 1144 |
+
Sign-in isn't allowed inside this in-app browser. Tap the{" "}
|
| 1145 |
+
<span className="font-semibold">⋯</span> menu above and choose{" "}
|
| 1146 |
+
<span className="font-semibold">“Open in Safari”</span> (or{" "}
|
| 1147 |
+
<span className="font-semibold">“Open in Browser”</span>), then sign in.
|
| 1148 |
+
</p>
|
| 1149 |
+
{showInstructions && (
|
| 1150 |
+
<p className="mt-2 font-medium text-amber-900">
|
| 1151 |
+
Copy the link below if the menu doesn't offer that option.
|
| 1152 |
+
</p>
|
| 1153 |
+
)}
|
| 1154 |
+
<div className="mt-2 flex flex-wrap gap-2">
|
| 1155 |
+
<button
|
| 1156 |
+
type="button"
|
| 1157 |
+
onClick={onEscape}
|
| 1158 |
+
className="inline-flex items-center justify-center rounded-md border border-amber-300 bg-white px-3 py-1.5 font-medium text-amber-900 transition hover:bg-amber-100"
|
| 1159 |
+
>
|
| 1160 |
+
Open in browser
|
| 1161 |
+
</button>
|
| 1162 |
+
<button
|
| 1163 |
+
type="button"
|
| 1164 |
+
onClick={onCopy}
|
| 1165 |
+
className="inline-flex items-center justify-center rounded-md border border-amber-300 bg-white px-3 py-1.5 font-medium text-amber-900 transition hover:bg-amber-100"
|
| 1166 |
+
>
|
| 1167 |
+
{copied ? "Link copied!" : "Copy link"}
|
| 1168 |
+
</button>
|
| 1169 |
+
</div>
|
| 1170 |
+
</div>
|
| 1171 |
+
</div>
|
| 1172 |
+
);
|
| 1173 |
+
}
|
frontend/src/components/auth/LoginModal.tsx
CHANGED
|
@@ -1,22 +1,9 @@
|
|
| 1 |
-
import {
|
| 2 |
import ReactDOM from "react-dom";
|
| 3 |
-
import { GoogleLogin } from "@react-oauth/google";
|
| 4 |
|
| 5 |
-
import
|
| 6 |
-
import MicrosoftAuthButton from "../public/MicrosoftAuthButton";
|
| 7 |
-
import { useSocialLogin } from "../../hooks/useSocialLogin";
|
| 8 |
-
import { isAppleSignInConfigured } from "../../lib/appleSignIn";
|
| 9 |
-
import { isMicrosoftSignInConfigured } from "../../lib/microsoftSignIn";
|
| 10 |
-
import {
|
| 11 |
-
copyLink,
|
| 12 |
-
detectInAppBrowser,
|
| 13 |
-
escapeToSystemBrowser,
|
| 14 |
-
} from "../../lib/inAppBrowser";
|
| 15 |
|
| 16 |
-
export
|
| 17 |
-
title?: string;
|
| 18 |
-
subtitle?: string;
|
| 19 |
-
}
|
| 20 |
|
| 21 |
interface LoginModalProps extends LoginModalCopy {
|
| 22 |
open: boolean;
|
|
@@ -27,126 +14,45 @@ interface LoginModalProps extends LoginModalCopy {
|
|
| 27 |
skipRedirect?: boolean;
|
| 28 |
}
|
| 29 |
|
| 30 |
-
const DEFAULT_TITLE = "Sign in to Blog2Video";
|
| 31 |
-
const DEFAULT_SUBTITLE = "Choose how you'd like to continue.";
|
| 32 |
-
|
| 33 |
/**
|
| 34 |
-
*
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
*
|
| 36 |
-
*
|
| 37 |
-
*
|
| 38 |
-
*
|
| 39 |
*/
|
| 40 |
export default function LoginModal({
|
| 41 |
open,
|
| 42 |
onClose,
|
| 43 |
onSuccess,
|
| 44 |
skipRedirect,
|
| 45 |
-
title
|
| 46 |
-
subtitle
|
| 47 |
}: LoginModalProps) {
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
signInWithApple,
|
| 51 |
-
signInWithMicrosoft,
|
| 52 |
-
onGoogleError,
|
| 53 |
-
signingIn,
|
| 54 |
-
error,
|
| 55 |
-
reactivate,
|
| 56 |
-
reset,
|
| 57 |
-
} = useSocialLogin({ onSuccess, skipRedirect });
|
| 58 |
-
|
| 59 |
-
// Only consult the UA once the modal opens; the result never changes for a
|
| 60 |
-
// given page load, but this keeps the check out of the render path.
|
| 61 |
-
const [inApp, setInApp] = useState(false);
|
| 62 |
-
const [showInstructions, setShowInstructions] = useState(false);
|
| 63 |
-
const [copied, setCopied] = useState(false);
|
| 64 |
-
|
| 65 |
-
useEffect(() => {
|
| 66 |
-
if (!open) return;
|
| 67 |
-
setInApp(detectInAppBrowser().isInApp);
|
| 68 |
-
setShowInstructions(false);
|
| 69 |
-
setCopied(false);
|
| 70 |
-
reset();
|
| 71 |
-
}, [open, reset]);
|
| 72 |
-
|
| 73 |
-
// Escape closes, and the backdrop is inert while a sign-in is in flight so a
|
| 74 |
-
// stray click can't orphan an in-progress exchange.
|
| 75 |
useEffect(() => {
|
| 76 |
if (!open) return;
|
| 77 |
const onKey = (e: KeyboardEvent) => {
|
| 78 |
-
if (e.key === "Escape"
|
| 79 |
};
|
| 80 |
document.addEventListener("keydown", onKey);
|
| 81 |
return () => document.removeEventListener("keydown", onKey);
|
| 82 |
-
}, [open,
|
| 83 |
-
|
| 84 |
-
const handleEscape = useCallback(() => {
|
| 85 |
-
// Android can hand off to Chrome; iOS cannot, so fall back to instructions.
|
| 86 |
-
if (!escapeToSystemBrowser(window.location.href)) setShowInstructions(true);
|
| 87 |
-
}, []);
|
| 88 |
-
|
| 89 |
-
const handleCopy = useCallback(async () => {
|
| 90 |
-
const ok = await copyLink(window.location.href);
|
| 91 |
-
setCopied(ok);
|
| 92 |
-
if (ok) setTimeout(() => setCopied(false), 2000);
|
| 93 |
-
}, []);
|
| 94 |
|
| 95 |
if (!open) return null;
|
| 96 |
|
| 97 |
-
// After a wrong-provider rejection we know exactly which provider owns the
|
| 98 |
-
// email, so offer only that one — recovery becomes a single click instead of
|
| 99 |
-
// another guess between several buttons.
|
| 100 |
-
const onlyProvider = error?.kind === "wrong_provider" ? error.provider : null;
|
| 101 |
-
|
| 102 |
-
// One list so adding a provider is a single entry. A provider whose client id
|
| 103 |
-
// isn't configured hides itself, which is what makes this safe to ship before
|
| 104 |
-
// the provider's console setup is done.
|
| 105 |
-
const providers = [
|
| 106 |
-
{
|
| 107 |
-
id: "apple",
|
| 108 |
-
enabled: isAppleSignInConfigured(),
|
| 109 |
-
render: () => (
|
| 110 |
-
<AppleAuthButton
|
| 111 |
-
onClick={signInWithApple}
|
| 112 |
-
text={onlyProvider ? "signin_with" : "continue_with"}
|
| 113 |
-
/>
|
| 114 |
-
),
|
| 115 |
-
},
|
| 116 |
-
{
|
| 117 |
-
id: "google",
|
| 118 |
-
enabled: true,
|
| 119 |
-
render: () => (
|
| 120 |
-
/* GIS renders a Google-hosted iframe, so it must mount only once this
|
| 121 |
-
container is laid out — i.e. after the modal is open. */
|
| 122 |
-
<GoogleLogin
|
| 123 |
-
onSuccess={signInWithGoogle}
|
| 124 |
-
onError={onGoogleError}
|
| 125 |
-
size="large"
|
| 126 |
-
shape="pill"
|
| 127 |
-
text="continue_with"
|
| 128 |
-
theme="outline"
|
| 129 |
-
width="300"
|
| 130 |
-
/>
|
| 131 |
-
),
|
| 132 |
-
},
|
| 133 |
-
{
|
| 134 |
-
id: "microsoft",
|
| 135 |
-
enabled: isMicrosoftSignInConfigured(),
|
| 136 |
-
render: () => (
|
| 137 |
-
<MicrosoftAuthButton
|
| 138 |
-
onClick={signInWithMicrosoft}
|
| 139 |
-
text={onlyProvider ? "signin_with" : "continue_with"}
|
| 140 |
-
/>
|
| 141 |
-
),
|
| 142 |
-
},
|
| 143 |
-
].filter((p) => p.enabled && (onlyProvider === null || onlyProvider === p.id));
|
| 144 |
-
|
| 145 |
return ReactDOM.createPortal(
|
| 146 |
<div className="fixed inset-0 z-[100] flex items-center justify-center p-4">
|
| 147 |
<div
|
| 148 |
className="absolute inset-0 bg-black/40 backdrop-blur-sm"
|
| 149 |
-
onClick={
|
| 150 |
aria-hidden
|
| 151 |
/>
|
| 152 |
<div
|
|
@@ -158,7 +64,6 @@ export default function LoginModal({
|
|
| 158 |
<button
|
| 159 |
type="button"
|
| 160 |
onClick={onClose}
|
| 161 |
-
disabled={signingIn}
|
| 162 |
aria-label="Close"
|
| 163 |
className="absolute right-4 top-4 rounded-full p-1 text-gray-400 transition hover:bg-gray-100 hover:text-gray-600 disabled:opacity-40"
|
| 164 |
>
|
|
@@ -167,132 +72,16 @@ export default function LoginModal({
|
|
| 167 |
</svg>
|
| 168 |
</button>
|
| 169 |
|
| 170 |
-
<
|
| 171 |
-
{
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
{
|
| 177 |
-
|
| 178 |
-
showInstructions={showInstructions}
|
| 179 |
-
copied={copied}
|
| 180 |
-
onEscape={handleEscape}
|
| 181 |
-
onCopy={handleCopy}
|
| 182 |
-
/>
|
| 183 |
-
) : signingIn ? (
|
| 184 |
-
<div className="flex flex-col items-center gap-3 py-6">
|
| 185 |
-
<div className="h-7 w-7 animate-spin rounded-full border-2 border-gray-200 border-t-purple-600" />
|
| 186 |
-
<p className="text-sm text-gray-600">Signing you in…</p>
|
| 187 |
-
</div>
|
| 188 |
-
) : (
|
| 189 |
-
<div className="flex flex-col items-center gap-3">
|
| 190 |
-
{error && <LoginErrorNotice error={error} onReactivate={reactivate} />}
|
| 191 |
-
|
| 192 |
-
{/* One fixed-width row per provider. Google Identity Services
|
| 193 |
-
renders its own iframe and does not honour `width` exactly, so
|
| 194 |
-
the row — not the button — defines the box; our own buttons
|
| 195 |
-
stretch to fill it and GIS is centred inside it. That keeps all
|
| 196 |
-
three the same width even though one is not ours to style. */}
|
| 197 |
-
{providers.map((p) => (
|
| 198 |
-
<div key={p.id} className="flex w-[300px] max-w-full justify-center">
|
| 199 |
-
{p.render()}
|
| 200 |
-
</div>
|
| 201 |
-
))}
|
| 202 |
-
</div>
|
| 203 |
-
)}
|
| 204 |
-
</div>
|
| 205 |
-
|
| 206 |
-
{!inApp && (
|
| 207 |
-
<p className="mt-6 text-center text-[11px] leading-relaxed text-gray-400">
|
| 208 |
-
By continuing you agree to our{" "}
|
| 209 |
-
<a href="/terms" className="underline hover:text-gray-600">Terms</a> and{" "}
|
| 210 |
-
<a href="/privacy" className="underline hover:text-gray-600">Privacy Policy</a>.
|
| 211 |
-
</p>
|
| 212 |
-
)}
|
| 213 |
</div>
|
| 214 |
</div>,
|
| 215 |
document.body
|
| 216 |
);
|
| 217 |
}
|
| 218 |
-
|
| 219 |
-
/** Error banner, including the one-click switch to the correct provider. */
|
| 220 |
-
function LoginErrorNotice({
|
| 221 |
-
error,
|
| 222 |
-
onReactivate,
|
| 223 |
-
}: {
|
| 224 |
-
error: NonNullable<ReturnType<typeof useSocialLogin>["error"]>;
|
| 225 |
-
onReactivate: () => void;
|
| 226 |
-
}) {
|
| 227 |
-
const isWrongProvider = error.kind === "wrong_provider";
|
| 228 |
-
const tone = isWrongProvider
|
| 229 |
-
? "border-amber-200 bg-amber-50 text-amber-900"
|
| 230 |
-
: "border-red-200 bg-red-50 text-red-700";
|
| 231 |
-
|
| 232 |
-
return (
|
| 233 |
-
<div className={`w-full rounded-xl border p-3 text-left text-xs ${tone}`}>
|
| 234 |
-
<p>{error.message}</p>
|
| 235 |
-
{error.kind === "account_deleted" && (
|
| 236 |
-
<button
|
| 237 |
-
type="button"
|
| 238 |
-
onClick={onReactivate}
|
| 239 |
-
className="mt-2 inline-flex items-center justify-center rounded-md border border-red-300 bg-white px-3 py-1.5 font-medium text-red-700 transition hover:bg-red-100"
|
| 240 |
-
>
|
| 241 |
-
Reactivate my account
|
| 242 |
-
</button>
|
| 243 |
-
)}
|
| 244 |
-
</div>
|
| 245 |
-
);
|
| 246 |
-
}
|
| 247 |
-
|
| 248 |
-
/**
|
| 249 |
-
* In-app browsers (Instagram, LinkedIn, TikTok…) block OAuth popups, and the
|
| 250 |
-
* provider buttons fail silently there. We show no sign-in options at all —
|
| 251 |
-
* only the way out to a real browser.
|
| 252 |
-
*/
|
| 253 |
-
function InAppEscape({
|
| 254 |
-
showInstructions,
|
| 255 |
-
copied,
|
| 256 |
-
onEscape,
|
| 257 |
-
onCopy,
|
| 258 |
-
}: {
|
| 259 |
-
showInstructions: boolean;
|
| 260 |
-
copied: boolean;
|
| 261 |
-
onEscape: () => void;
|
| 262 |
-
onCopy: () => void;
|
| 263 |
-
}) {
|
| 264 |
-
return (
|
| 265 |
-
<div className="flex flex-col items-center gap-3">
|
| 266 |
-
<div className="w-full rounded-xl border border-amber-200 bg-amber-50 p-3 text-left text-xs text-amber-900">
|
| 267 |
-
<p className="font-medium">Open this page in your browser to sign in</p>
|
| 268 |
-
<p className="mt-1 text-amber-800">
|
| 269 |
-
Sign-in isn't allowed inside this in-app browser. Tap the{" "}
|
| 270 |
-
<span className="font-semibold">⋯</span> menu above and choose{" "}
|
| 271 |
-
<span className="font-semibold">“Open in Safari”</span> (or{" "}
|
| 272 |
-
<span className="font-semibold">“Open in Browser”</span>), then sign in.
|
| 273 |
-
</p>
|
| 274 |
-
{showInstructions && (
|
| 275 |
-
<p className="mt-2 font-medium text-amber-900">
|
| 276 |
-
Copy the link below if the menu doesn't offer that option.
|
| 277 |
-
</p>
|
| 278 |
-
)}
|
| 279 |
-
<div className="mt-2 flex flex-wrap gap-2">
|
| 280 |
-
<button
|
| 281 |
-
type="button"
|
| 282 |
-
onClick={onEscape}
|
| 283 |
-
className="inline-flex items-center justify-center rounded-md border border-amber-300 bg-white px-3 py-1.5 font-medium text-amber-900 transition hover:bg-amber-100"
|
| 284 |
-
>
|
| 285 |
-
Open in browser
|
| 286 |
-
</button>
|
| 287 |
-
<button
|
| 288 |
-
type="button"
|
| 289 |
-
onClick={onCopy}
|
| 290 |
-
className="inline-flex items-center justify-center rounded-md border border-amber-300 bg-white px-3 py-1.5 font-medium text-amber-900 transition hover:bg-amber-100"
|
| 291 |
-
>
|
| 292 |
-
{copied ? "Link copied!" : "Copy link"}
|
| 293 |
-
</button>
|
| 294 |
-
</div>
|
| 295 |
-
</div>
|
| 296 |
-
</div>
|
| 297 |
-
);
|
| 298 |
-
}
|
|
|
|
| 1 |
+
import { useEffect } from "react";
|
| 2 |
import ReactDOM from "react-dom";
|
|
|
|
| 3 |
|
| 4 |
+
import AuthFlow, { type LoginModalCopy } from "./AuthFlow";
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
+
export type { LoginModalCopy };
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
interface LoginModalProps extends LoginModalCopy {
|
| 9 |
open: boolean;
|
|
|
|
| 14 |
skipRedirect?: boolean;
|
| 15 |
}
|
| 16 |
|
|
|
|
|
|
|
|
|
|
| 17 |
/**
|
| 18 |
+
* Dialog chrome around the shared sign-in surface.
|
| 19 |
+
*
|
| 20 |
+
* The flow itself lives in AuthFlow, which the full-page /signin and /signup
|
| 21 |
+
* routes render too — so this file is only the portal, backdrop and close
|
| 22 |
+
* button. Keeping one implementation is what stops the modal and the page
|
| 23 |
+
* drifting apart on things like the 409 provider narrowing or the burned-code
|
| 24 |
+
* recovery.
|
| 25 |
*
|
| 26 |
+
* Still used by the in-place tool gates (SignupGate, the /tools widgets, the
|
| 27 |
+
* support widget), which sign the user in WITHOUT navigating away so a
|
| 28 |
+
* half-filled form survives. Plain CTAs link to /signin instead.
|
| 29 |
*/
|
| 30 |
export default function LoginModal({
|
| 31 |
open,
|
| 32 |
onClose,
|
| 33 |
onSuccess,
|
| 34 |
skipRedirect,
|
| 35 |
+
title,
|
| 36 |
+
subtitle,
|
| 37 |
}: LoginModalProps) {
|
| 38 |
+
// Escape closes. The backdrop stays clickable here rather than tracking the
|
| 39 |
+
// flow's busy state, which now lives inside AuthFlow.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
useEffect(() => {
|
| 41 |
if (!open) return;
|
| 42 |
const onKey = (e: KeyboardEvent) => {
|
| 43 |
+
if (e.key === "Escape") onClose();
|
| 44 |
};
|
| 45 |
document.addEventListener("keydown", onKey);
|
| 46 |
return () => document.removeEventListener("keydown", onKey);
|
| 47 |
+
}, [open, onClose]);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
|
| 49 |
if (!open) return null;
|
| 50 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
return ReactDOM.createPortal(
|
| 52 |
<div className="fixed inset-0 z-[100] flex items-center justify-center p-4">
|
| 53 |
<div
|
| 54 |
className="absolute inset-0 bg-black/40 backdrop-blur-sm"
|
| 55 |
+
onClick={onClose}
|
| 56 |
aria-hidden
|
| 57 |
/>
|
| 58 |
<div
|
|
|
|
| 64 |
<button
|
| 65 |
type="button"
|
| 66 |
onClick={onClose}
|
|
|
|
| 67 |
aria-label="Close"
|
| 68 |
className="absolute right-4 top-4 rounded-full p-1 text-gray-400 transition hover:bg-gray-100 hover:text-gray-600 disabled:opacity-40"
|
| 69 |
>
|
|
|
|
| 72 |
</svg>
|
| 73 |
</button>
|
| 74 |
|
| 75 |
+
<AuthFlow
|
| 76 |
+
active={open}
|
| 77 |
+
variant="modal"
|
| 78 |
+
onSuccess={onSuccess}
|
| 79 |
+
skipRedirect={skipRedirect}
|
| 80 |
+
title={title}
|
| 81 |
+
subtitle={subtitle}
|
| 82 |
+
/>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
</div>
|
| 84 |
</div>,
|
| 85 |
document.body
|
| 86 |
);
|
| 87 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
frontend/src/components/public/AppleAuthButton.tsx
DELETED
|
@@ -1,50 +0,0 @@
|
|
| 1 |
-
/**
|
| 2 |
-
* "Sign in with Apple" button.
|
| 3 |
-
*
|
| 4 |
-
* Styled to Apple's Human Interface Guidelines — white pill, black Apple logo,
|
| 5 |
-
* the exact wording. Stretches to fill its row in LoginModal, which is what
|
| 6 |
-
* keeps it the same width as the Google button (whose iframe we cannot size
|
| 7 |
-
* directly).
|
| 8 |
-
*/
|
| 9 |
-
interface AppleAuthButtonProps {
|
| 10 |
-
onClick: () => void;
|
| 11 |
-
disabled?: boolean;
|
| 12 |
-
/** Match the Google button's width, in px, so the two pills align. */
|
| 13 |
-
width?: string;
|
| 14 |
-
text?: "signin_with" | "continue_with";
|
| 15 |
-
}
|
| 16 |
-
|
| 17 |
-
export default function AppleAuthButton({
|
| 18 |
-
onClick,
|
| 19 |
-
disabled = false,
|
| 20 |
-
text = "continue_with",
|
| 21 |
-
}: AppleAuthButtonProps) {
|
| 22 |
-
const label = text === "signin_with" ? "Sign in with Apple" : "Continue with Apple";
|
| 23 |
-
|
| 24 |
-
return (
|
| 25 |
-
<button
|
| 26 |
-
type="button"
|
| 27 |
-
onClick={onClick}
|
| 28 |
-
disabled={disabled}
|
| 29 |
-
aria-label={label}
|
| 30 |
-
className="relative flex h-10 w-full items-center justify-center rounded-full border pl-[22px] border-gray-300 bg-white text-sm font-medium text-gray-700 shadow-sm transition hover:bg-gray-50 disabled:cursor-not-allowed disabled:opacity-60"
|
| 31 |
-
>
|
| 32 |
-
{/* Google Identity Services centres its own label inside its iframe and
|
| 33 |
-
we cannot restyle it, so ours centre too. Its label measures ~11px
|
| 34 |
-
right of a plain centre, so `pl-[22px]` on this box shifts our centred
|
| 35 |
-
label by half that to match. The icon stays absolutely positioned, so
|
| 36 |
-
padding does not move it and the three logos stay aligned.
|
| 37 |
-
Apple's guidelines allow a white button with a black logo; the mark
|
| 38 |
-
keeps its own colour rather than inheriting the label text. */}
|
| 39 |
-
<svg
|
| 40 |
-
className="absolute left-5 h-[18px] w-[18px] text-black"
|
| 41 |
-
viewBox="0 0 384 512"
|
| 42 |
-
fill="currentColor"
|
| 43 |
-
aria-hidden
|
| 44 |
-
>
|
| 45 |
-
<path d="M318.7 268.7c-.2-36.7 16.4-64.4 50-84.8-18.8-26.9-47.2-41.7-84.7-44.6-35.5-2.8-74.3 20.7-88.5 20.7-15 0-49.4-19.7-76.4-19.7C63.3 141.2 4 184.8 4 273.5q0 39.3 14.4 81.2c12.8 36.7 59 126.7 107.2 125.2 25.2-.6 43-17.9 75.8-17.9 31.8 0 48.3 17.9 76.4 17.9 48.6-.7 90.4-82.5 102.6-119.3-65.2-30.7-61.7-90-61.7-91.9zm-56.6-164.2c27.3-32.4 24.8-61.9 24-72.5-24.1 1.4-52 16.4-67.9 34.9-17.5 19.8-27.8 44.3-25.6 71.9 26.1 2 49.9-11.4 69.5-34.3z" />
|
| 46 |
-
</svg>
|
| 47 |
-
{label}
|
| 48 |
-
</button>
|
| 49 |
-
);
|
| 50 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
frontend/src/components/public/MicrosoftAuthButton.tsx
DELETED
|
@@ -1,45 +0,0 @@
|
|
| 1 |
-
/**
|
| 2 |
-
* "Sign in with Microsoft" button.
|
| 3 |
-
*
|
| 4 |
-
* Follows Microsoft's branding guidance — white surface, grey border, the
|
| 5 |
-
* four-square logo in its fixed colours, and the prescribed wording. Stretches
|
| 6 |
-
* to fill its row in LoginModal, which is what keeps it the same width as the
|
| 7 |
-
* Google button (whose iframe we cannot size directly).
|
| 8 |
-
*/
|
| 9 |
-
interface MicrosoftAuthButtonProps {
|
| 10 |
-
onClick: () => void;
|
| 11 |
-
disabled?: boolean;
|
| 12 |
-
text?: "signin_with" | "continue_with";
|
| 13 |
-
}
|
| 14 |
-
|
| 15 |
-
export default function MicrosoftAuthButton({
|
| 16 |
-
onClick,
|
| 17 |
-
disabled = false,
|
| 18 |
-
text = "continue_with",
|
| 19 |
-
}: MicrosoftAuthButtonProps) {
|
| 20 |
-
const label =
|
| 21 |
-
text === "signin_with" ? "Sign in with Microsoft" : "Continue with Microsoft";
|
| 22 |
-
|
| 23 |
-
return (
|
| 24 |
-
<button
|
| 25 |
-
type="button"
|
| 26 |
-
onClick={onClick}
|
| 27 |
-
disabled={disabled}
|
| 28 |
-
aria-label={label}
|
| 29 |
-
className="relative flex h-10 w-full items-center justify-center rounded-full border pl-[22px] border-gray-300 bg-white text-sm font-medium text-gray-700 shadow-sm transition hover:bg-gray-50 disabled:cursor-not-allowed disabled:opacity-60"
|
| 30 |
-
>
|
| 31 |
-
{/* Google Identity Services centres its own label inside its iframe and
|
| 32 |
-
we cannot restyle it, so ours centre too. Its label measures ~11px
|
| 33 |
-
right of a plain centre, so `pl-[22px]` on this box shifts our centred
|
| 34 |
-
label by half that to match. The icon stays absolutely positioned, so
|
| 35 |
-
padding does not move it and the three logos stay aligned. */}
|
| 36 |
-
<svg className="absolute left-5 h-[18px] w-[18px]" viewBox="0 0 21 21" aria-hidden>
|
| 37 |
-
<rect x="1" y="1" width="9" height="9" fill="#f25022" />
|
| 38 |
-
<rect x="11" y="1" width="9" height="9" fill="#7fba00" />
|
| 39 |
-
<rect x="1" y="11" width="9" height="9" fill="#00a4ef" />
|
| 40 |
-
<rect x="11" y="11" width="9" height="9" fill="#ffb900" />
|
| 41 |
-
</svg>
|
| 42 |
-
{label}
|
| 43 |
-
</button>
|
| 44 |
-
);
|
| 45 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
frontend/src/components/remotion/imageBoxConfig.ts
CHANGED
|
@@ -562,10 +562,12 @@ export const LAYOUT_IMAGE_BOX_DIMS: Record<string, ImageBoxDims> = {
|
|
| 562 |
// pull_quote__v2 / ending_socials__v2 are intentionally absent — they render
|
| 563 |
// no image (both bases are in meta.json `layouts_without_image`).
|
| 564 |
|
| 565 |
-
// Polaroid-style card, tilted, pinned right (landscape) /
|
| 566 |
news_headline: {
|
| 567 |
landscape: { w: 0.435, h: 0.594 }, // measured 557 × 428
|
| 568 |
-
|
|
|
|
|
|
|
| 569 |
},
|
| 570 |
|
| 571 |
// Tilted photo card beside the lead column.
|
|
|
|
| 562 |
// pull_quote__v2 / ending_socials__v2 are intentionally absent — they render
|
| 563 |
// no image (both bases are in meta.json `layouts_without_image`).
|
| 564 |
|
| 565 |
+
// Polaroid-style card, tilted, pinned right (landscape) / bottom (portrait).
|
| 566 |
news_headline: {
|
| 567 |
landscape: { w: 0.435, h: 0.594 }, // measured 557 × 428
|
| 568 |
+
// Portrait card moved from top:15% to bottom:6% and 35%→34% tall so the
|
| 569 |
+
// copy no longer overlaps it; height re-derived accordingly.
|
| 570 |
+
portrait: { w: 0.841, h: 0.370 }, // 0.34 frame height + the card's padding
|
| 571 |
},
|
| 572 |
|
| 573 |
// Tilted photo card beside the lead column.
|
frontend/src/components/remotion/newspaper/layouts/NewsHeadline.tsx
CHANGED
|
@@ -212,7 +212,7 @@ export const NewsHeadline: React.FC<
|
|
| 212 |
: [words[0], words[Math.floor(words.length / 2)], words[words.length - 1]];
|
| 213 |
|
| 214 |
// Calculate description font size for relative scaling
|
| 215 |
-
const actualDescriptionFontSize = descriptionFontSize ?? (p ?
|
| 216 |
const categoryBaseFontSize = p ? 28 : 24; // Base for category without descriptionFontSize
|
| 217 |
const authorBaseFontSize = p ? 20 : 16; // Base for author without descriptionFontSize
|
| 218 |
// A clip fills the same visual slot as a still, so it must not
|
|
@@ -233,7 +233,7 @@ export const NewsHeadline: React.FC<
|
|
| 233 |
const titleRef = React.useRef<HTMLDivElement>(null);
|
| 234 |
const categoryRef = React.useRef<HTMLDivElement>(null);
|
| 235 |
|
| 236 |
-
const actualTitleFontSize = titleFontSize ?? (p ?
|
| 237 |
|
| 238 |
/* Stage 1 — the headline fits its own share of the column.
|
| 239 |
The title is `flex-shrink:0`, so its clientHeight always equals its content
|
|
@@ -243,7 +243,11 @@ export const NewsHeadline: React.FC<
|
|
| 243 |
fits inside its share is left completely alone. */
|
| 244 |
const titleBudgetPx = React.useMemo(() => {
|
| 245 |
// Container height minus its vertical padding (percentages of the frame).
|
| 246 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 247 |
const inner = videoHeight * (1 - padFrac);
|
| 248 |
// The headline may claim at most this much of the usable column; the rest
|
| 249 |
// is reserved for the category chip, byline and narration.
|
|
@@ -284,15 +288,22 @@ export const NewsHeadline: React.FC<
|
|
| 284 |
of those is affected by centering. */
|
| 285 |
const [categoryH, setCategoryH] = React.useState(0);
|
| 286 |
const [titleH, setTitleH] = React.useState(0);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 287 |
React.useLayoutEffect(() => {
|
| 288 |
setCategoryH(categoryRef.current?.offsetHeight ?? 0);
|
| 289 |
setTitleH(titleRef.current?.offsetHeight ?? 0);
|
|
|
|
| 290 |
// eslint-disable-next-line react-hooks/exhaustive-deps
|
| 291 |
-
}, [titlePx, cat, stats, title]);
|
| 292 |
|
| 293 |
const narrationBudgetPx = React.useMemo(() => {
|
| 294 |
if (portraitNoImage) return undefined; // that variant's own clientHeight IS the true budget (single flex:1 child).
|
| 295 |
-
|
|
|
|
| 296 |
const inner = videoHeight * (1 - padFrac);
|
| 297 |
const categoryMargin = p ? 20 : 30;
|
| 298 |
const titleMargin = p ? 40 : 36;
|
|
@@ -302,6 +313,35 @@ export const NewsHeadline: React.FC<
|
|
| 302 |
return Math.max(1, (inner - used) * 0.92);
|
| 303 |
}, [videoHeight, p, portraitNoImage, categoryH, titleH]);
|
| 304 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 305 |
const { px: narrationPx } = useFitText(
|
| 306 |
narrationRef,
|
| 307 |
actualDescriptionFontSize,
|
|
@@ -336,12 +376,21 @@ export const NewsHeadline: React.FC<
|
|
| 336 |
<div
|
| 337 |
style={{
|
| 338 |
position: "absolute",
|
| 339 |
-
// Portrait:
|
| 340 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 341 |
right: p ? "auto" : "4%",
|
| 342 |
left: p ? "50%" : "auto",
|
| 343 |
width: p ? "80%" : "40%",
|
| 344 |
-
height: p ?
|
| 345 |
// ✅ physical styling: white paper background and padding
|
| 346 |
background: "#fff",
|
| 347 |
padding: "10px 10px 30px 10px", // extra bottom padding for 'pasted' look
|
|
@@ -408,8 +457,24 @@ export const NewsHeadline: React.FC<
|
|
| 408 |
inset: 0,
|
| 409 |
display: "flex",
|
| 410 |
flexDirection: "column",
|
| 411 |
-
|
| 412 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 413 |
zIndex: 10,
|
| 414 |
opacity: contentOpacity,
|
| 415 |
// Let the narration shrink into the leftover space instead of
|
|
@@ -478,7 +543,7 @@ export const NewsHeadline: React.FC<
|
|
| 478 |
fontSize: titlePx,
|
| 479 |
fontWeight: 800,
|
| 480 |
lineHeight: 1.0,
|
| 481 |
-
marginBottom: portraitNoImage ?
|
| 482 |
maxWidth: p ? "100%" : (imageUrl ? "50%" : "60%"),
|
| 483 |
flexShrink: 0,
|
| 484 |
}}
|
|
@@ -518,10 +583,13 @@ export const NewsHeadline: React.FC<
|
|
| 518 |
style={
|
| 519 |
portraitNoImage
|
| 520 |
? {
|
| 521 |
-
flex:
|
|
|
|
|
|
|
|
|
|
| 522 |
display: "flex",
|
| 523 |
alignItems: "center",
|
| 524 |
-
justifyContent: "
|
| 525 |
minHeight: 0,
|
| 526 |
paddingTop: 24,
|
| 527 |
paddingBottom: 24,
|
|
@@ -542,7 +610,15 @@ export const NewsHeadline: React.FC<
|
|
| 542 |
// second system disagreeing about it.
|
| 543 |
{
|
| 544 |
flexShrink: 0,
|
| 545 |
-
height:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 546 |
overflow: "hidden",
|
| 547 |
display: "flex",
|
| 548 |
}
|
|
@@ -561,10 +637,12 @@ export const NewsHeadline: React.FC<
|
|
| 561 |
width: p ? "100%" : (imageUrl ? "50%" : "70%"),
|
| 562 |
maxWidth: p ? "100%" : (imageUrl ? "50%" : "70%"),
|
| 563 |
opacity: 0.9,
|
| 564 |
-
|
| 565 |
-
//
|
| 566 |
-
|
| 567 |
-
|
|
|
|
|
|
|
| 568 |
minHeight: 0,
|
| 569 |
overflow: "hidden",
|
| 570 |
}}
|
|
|
|
| 212 |
: [words[0], words[Math.floor(words.length / 2)], words[words.length - 1]];
|
| 213 |
|
| 214 |
// Calculate description font size for relative scaling
|
| 215 |
+
const actualDescriptionFontSize = descriptionFontSize ?? (p ? 37 : 28);
|
| 216 |
const categoryBaseFontSize = p ? 28 : 24; // Base for category without descriptionFontSize
|
| 217 |
const authorBaseFontSize = p ? 20 : 16; // Base for author without descriptionFontSize
|
| 218 |
// A clip fills the same visual slot as a still, so it must not
|
|
|
|
| 233 |
const titleRef = React.useRef<HTMLDivElement>(null);
|
| 234 |
const categoryRef = React.useRef<HTMLDivElement>(null);
|
| 235 |
|
| 236 |
+
const actualTitleFontSize = titleFontSize ?? (p ? 68 : 62);
|
| 237 |
|
| 238 |
/* Stage 1 — the headline fits its own share of the column.
|
| 239 |
The title is `flex-shrink:0`, so its clientHeight always equals its content
|
|
|
|
| 243 |
fits inside its share is left completely alone. */
|
| 244 |
const titleBudgetPx = React.useMemo(() => {
|
| 245 |
// Container height minus its vertical padding (percentages of the frame).
|
| 246 |
+
// Portrait-with-image: 12% top pad + the picture's MINIMUM 25.5% band, so
|
| 247 |
+
// ~62.5% of the frame is available to copy. The original 0.15 overstated
|
| 248 |
+
// the column by ~493px on a 1280-tall frame, which is what let the auto-fit
|
| 249 |
+
// grow the headline straight down into the photo.
|
| 250 |
+
const padFrac = portraitNoImage ? 0.12 + 0.1 : p ? 0.375 : 0.14;
|
| 251 |
const inner = videoHeight * (1 - padFrac);
|
| 252 |
// The headline may claim at most this much of the usable column; the rest
|
| 253 |
// is reserved for the category chip, byline and narration.
|
|
|
|
| 288 |
of those is affected by centering. */
|
| 289 |
const [categoryH, setCategoryH] = React.useState(0);
|
| 290 |
const [titleH, setTitleH] = React.useState(0);
|
| 291 |
+
/* The narration's REAL rendered height, not its budget. Needed because a
|
| 292 |
+
user-set font size makes useFitText a no-op (minPx === targetPx), so the
|
| 293 |
+
copy keeps its chosen size and simply occupies more room — the case where
|
| 294 |
+
the picture has to give way instead of the text being clipped. */
|
| 295 |
+
const [narrationH, setNarrationH] = React.useState(0);
|
| 296 |
React.useLayoutEffect(() => {
|
| 297 |
setCategoryH(categoryRef.current?.offsetHeight ?? 0);
|
| 298 |
setTitleH(titleRef.current?.offsetHeight ?? 0);
|
| 299 |
+
setNarrationH(narrationRef.current?.offsetHeight ?? 0);
|
| 300 |
// eslint-disable-next-line react-hooks/exhaustive-deps
|
| 301 |
+
}, [titlePx, cat, stats, title, narration, actualDescriptionFontSize, descriptionFontSizeIsUserSet, videoHeight]);
|
| 302 |
|
| 303 |
const narrationBudgetPx = React.useMemo(() => {
|
| 304 |
if (portraitNoImage) return undefined; // that variant's own clientHeight IS the true budget (single flex:1 child).
|
| 305 |
+
// Mirrors titleBudgetPx: the picture's minimum band is not available to copy.
|
| 306 |
+
const padFrac = p ? 0.375 : 0.14;
|
| 307 |
const inner = videoHeight * (1 - padFrac);
|
| 308 |
const categoryMargin = p ? 20 : 30;
|
| 309 |
const titleMargin = p ? 40 : 36;
|
|
|
|
| 313 |
return Math.max(1, (inner - used) * 0.92);
|
| 314 |
}, [videoHeight, p, portraitNoImage, categoryH, titleH]);
|
| 315 |
|
| 316 |
+
/* ── Portrait picture band ────────────────────────────────────────────────
|
| 317 |
+
The card's height is derived, not fixed. The copy is laid out first and the
|
| 318 |
+
picture takes whatever is left below it, so when the text grows — a long
|
| 319 |
+
headline, a long narration, or a user-set font size that useFitText is not
|
| 320 |
+
allowed to shrink — the IMAGE COMPRESSES instead of the copy being clipped
|
| 321 |
+
or running underneath the card.
|
| 322 |
+
|
| 323 |
+
Clamped at both ends: never taller than 42% (so the picture stays a
|
| 324 |
+
picture and not the whole page), never shorter than 16% (so heavy copy
|
| 325 |
+
leaves a photo that is still recognisable rather than a sliver). */
|
| 326 |
+
const PORTRAIT_CARD_MAX_FRAC = 0.42;
|
| 327 |
+
const PORTRAIT_CARD_MIN_FRAC = 0.16;
|
| 328 |
+
const PORTRAIT_CARD_BOTTOM_FRAC = 0.06;
|
| 329 |
+
const portraitCardHeightFrac = React.useMemo(() => {
|
| 330 |
+
if (!p || !hasVisual) return PORTRAIT_CARD_MAX_FRAC;
|
| 331 |
+
const topPad = 0.12 * videoHeight;
|
| 332 |
+
const categoryMargin = 20;
|
| 333 |
+
const titleMargin = 40;
|
| 334 |
+
const gap = 0.035 * videoHeight;
|
| 335 |
+
// Where the copy actually ends, measured rather than assumed.
|
| 336 |
+
const textBottom =
|
| 337 |
+
topPad + categoryH + categoryMargin + titleH + titleMargin + narrationH;
|
| 338 |
+
const leftover =
|
| 339 |
+
videoHeight - textBottom - gap - PORTRAIT_CARD_BOTTOM_FRAC * videoHeight;
|
| 340 |
+
const frac = leftover / videoHeight;
|
| 341 |
+
return Math.min(PORTRAIT_CARD_MAX_FRAC, Math.max(PORTRAIT_CARD_MIN_FRAC, frac));
|
| 342 |
+
}, [p, hasVisual, videoHeight, categoryH, titleH, narrationH]);
|
| 343 |
+
|
| 344 |
+
|
| 345 |
const { px: narrationPx } = useFitText(
|
| 346 |
narrationRef,
|
| 347 |
actualDescriptionFontSize,
|
|
|
|
| 376 |
<div
|
| 377 |
style={{
|
| 378 |
position: "absolute",
|
| 379 |
+
// Portrait: pinned to the BOTTOM of the page, with the copy stacked
|
| 380 |
+
// above it. It used to sit at top:15% height:35% while the content
|
| 381 |
+
// container ran the full frame with justifyContent:"flex-end" — so
|
| 382 |
+
// any stack taller than ~448px grew up through the card and the
|
| 383 |
+
// headline painted straight over the photo (content is zIndex 10,
|
| 384 |
+
// card is 5). Reserving the lower band for the picture and ending
|
| 385 |
+
// the copy above it removes the collision by construction rather
|
| 386 |
+
// than relying on the text happening to be short enough.
|
| 387 |
+
// Landscape is unchanged: Right Side.
|
| 388 |
+
top: p ? "auto" : "18%",
|
| 389 |
+
bottom: p ? "6%" : "auto",
|
| 390 |
right: p ? "auto" : "4%",
|
| 391 |
left: p ? "50%" : "auto",
|
| 392 |
width: p ? "80%" : "40%",
|
| 393 |
+
height: p ? `${portraitCardHeightFrac * 100}%` : "50%",
|
| 394 |
// ✅ physical styling: white paper background and padding
|
| 395 |
background: "#fff",
|
| 396 |
padding: "10px 10px 30px 10px", // extra bottom padding for 'pasted' look
|
|
|
|
| 457 |
inset: 0,
|
| 458 |
display: "flex",
|
| 459 |
flexDirection: "column",
|
| 460 |
+
// Portrait-with-image anchors to the TOP: the copy starts below the
|
| 461 |
+
// masthead area and grows downward into its reserved band, while the
|
| 462 |
+
// picture owns the bottom. With "flex-end" the stack hugged its floor
|
| 463 |
+
// instead, so any extra height pushed UP — and, once the floor was
|
| 464 |
+
// raised, the last narration line still crossed the card's top edge.
|
| 465 |
+
// No picture: the copy is the only content, so centre the whole stack
|
| 466 |
+
// and let it grow symmetrically up and down from the middle.
|
| 467 |
+
justifyContent: portraitNoImage ? "center" : p ? "flex-start" : "center",
|
| 468 |
+
// Portrait-with-image: the copy's floor corresponds to the card at its
|
| 469 |
+
// MINIMUM height (16% + 6% bottom + 3.5% gap = 25.5%), not its maximum.
|
| 470 |
+
// The card compresses toward that floor as the copy grows, so
|
| 471 |
+
// reserving the full 34% band here would clip text that the picture
|
| 472 |
+
// was willing to make room for.
|
| 473 |
+
padding: portraitNoImage
|
| 474 |
+
? "12% 10% 10% 10%"
|
| 475 |
+
: p
|
| 476 |
+
? "12% 10% 25.5% 10%"
|
| 477 |
+
: "7% 10%",
|
| 478 |
zIndex: 10,
|
| 479 |
opacity: contentOpacity,
|
| 480 |
// Let the narration shrink into the leftover space instead of
|
|
|
|
| 543 |
fontSize: titlePx,
|
| 544 |
fontWeight: 800,
|
| 545 |
lineHeight: 1.0,
|
| 546 |
+
marginBottom: portraitNoImage ? 28 : p ? 40 : 36,
|
| 547 |
maxWidth: p ? "100%" : (imageUrl ? "50%" : "60%"),
|
| 548 |
flexShrink: 0,
|
| 549 |
}}
|
|
|
|
| 583 |
style={
|
| 584 |
portraitNoImage
|
| 585 |
? {
|
| 586 |
+
// Content-sized, NOT flex:1 — stretching this to fill the
|
| 587 |
+
// column is what pinned the title to the top and left the
|
| 588 |
+
// body marooned near the bottom.
|
| 589 |
+
flex: "0 1 auto",
|
| 590 |
display: "flex",
|
| 591 |
alignItems: "center",
|
| 592 |
+
justifyContent: "flex-start",
|
| 593 |
minHeight: 0,
|
| 594 |
paddingTop: 24,
|
| 595 |
paddingBottom: 24,
|
|
|
|
| 610 |
// second system disagreeing about it.
|
| 611 |
{
|
| 612 |
flexShrink: 0,
|
| 613 |
+
// maxHeight, NOT height: a fixed height made this block
|
| 614 |
+
// occupy the whole budget even for one short line, so the
|
| 615 |
+
// text stack ended at ~71% of the frame in every case and
|
| 616 |
+
// the picture below it always clamped to its floor. The
|
| 617 |
+
// cap still preserves what the fixed height was for —
|
| 618 |
+
// the box can never exceed the budget useFitText fitted
|
| 619 |
+
// the copy into — but short copy now takes only the room
|
| 620 |
+
// it needs, and the picture gets the rest.
|
| 621 |
+
maxHeight: narrationBudgetPx,
|
| 622 |
overflow: "hidden",
|
| 623 |
display: "flex",
|
| 624 |
}
|
|
|
|
| 637 |
width: p ? "100%" : (imageUrl ? "50%" : "70%"),
|
| 638 |
maxWidth: p ? "100%" : (imageUrl ? "50%" : "70%"),
|
| 639 |
opacity: 0.9,
|
| 640 |
+
// Left-aligned like the category and headline above it, so the
|
| 641 |
+
// whole block reads as one column rather than a centred caption.
|
| 642 |
+
textAlign: undefined,
|
| 643 |
+
// Content-sized now that the wrapper is capped rather than
|
| 644 |
+
// fixed; height:100% here would re-inflate it to the full budget
|
| 645 |
+
// and reintroduce the always-at-the-floor picture.
|
| 646 |
minHeight: 0,
|
| 647 |
overflow: "hidden",
|
| 648 |
}}
|
frontend/src/components/remotion/newspaper/layouts/NewsHeadlineV2.tsx
CHANGED
|
@@ -131,8 +131,8 @@ export const NewsHeadlineV2: React.FC<
|
|
| 131 |
first ten frames, in the equivalent newspaper opening scene). */
|
| 132 |
const titleRef = React.useRef<HTMLDivElement>(null);
|
| 133 |
const narrationRef = React.useRef<HTMLDivElement>(null);
|
| 134 |
-
const titleTargetPx = titleFontSize ?? (p ?
|
| 135 |
-
const narrationTargetPx = descriptionFontSize ?? (p ?
|
| 136 |
const stackBudgetPx = Math.round(videoHeight * (hasVisual ? (p ? 0.34 : 0.32) : p ? 0.55 : 0.5));
|
| 137 |
const titleBudgetPx = Math.round(stackBudgetPx * (narration ? 0.66 : 1));
|
| 138 |
|
|
|
|
| 131 |
first ten frames, in the equivalent newspaper opening scene). */
|
| 132 |
const titleRef = React.useRef<HTMLDivElement>(null);
|
| 133 |
const narrationRef = React.useRef<HTMLDivElement>(null);
|
| 134 |
+
const titleTargetPx = titleFontSize ?? (p ? 65 : 54);
|
| 135 |
+
const narrationTargetPx = descriptionFontSize ?? (p ? 32 : 27);
|
| 136 |
const stackBudgetPx = Math.round(videoHeight * (hasVisual ? (p ? 0.34 : 0.32) : p ? 0.55 : 0.5));
|
| 137 |
const titleBudgetPx = Math.round(stackBudgetPx * (narration ? 0.66 : 1));
|
| 138 |
|
frontend/src/components/remotion/newspaper/layouts/NewsHeadlineV3.tsx
CHANGED
|
@@ -141,8 +141,8 @@ export const NewsHeadlineV3: React.FC<
|
|
| 141 |
first ten frames, in the equivalent newspaper opening scene). */
|
| 142 |
const titleRef = React.useRef<HTMLDivElement>(null);
|
| 143 |
const narrationRef = React.useRef<HTMLDivElement>(null);
|
| 144 |
-
const titleTargetPx = titleFontSize ?? (p ?
|
| 145 |
-
const narrationTargetPx = descriptionFontSize ?? (p ?
|
| 146 |
const stackBudgetPx = Math.round(videoHeight * (hasVisual ? (p ? 0.32 : 0.62) : p ? 0.6 : 0.62));
|
| 147 |
const titleBudgetPx = Math.round(stackBudgetPx * (narration ? 0.6 : 1));
|
| 148 |
|
|
|
|
| 141 |
first ten frames, in the equivalent newspaper opening scene). */
|
| 142 |
const titleRef = React.useRef<HTMLDivElement>(null);
|
| 143 |
const narrationRef = React.useRef<HTMLDivElement>(null);
|
| 144 |
+
const titleTargetPx = titleFontSize ?? (p ? 66 : 50);
|
| 145 |
+
const narrationTargetPx = descriptionFontSize ?? (p ? 33 : 26);
|
| 146 |
const stackBudgetPx = Math.round(videoHeight * (hasVisual ? (p ? 0.32 : 0.62) : p ? 0.6 : 0.62));
|
| 147 |
const titleBudgetPx = Math.round(stackBudgetPx * (narration ? 0.6 : 1));
|
| 148 |
|
frontend/src/components/remotion/nightfall/layouts/SplitGlass.tsx
CHANGED
|
@@ -79,10 +79,14 @@ export const SplitGlass: React.FC<NightfallLayoutProps> = ({
|
|
| 79 |
// Portrait specific animation timings and values
|
| 80 |
const pEntryStart = 15;
|
| 81 |
const pEntrySettled = pEntryStart + 40; // When entry animation settles
|
| 82 |
-
|
|
|
|
|
|
|
| 83 |
const pHoldEnd = pEntrySettled + pHoldDuration;
|
| 84 |
const pExitStart = pHoldEnd; // When exit animation starts
|
| 85 |
-
|
|
|
|
|
|
|
| 86 |
|
| 87 |
// Portrait card opacity (fade in, stay, fade out)
|
| 88 |
const pCardOpacity = interpolate(
|
|
@@ -92,11 +96,13 @@ export const SplitGlass: React.FC<NightfallLayoutProps> = ({
|
|
| 92 |
{ extrapolateRight: "clamp" }
|
| 93 |
);
|
| 94 |
|
| 95 |
-
// Portrait card Y position (start high, settle, stay,
|
|
|
|
|
|
|
| 96 |
const pCardTransformY = interpolate(
|
| 97 |
frame,
|
| 98 |
[pEntryStart, pEntrySettled, pExitStart, pExitEnd],
|
| 99 |
-
[-300, 0, 0,
|
| 100 |
{ extrapolateRight: "clamp" }
|
| 101 |
);
|
| 102 |
|
|
|
|
| 79 |
// Portrait specific animation timings and values
|
| 80 |
const pEntryStart = 15;
|
| 81 |
const pEntrySettled = pEntryStart + 40; // When entry animation settles
|
| 82 |
+
// Cards hold well past the point the text is readable before leaving, so the
|
| 83 |
+
// exit reads as a deliberate beat rather than the cards drifting off mid-read.
|
| 84 |
+
const pHoldDuration = 85;
|
| 85 |
const pHoldEnd = pEntrySettled + pHoldDuration;
|
| 86 |
const pExitStart = pHoldEnd; // When exit animation starts
|
| 87 |
+
// Short window: once they go, they go. A long exit made the cards hang
|
| 88 |
+
// around half-faded, which read as sinking rather than flowing away.
|
| 89 |
+
const pExitEnd = pExitStart + 20; // When exit animation finishes
|
| 90 |
|
| 91 |
// Portrait card opacity (fade in, stay, fade out)
|
| 92 |
const pCardOpacity = interpolate(
|
|
|
|
| 96 |
{ extrapolateRight: "clamp" }
|
| 97 |
);
|
| 98 |
|
| 99 |
+
// Portrait card Y position (start high, settle, stay, sweep away)
|
| 100 |
+
// Travels well past the old 300px so the cards clear frame while the fade
|
| 101 |
+
// is still running — they flow out instead of fading in place.
|
| 102 |
const pCardTransformY = interpolate(
|
| 103 |
frame,
|
| 104 |
[pEntryStart, pEntrySettled, pExitStart, pExitEnd],
|
| 105 |
+
[-300, 0, 0, 700],
|
| 106 |
{ extrapolateRight: "clamp" }
|
| 107 |
);
|
| 108 |
|
frontend/src/hooks/useEmailAuth.ts
ADDED
|
@@ -0,0 +1,411 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { useCallback, useState } from "react";
|
| 2 |
+
|
| 3 |
+
import {
|
| 4 |
+
emailLogin,
|
| 5 |
+
emailRegisterResend,
|
| 6 |
+
emailRegisterStart,
|
| 7 |
+
emailRegisterVerify,
|
| 8 |
+
forgotPasswordCheck,
|
| 9 |
+
forgotPasswordComplete,
|
| 10 |
+
forgotPasswordStart,
|
| 11 |
+
} from "../api/client";
|
| 12 |
+
import { useAuth } from "./useAuth";
|
| 13 |
+
import { usePostLoginRedirect } from "./usePostLoginRedirect";
|
| 14 |
+
import { parseLoginError, type LoginError } from "./useSocialLogin";
|
| 15 |
+
import { getErrorMessage } from "../contexts/ErrorModalContext";
|
| 16 |
+
|
| 17 |
+
/**
|
| 18 |
+
* Built-in email + password sign-in, as a staged flow inside the login modal.
|
| 19 |
+
*
|
| 20 |
+
* Mirrors useSocialLogin's contract (same onSuccess/skipRedirect options, the
|
| 21 |
+
* same LoginError shape, the same held-credential reactivation retry) so the
|
| 22 |
+
* modal can treat both paths identically and the 409 wrong-provider recovery
|
| 23 |
+
* works the same whichever one produced it.
|
| 24 |
+
*/
|
| 25 |
+
|
| 26 |
+
/** Seconds between code resends; matches RESEND_COOLDOWN_SECONDS server-side. */
|
| 27 |
+
const RESEND_COOLDOWN_SECONDS = 60;
|
| 28 |
+
|
| 29 |
+
/**
|
| 30 |
+
* Which of the two intents the user picked on the first step.
|
| 31 |
+
*
|
| 32 |
+
* It only changes wording and which request the password step fires — it is NOT
|
| 33 |
+
* a security boundary. Signing up with an address that already exists still
|
| 34 |
+
* returns 409, and logging in with one that doesn't still returns the same
|
| 35 |
+
* ambiguous 401, so picking the "wrong" one costs a click, never information.
|
| 36 |
+
*/
|
| 37 |
+
export type EmailMode = "login" | "signup";
|
| 38 |
+
|
| 39 |
+
export type EmailStage =
|
| 40 |
+
// `email` carries the address too, so stepping back (or being routed back by
|
| 41 |
+
// an error) never makes the user retype what they already entered.
|
| 42 |
+
| { name: "email"; mode: EmailMode; email: string }
|
| 43 |
+
/**
|
| 44 |
+
* `switchedFromSignup` marks the one transition the user did not ask for:
|
| 45 |
+
* they submitted a SIGNUP and the address turned out to already exist, so we
|
| 46 |
+
* flipped them to the sign-in form. The form reads it to clear the carried-over
|
| 47 |
+
* password and keep the "account already exists" notice up.
|
| 48 |
+
*
|
| 49 |
+
* Without it the signup password sat in a login box under a "Sign in" button,
|
| 50 |
+
* so the next submit either said "email and password don't match" (burying the
|
| 51 |
+
* real reason) or — when the two passwords happened to match — silently signed
|
| 52 |
+
* them in, which is not what anyone clicking "Sign up" asked for.
|
| 53 |
+
*/
|
| 54 |
+
| { name: "password"; email: string; mode: EmailMode; switchedFromSignup?: boolean }
|
| 55 |
+
| { name: "otp"; email: string; resendAt: number }
|
| 56 |
+
| { name: "forgot_email"; email: string }
|
| 57 |
+
| { name: "forgot_code"; email: string; resendAt: number }
|
| 58 |
+
| { name: "forgot_password"; email: string; code: string };
|
| 59 |
+
|
| 60 |
+
interface UseEmailAuthOptions {
|
| 61 |
+
onSuccess?: () => void;
|
| 62 |
+
skipRedirect?: boolean;
|
| 63 |
+
/** Which intent the surface opens in. Defaults to "signup": most people
|
| 64 |
+
* reaching a sign-in surface from a CTA are new, and an existing user is one
|
| 65 |
+
* click from the "Already have an account? Sign in" toggle. /signin passes
|
| 66 |
+
* "login" explicitly so that route still opens on the sign-in form. */
|
| 67 |
+
initialMode?: EmailMode;
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
function resendAtFrom(resendIn?: number): number {
|
| 71 |
+
return Date.now() + (resendIn ?? RESEND_COOLDOWN_SECONDS) * 1000;
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
export function useEmailAuth({
|
| 75 |
+
onSuccess,
|
| 76 |
+
skipRedirect = false,
|
| 77 |
+
initialMode = "signup",
|
| 78 |
+
}: UseEmailAuthOptions = {}) {
|
| 79 |
+
const { login } = useAuth();
|
| 80 |
+
const redirectAfterLogin = usePostLoginRedirect();
|
| 81 |
+
|
| 82 |
+
const [stage, setStage] = useState<EmailStage>({ name: "email", mode: initialMode, email: "" });
|
| 83 |
+
const [busy, setBusy] = useState(false);
|
| 84 |
+
const [error, setError] = useState<LoginError | null>(null);
|
| 85 |
+
/**
|
| 86 |
+
* What the account-deleted prompt should retry, held exactly as useSocialLogin
|
| 87 |
+
* holds the provider token.
|
| 88 |
+
*
|
| 89 |
+
* Two shapes, because a deleted account can be met on two different steps and
|
| 90 |
+
* they are reactivated by different requests:
|
| 91 |
+
* login — the typed credential; retried as emailLogin(?reactivate=true).
|
| 92 |
+
* forgot — the address alone; retried as forgotPasswordStart(?reactivate=true).
|
| 93 |
+
* The forgot case has no password to hold by definition, which is why it can't
|
| 94 |
+
* reuse the login retry — that was the bug: `reactivate` bailed on a null
|
| 95 |
+
* `pending` and the confirm button did nothing.
|
| 96 |
+
*/
|
| 97 |
+
type PendingReactivation =
|
| 98 |
+
| { via: "login"; email: string; password: string }
|
| 99 |
+
| { via: "forgot"; email: string };
|
| 100 |
+
const [pending, setPending] = useState<PendingReactivation | null>(null);
|
| 101 |
+
/** True while the in-flight request is a reactivation rather than a sign-in.
|
| 102 |
+
* `busy` alone can't distinguish them, and the two need different wording. */
|
| 103 |
+
const [reactivating, setReactivating] = useState(false);
|
| 104 |
+
|
| 105 |
+
const finish = useCallback(
|
| 106 |
+
async (token: string, user: Parameters<typeof login>[1]) => {
|
| 107 |
+
localStorage.removeItem("b2v_ref_code");
|
| 108 |
+
login(token, user);
|
| 109 |
+
onSuccess?.();
|
| 110 |
+
if (!skipRedirect) await redirectAfterLogin();
|
| 111 |
+
},
|
| 112 |
+
[login, redirectAfterLogin, onSuccess, skipRedirect]
|
| 113 |
+
);
|
| 114 |
+
|
| 115 |
+
/** Switch between "Log in" and "Sign up" on the first step. */
|
| 116 |
+
const setMode = useCallback((mode: EmailMode) => {
|
| 117 |
+
setError(null);
|
| 118 |
+
setStage((s) =>
|
| 119 |
+
s.name === "email"
|
| 120 |
+
? { name: "email", mode, email: s.email }
|
| 121 |
+
: s.name === "password"
|
| 122 |
+
? { name: "password", email: s.email, mode }
|
| 123 |
+
: s
|
| 124 |
+
);
|
| 125 |
+
}, []);
|
| 126 |
+
|
| 127 |
+
/** Step 1: an address was entered. We never probe whether it exists — that
|
| 128 |
+
* would be an account-existence oracle with no other purpose — so both modes
|
| 129 |
+
* go to the password step and the request's outcome disambiguates. */
|
| 130 |
+
const submitEmail = useCallback((email: string, mode: EmailMode) => {
|
| 131 |
+
setError(null);
|
| 132 |
+
setStage({ name: "password", email: email.trim().toLowerCase(), mode });
|
| 133 |
+
}, []);
|
| 134 |
+
|
| 135 |
+
/** Keep the stage's address in step with the field as the user types, so any
|
| 136 |
+
* error that routes them elsewhere still has it. */
|
| 137 |
+
const setEmailValue = useCallback((email: string) => {
|
| 138 |
+
setStage((s) => (s.name === "email" ? { ...s, email } : s));
|
| 139 |
+
}, []);
|
| 140 |
+
|
| 141 |
+
/**
|
| 142 |
+
* "This address already has a password account" — however it was phrased.
|
| 143 |
+
*
|
| 144 |
+
* The backend says this two ways: `email_already_registered` when signup finds
|
| 145 |
+
* a live account, and a `wrong_provider` 409 naming "email" when the account
|
| 146 |
+
* is found by the shared identity check. They mean the same thing to the user,
|
| 147 |
+
* and every path that can raise either must route to the SAME place, or they
|
| 148 |
+
* end up reading "sign in with your password" on a screen that has no password
|
| 149 |
+
* field — and, worse, an empty email box they must retype.
|
| 150 |
+
*/
|
| 151 |
+
const isExistingEmailAccount = (parsed: LoginError) =>
|
| 152 |
+
parsed.kind === "email_already_registered" ||
|
| 153 |
+
(parsed.kind === "wrong_provider" && parsed.provider === "email");
|
| 154 |
+
|
| 155 |
+
/** Step 2. In login mode this signs in; in signup mode it requests a code.
|
| 156 |
+
* Either way a mismatch between the mode and reality is recoverable in one
|
| 157 |
+
* click — the errors below flip the user to the other mode rather than
|
| 158 |
+
* dead-ending them. */
|
| 159 |
+
const submitPassword = useCallback(
|
| 160 |
+
async (email: string, password: string, mode: EmailMode) => {
|
| 161 |
+
setBusy(true);
|
| 162 |
+
setError(null);
|
| 163 |
+
try {
|
| 164 |
+
if (mode === "signup") {
|
| 165 |
+
const res = await emailRegisterStart(email, password);
|
| 166 |
+
setStage({ name: "otp", email, resendAt: resendAtFrom(res.data.resend_in) });
|
| 167 |
+
setBusy(false);
|
| 168 |
+
return;
|
| 169 |
+
}
|
| 170 |
+
const res = await emailLogin(email, password);
|
| 171 |
+
await finish(res.data.access_token, res.data.user);
|
| 172 |
+
} catch (err) {
|
| 173 |
+
const parsed = parseLoginError(err);
|
| 174 |
+
// Only a LOGIN can offer reactivation. The signup endpoint answers
|
| 175 |
+
// `email_already_registered` for a deleted account rather than 403, so
|
| 176 |
+
// this should be unreachable in signup mode — but the mode gate stays as
|
| 177 |
+
// defence in depth: holding a freshly-typed signup password as the
|
| 178 |
+
// credential for an existing account would let the confirm button sign
|
| 179 |
+
// someone in with a password that account never had.
|
| 180 |
+
if (parsed.kind === "account_deleted" && mode === "login") {
|
| 181 |
+
setPending({ via: "login", email, password });
|
| 182 |
+
}
|
| 183 |
+
// Signed up with an address that already exists -> they meant to log in.
|
| 184 |
+
// Flagged as an involuntary switch so the form drops the signup password
|
| 185 |
+
// instead of offering it for one-click sign-in under a new label.
|
| 186 |
+
if (isExistingEmailAccount(parsed)) {
|
| 187 |
+
setStage({ name: "password", email, mode: "login", switchedFromSignup: true });
|
| 188 |
+
}
|
| 189 |
+
setError(parsed);
|
| 190 |
+
setBusy(false);
|
| 191 |
+
}
|
| 192 |
+
},
|
| 193 |
+
[finish]
|
| 194 |
+
);
|
| 195 |
+
|
| 196 |
+
const submitCode = useCallback(
|
| 197 |
+
async (email: string, code: string) => {
|
| 198 |
+
setBusy(true);
|
| 199 |
+
setError(null);
|
| 200 |
+
try {
|
| 201 |
+
const refCode = localStorage.getItem("b2v_ref_code");
|
| 202 |
+
const res = await emailRegisterVerify(email, code, refCode);
|
| 203 |
+
await finish(res.data.access_token, res.data.user);
|
| 204 |
+
} catch (err) {
|
| 205 |
+
const parsed = parseLoginError(err);
|
| 206 |
+
// A burned code can't be retried — send them back to start over.
|
| 207 |
+
if (parsed.kind === "code_burned") setStage({ name: "password", email, mode: "signup" });
|
| 208 |
+
// Someone registered this address while the code was in flight, so the
|
| 209 |
+
// pending signup is moot — hand them the sign-in form for it.
|
| 210 |
+
else if (isExistingEmailAccount(parsed)) {
|
| 211 |
+
setStage({ name: "password", email, mode: "login", switchedFromSignup: true });
|
| 212 |
+
}
|
| 213 |
+
setError(parsed);
|
| 214 |
+
setBusy(false);
|
| 215 |
+
}
|
| 216 |
+
},
|
| 217 |
+
[finish]
|
| 218 |
+
);
|
| 219 |
+
|
| 220 |
+
const resendCode = useCallback(async (email: string) => {
|
| 221 |
+
setBusy(true);
|
| 222 |
+
setError(null);
|
| 223 |
+
try {
|
| 224 |
+
const res = await emailRegisterResend(email);
|
| 225 |
+
setStage({ name: "otp", email, resendAt: resendAtFrom(res.data.resend_in) });
|
| 226 |
+
setBusy(false);
|
| 227 |
+
} catch (err) {
|
| 228 |
+
const parsed = parseLoginError(err);
|
| 229 |
+
// Cooldown: keep the user on the code step, just re-arm the timer.
|
| 230 |
+
if (parsed.kind === "resend_cooldown") {
|
| 231 |
+
setStage({ name: "otp", email, resendAt: resendAtFrom(parsed.retryAfter) });
|
| 232 |
+
} else if (isExistingEmailAccount(parsed)) {
|
| 233 |
+
setStage({ name: "password", email, mode: "login", switchedFromSignup: true });
|
| 234 |
+
}
|
| 235 |
+
setError(parsed);
|
| 236 |
+
setBusy(false);
|
| 237 |
+
}
|
| 238 |
+
}, []);
|
| 239 |
+
|
| 240 |
+
// ─── Forgot password ──────────────────────────────────────────────────
|
| 241 |
+
|
| 242 |
+
const startForgot = useCallback((email: string) => {
|
| 243 |
+
setError(null);
|
| 244 |
+
setStage({ name: "forgot_email", email });
|
| 245 |
+
}, []);
|
| 246 |
+
|
| 247 |
+
/** Ask for a reset code. `confirmReactivate` revives a soft-deleted account
|
| 248 |
+
* first; it still only emails a code, so this never signs anyone in. */
|
| 249 |
+
const requestResetCode = useCallback(async (email: string, confirmReactivate = false) => {
|
| 250 |
+
setBusy(true);
|
| 251 |
+
if (confirmReactivate) setReactivating(true);
|
| 252 |
+
setError(null);
|
| 253 |
+
try {
|
| 254 |
+
const res = await forgotPasswordStart(email, confirmReactivate);
|
| 255 |
+
setPending(null);
|
| 256 |
+
setStage({ name: "forgot_code", email, resendAt: resendAtFrom(res.data.resend_in) });
|
| 257 |
+
setBusy(false);
|
| 258 |
+
setReactivating(false);
|
| 259 |
+
} catch (err) {
|
| 260 |
+
const parsed = parseLoginError(err);
|
| 261 |
+
// Deleted account: hold the address so the confirm dialog can retry this
|
| 262 |
+
// same request with ?reactivate=true. There is no password to hold here —
|
| 263 |
+
// the user is on this path precisely because they don't have it.
|
| 264 |
+
if (parsed.kind === "account_deleted") setPending({ via: "forgot", email });
|
| 265 |
+
setError(parsed);
|
| 266 |
+
setBusy(false);
|
| 267 |
+
setReactivating(false);
|
| 268 |
+
}
|
| 269 |
+
}, []);
|
| 270 |
+
|
| 271 |
+
/** The code is carried forward, not verified separately: checking it in its
|
| 272 |
+
* own round trip would consume it and leave nothing to authorize the change. */
|
| 273 |
+
const submitResetCode = useCallback(async (email: string, code: string) => {
|
| 274 |
+
setBusy(true);
|
| 275 |
+
setError(null);
|
| 276 |
+
try {
|
| 277 |
+
// Validate up front so a wrong code is rejected HERE rather than walking
|
| 278 |
+
// the user through choosing a new password and only failing on submit.
|
| 279 |
+
// This does not spend the code — forgot/complete still consumes it, since
|
| 280 |
+
// that is what authorizes the actual password change.
|
| 281 |
+
await forgotPasswordCheck(email, code);
|
| 282 |
+
setStage({ name: "forgot_password", email, code });
|
| 283 |
+
setBusy(false);
|
| 284 |
+
} catch (err) {
|
| 285 |
+
const parsed = parseLoginError(err);
|
| 286 |
+
// A burned or expired code can't be retried — send them back to request
|
| 287 |
+
// a fresh one instead of leaving them on a dead input.
|
| 288 |
+
if (parsed.kind === "code_burned" || parsed.kind === "code_expired") {
|
| 289 |
+
setStage({ name: "forgot_email", email });
|
| 290 |
+
}
|
| 291 |
+
setError(parsed);
|
| 292 |
+
setBusy(false);
|
| 293 |
+
}
|
| 294 |
+
}, []);
|
| 295 |
+
|
| 296 |
+
const completeReset = useCallback(
|
| 297 |
+
async (email: string, code: string, newPassword: string) => {
|
| 298 |
+
setBusy(true);
|
| 299 |
+
setError(null);
|
| 300 |
+
try {
|
| 301 |
+
const res = await forgotPasswordComplete(email, code, newPassword);
|
| 302 |
+
await finish(res.data.access_token, res.data.user);
|
| 303 |
+
} catch (err) {
|
| 304 |
+
const parsed = parseLoginError(err);
|
| 305 |
+
// The code was rejected, so go back and let them re-enter it.
|
| 306 |
+
if (
|
| 307 |
+
parsed.kind === "code_invalid" ||
|
| 308 |
+
parsed.kind === "code_expired" ||
|
| 309 |
+
parsed.kind === "code_burned"
|
| 310 |
+
) {
|
| 311 |
+
setStage({ name: "forgot_code", email, resendAt: 0 });
|
| 312 |
+
}
|
| 313 |
+
setError(parsed);
|
| 314 |
+
setBusy(false);
|
| 315 |
+
}
|
| 316 |
+
},
|
| 317 |
+
[finish]
|
| 318 |
+
);
|
| 319 |
+
|
| 320 |
+
/**
|
| 321 |
+
* Confirm reactivation of a soft-deleted account, by whichever route met it.
|
| 322 |
+
*
|
| 323 |
+
* From the login step the held password reactivates and signs in directly.
|
| 324 |
+
* From the forgot-password step there is no password, so it reactivates and
|
| 325 |
+
* emails a reset code instead — the user lands on the code step and only
|
| 326 |
+
* reaches a session after setting a new one, which is the whole point: a
|
| 327 |
+
* confirmation click must not itself be a way into an account whose password
|
| 328 |
+
* the clicker doesn't know.
|
| 329 |
+
*/
|
| 330 |
+
const reactivate = useCallback(async () => {
|
| 331 |
+
if (!pending) return;
|
| 332 |
+
if (pending.via === "forgot") {
|
| 333 |
+
await requestResetCode(pending.email, true);
|
| 334 |
+
return;
|
| 335 |
+
}
|
| 336 |
+
setBusy(true);
|
| 337 |
+
setReactivating(true);
|
| 338 |
+
setError(null);
|
| 339 |
+
try {
|
| 340 |
+
const res = await emailLogin(pending.email, pending.password, true);
|
| 341 |
+
setPending(null);
|
| 342 |
+
await finish(res.data.access_token, res.data.user);
|
| 343 |
+
} catch (err) {
|
| 344 |
+
setError({
|
| 345 |
+
kind: "generic",
|
| 346 |
+
message: getErrorMessage(err, "Failed to reactivate account."),
|
| 347 |
+
});
|
| 348 |
+
setBusy(false);
|
| 349 |
+
setReactivating(false);
|
| 350 |
+
}
|
| 351 |
+
}, [pending, finish, requestResetCode]);
|
| 352 |
+
|
| 353 |
+
/** One step back, preserving the address so it needn't be retyped. */
|
| 354 |
+
const back = useCallback(() => {
|
| 355 |
+
setError(null);
|
| 356 |
+
setPending(null);
|
| 357 |
+
setStage((s) => {
|
| 358 |
+
switch (s.name) {
|
| 359 |
+
case "password":
|
| 360 |
+
return { name: "email", mode: s.mode, email: s.email };
|
| 361 |
+
case "otp":
|
| 362 |
+
return { name: "password", email: s.email, mode: "signup" };
|
| 363 |
+
case "forgot_email":
|
| 364 |
+
return { name: "password", email: s.email, mode: "login" };
|
| 365 |
+
case "forgot_code":
|
| 366 |
+
return { name: "forgot_email", email: s.email };
|
| 367 |
+
case "forgot_password":
|
| 368 |
+
return { name: "forgot_code", email: s.email, resendAt: 0 };
|
| 369 |
+
default:
|
| 370 |
+
return s;
|
| 371 |
+
}
|
| 372 |
+
});
|
| 373 |
+
}, []);
|
| 374 |
+
|
| 375 |
+
/** Dismiss the current error without leaving the step or losing what was typed.
|
| 376 |
+
* Used by the reactivation prompt's Cancel, which must not restart the flow. */
|
| 377 |
+
const dismissError = useCallback(() => {
|
| 378 |
+
setError(null);
|
| 379 |
+
setPending(null);
|
| 380 |
+
setReactivating(false);
|
| 381 |
+
}, []);
|
| 382 |
+
|
| 383 |
+
const reset = useCallback(() => {
|
| 384 |
+
setReactivating(false);
|
| 385 |
+
setStage({ name: "email", mode: initialMode, email: "" });
|
| 386 |
+
setError(null);
|
| 387 |
+
setPending(null);
|
| 388 |
+
setBusy(false);
|
| 389 |
+
}, [initialMode]);
|
| 390 |
+
|
| 391 |
+
return {
|
| 392 |
+
stage,
|
| 393 |
+
busy,
|
| 394 |
+
error,
|
| 395 |
+
setMode,
|
| 396 |
+
setEmailValue,
|
| 397 |
+
submitEmail,
|
| 398 |
+
submitPassword,
|
| 399 |
+
submitCode,
|
| 400 |
+
resendCode,
|
| 401 |
+
startForgot,
|
| 402 |
+
requestResetCode,
|
| 403 |
+
submitResetCode,
|
| 404 |
+
completeReset,
|
| 405 |
+
reactivate,
|
| 406 |
+
reactivating,
|
| 407 |
+
dismissError,
|
| 408 |
+
back,
|
| 409 |
+
reset,
|
| 410 |
+
};
|
| 411 |
+
}
|
frontend/src/hooks/useSocialLogin.ts
CHANGED
|
@@ -1,12 +1,14 @@
|
|
| 1 |
import { useCallback, useState } from "react";
|
| 2 |
import type { CredentialResponse } from "@react-oauth/google";
|
| 3 |
|
| 4 |
-
import {
|
| 5 |
-
import
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
import { useAuth } from "./useAuth";
|
| 7 |
import { usePostLoginRedirect } from "./usePostLoginRedirect";
|
| 8 |
-
import { AppleSignInCancelled, signInWithApple } from "../lib/appleSignIn";
|
| 9 |
-
import { MicrosoftSignInCancelled, signInWithMicrosoft } from "../lib/microsoftSignIn";
|
| 10 |
import { getErrorMessage } from "../contexts/ErrorModalContext";
|
| 11 |
|
| 12 |
/**
|
|
@@ -16,14 +18,25 @@ import { getErrorMessage } from "../contexts/ErrorModalContext";
|
|
| 16 |
* login() → redirect with their own error handling, and only three of them
|
| 17 |
* understood the `account_deleted` response. Centralizing it means a new
|
| 18 |
* provider or a new failure mode is handled once.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
*/
|
| 20 |
|
| 21 |
/** What the UI should show; anything unmapped falls through to `message`. */
|
| 22 |
export type LoginErrorKind =
|
| 23 |
| "wrong_provider"
|
| 24 |
| "account_deleted"
|
| 25 |
-
|
| 26 |
-
| "
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
| "generic";
|
| 28 |
|
| 29 |
export interface LoginError {
|
|
@@ -34,6 +47,10 @@ export interface LoginError {
|
|
| 34 |
providerLabel?: string;
|
| 35 |
/** For "wrong_provider": that account is soft-deleted, so word it as reactivation. */
|
| 36 |
deleted?: boolean;
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
}
|
| 38 |
|
| 39 |
interface WrongProviderDetail {
|
|
@@ -43,11 +60,24 @@ interface WrongProviderDetail {
|
|
| 43 |
deleted: boolean;
|
| 44 |
}
|
| 45 |
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
const status = res?.status;
|
| 50 |
const detail = res?.data?.detail;
|
|
|
|
| 51 |
|
| 52 |
// 409: the email belongs to the other provider. The body names it so we can
|
| 53 |
// offer a one-click switch rather than making the user guess.
|
|
@@ -56,17 +86,26 @@ function parseLoginError(err: unknown): LoginError {
|
|
| 56 |
if (d.code === "wrong_auth_provider" && d.provider) {
|
| 57 |
// The backend always sends provider_label; the map is a defensive
|
| 58 |
// fallback that must name the right provider, never a two-way guess.
|
| 59 |
-
const label =
|
| 60 |
-
|
| 61 |
-
({ google: "Google", apple: "Apple", microsoft: "Microsoft" }[d.provider] ?? d.provider);
|
| 62 |
return {
|
| 63 |
kind: "wrong_provider",
|
| 64 |
provider: d.provider,
|
| 65 |
providerLabel: label,
|
| 66 |
deleted: Boolean(d.deleted),
|
| 67 |
message: d.deleted
|
| 68 |
-
?
|
| 69 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
};
|
| 71 |
}
|
| 72 |
}
|
|
@@ -75,19 +114,93 @@ function parseLoginError(err: unknown): LoginError {
|
|
| 75 |
return { kind: "account_deleted", message: "This account was deleted." };
|
| 76 |
}
|
| 77 |
|
| 78 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
return {
|
| 80 |
-
kind: "
|
| 81 |
-
message:
|
| 82 |
-
"Please share your email to continue. Choose your Apple email instead of “Hide My Email” when signing in.",
|
| 83 |
};
|
| 84 |
}
|
| 85 |
|
| 86 |
-
if (status ===
|
| 87 |
return {
|
| 88 |
-
kind: "
|
| 89 |
-
|
| 90 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
};
|
| 92 |
}
|
| 93 |
|
|
@@ -119,14 +232,12 @@ export function useSocialLogin({
|
|
| 119 |
const redirectAfterLogin = usePostLoginRedirect();
|
| 120 |
|
| 121 |
const [signingIn, setSigningIn] = useState(false);
|
|
|
|
|
|
|
|
|
|
| 122 |
const [error, setError] = useState<LoginError | null>(null);
|
| 123 |
/** Held so the account-deleted prompt can retry the same credential. */
|
| 124 |
-
const [pending, setPending] = useState<
|
| 125 |
-
| { provider: "google"; credential: string }
|
| 126 |
-
| { provider: "apple"; identityToken: string }
|
| 127 |
-
| { provider: "microsoft"; idToken: string }
|
| 128 |
-
| null
|
| 129 |
-
>(null);
|
| 130 |
|
| 131 |
const finish = useCallback(
|
| 132 |
async (token: string, user: Parameters<typeof login>[1]) => {
|
|
@@ -152,7 +263,7 @@ export function useSocialLogin({
|
|
| 152 |
} catch (err) {
|
| 153 |
const parsed = parseLoginError(err);
|
| 154 |
if (parsed.kind === "account_deleted") {
|
| 155 |
-
setPending({
|
| 156 |
}
|
| 157 |
setError(parsed);
|
| 158 |
setSigningIn(false);
|
|
@@ -161,95 +272,14 @@ export function useSocialLogin({
|
|
| 161 |
[finish]
|
| 162 |
);
|
| 163 |
|
| 164 |
-
const startAppleSignIn = useCallback(async () => {
|
| 165 |
-
setSigningIn(true);
|
| 166 |
-
setError(null);
|
| 167 |
-
const refCode = localStorage.getItem("b2v_ref_code");
|
| 168 |
-
|
| 169 |
-
// Obtain the token first, so the exchange below can hold on to it for a
|
| 170 |
-
// possible reactivation retry.
|
| 171 |
-
let identityToken: string;
|
| 172 |
-
let appleUser: Awaited<ReturnType<typeof signInWithApple>>["user"];
|
| 173 |
-
try {
|
| 174 |
-
({ identityToken, user: appleUser } = await signInWithApple());
|
| 175 |
-
} catch (err) {
|
| 176 |
-
// Closing the popup is a deliberate action, not an error to report.
|
| 177 |
-
if (err instanceof AppleSignInCancelled) {
|
| 178 |
-
setSigningIn(false);
|
| 179 |
-
return;
|
| 180 |
-
}
|
| 181 |
-
setError({
|
| 182 |
-
kind: "generic",
|
| 183 |
-
message: getErrorMessage(err, "Apple sign-in failed. Please try again."),
|
| 184 |
-
});
|
| 185 |
-
setSigningIn(false);
|
| 186 |
-
return;
|
| 187 |
-
}
|
| 188 |
-
|
| 189 |
-
try {
|
| 190 |
-
const res = await appleLogin(identityToken, appleUser, false, refCode);
|
| 191 |
-
await finish(res.data.access_token, res.data.user);
|
| 192 |
-
} catch (err) {
|
| 193 |
-
const parsed = parseLoginError(err);
|
| 194 |
-
if (parsed.kind === "account_deleted") {
|
| 195 |
-
setPending({ provider: "apple", identityToken });
|
| 196 |
-
}
|
| 197 |
-
setError(parsed);
|
| 198 |
-
setSigningIn(false);
|
| 199 |
-
}
|
| 200 |
-
}, [finish]);
|
| 201 |
-
|
| 202 |
-
const startMicrosoftSignIn = useCallback(async () => {
|
| 203 |
-
setSigningIn(true);
|
| 204 |
-
setError(null);
|
| 205 |
-
const refCode = localStorage.getItem("b2v_ref_code");
|
| 206 |
-
|
| 207 |
-
// Obtain the token first, so the exchange below can hold on to it for a
|
| 208 |
-
// possible reactivation retry.
|
| 209 |
-
let idToken: string;
|
| 210 |
-
try {
|
| 211 |
-
({ idToken } = await signInWithMicrosoft());
|
| 212 |
-
} catch (err) {
|
| 213 |
-
// Closing the popup is a deliberate action, not an error to report.
|
| 214 |
-
if (err instanceof MicrosoftSignInCancelled) {
|
| 215 |
-
setSigningIn(false);
|
| 216 |
-
return;
|
| 217 |
-
}
|
| 218 |
-
setError({
|
| 219 |
-
kind: "generic",
|
| 220 |
-
message: getErrorMessage(err, "Microsoft sign-in failed. Please try again."),
|
| 221 |
-
});
|
| 222 |
-
setSigningIn(false);
|
| 223 |
-
return;
|
| 224 |
-
}
|
| 225 |
-
|
| 226 |
-
try {
|
| 227 |
-
const res = await microsoftLogin(idToken, false, refCode);
|
| 228 |
-
await finish(res.data.access_token, res.data.user);
|
| 229 |
-
} catch (err) {
|
| 230 |
-
const parsed = parseLoginError(err);
|
| 231 |
-
if (parsed.kind === "account_deleted") {
|
| 232 |
-
setPending({ provider: "microsoft", idToken });
|
| 233 |
-
}
|
| 234 |
-
setError(parsed);
|
| 235 |
-
setSigningIn(false);
|
| 236 |
-
}
|
| 237 |
-
}, [finish]);
|
| 238 |
-
|
| 239 |
/** Confirm reactivation of a soft-deleted account, reusing the held credential. */
|
| 240 |
const reactivate = useCallback(async () => {
|
| 241 |
if (!pending) return;
|
| 242 |
setSigningIn(true);
|
|
|
|
| 243 |
setError(null);
|
| 244 |
try {
|
| 245 |
-
|
| 246 |
-
if (pending.provider === "google") {
|
| 247 |
-
res = await googleLogin(pending.credential, true);
|
| 248 |
-
} else if (pending.provider === "apple") {
|
| 249 |
-
res = await appleLogin(pending.identityToken, null, true);
|
| 250 |
-
} else {
|
| 251 |
-
res = await microsoftLogin(pending.idToken, true);
|
| 252 |
-
}
|
| 253 |
setPending(null);
|
| 254 |
await finish(res.data.access_token, res.data.user);
|
| 255 |
} catch (err) {
|
|
@@ -258,22 +288,31 @@ export function useSocialLogin({
|
|
| 258 |
message: getErrorMessage(err, "Failed to reactivate account."),
|
| 259 |
});
|
| 260 |
setSigningIn(false);
|
|
|
|
| 261 |
}
|
| 262 |
}, [pending, finish]);
|
| 263 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 264 |
const reset = useCallback(() => {
|
| 265 |
setError(null);
|
| 266 |
setPending(null);
|
| 267 |
setSigningIn(false);
|
|
|
|
| 268 |
}, []);
|
| 269 |
|
| 270 |
return {
|
| 271 |
signInWithGoogle,
|
| 272 |
-
signInWithApple: startAppleSignIn,
|
| 273 |
-
signInWithMicrosoft: startMicrosoftSignIn,
|
| 274 |
signingIn,
|
| 275 |
error,
|
| 276 |
reactivate,
|
|
|
|
|
|
|
| 277 |
reset,
|
| 278 |
/** Google sign-in failed inside GIS, before any token reached us. */
|
| 279 |
onGoogleError: useCallback(
|
|
|
|
| 1 |
import { useCallback, useState } from "react";
|
| 2 |
import type { CredentialResponse } from "@react-oauth/google";
|
| 3 |
|
| 4 |
+
import { googleLogin } from "../api/client";
|
| 5 |
+
import {
|
| 6 |
+
AUTH_PROVIDER_LABELS,
|
| 7 |
+
MIN_PASSWORD_LENGTH,
|
| 8 |
+
type AuthProvider,
|
| 9 |
+
} from "../api/types";
|
| 10 |
import { useAuth } from "./useAuth";
|
| 11 |
import { usePostLoginRedirect } from "./usePostLoginRedirect";
|
|
|
|
|
|
|
| 12 |
import { getErrorMessage } from "../contexts/ErrorModalContext";
|
| 13 |
|
| 14 |
/**
|
|
|
|
| 18 |
* login() → redirect with their own error handling, and only three of them
|
| 19 |
* understood the `account_deleted` response. Centralizing it means a new
|
| 20 |
* provider or a new failure mode is handled once.
|
| 21 |
+
*
|
| 22 |
+
* Google is the only social provider (Apple and Microsoft were removed), but
|
| 23 |
+
* the shape stays general: parseLoginError below is shared with the email +
|
| 24 |
+
* password flow, which is the other half of every error case here.
|
| 25 |
*/
|
| 26 |
|
| 27 |
/** What the UI should show; anything unmapped falls through to `message`. */
|
| 28 |
export type LoginErrorKind =
|
| 29 |
| "wrong_provider"
|
| 30 |
| "account_deleted"
|
| 31 |
+
// Email + password
|
| 32 |
+
| "email_already_registered"
|
| 33 |
+
| "invalid_credentials"
|
| 34 |
+
| "password_policy"
|
| 35 |
+
| "code_invalid"
|
| 36 |
+
| "code_expired"
|
| 37 |
+
| "code_burned"
|
| 38 |
+
| "resend_cooldown"
|
| 39 |
+
| "rate_limited"
|
| 40 |
| "generic";
|
| 41 |
|
| 42 |
export interface LoginError {
|
|
|
|
| 47 |
providerLabel?: string;
|
| 48 |
/** For "wrong_provider": that account is soft-deleted, so word it as reactivation. */
|
| 49 |
deleted?: boolean;
|
| 50 |
+
/** For "code_invalid": guesses left before the code is burned. */
|
| 51 |
+
attemptsRemaining?: number;
|
| 52 |
+
/** For 429s: seconds until the caller may retry. */
|
| 53 |
+
retryAfter?: number;
|
| 54 |
}
|
| 55 |
|
| 56 |
interface WrongProviderDetail {
|
|
|
|
| 60 |
deleted: boolean;
|
| 61 |
}
|
| 62 |
|
| 63 |
+
/**
|
| 64 |
+
* Maps a backend auth error onto what the UI should show.
|
| 65 |
+
*
|
| 66 |
+
* Exported because email/password auth shares it. A second copy would drift on
|
| 67 |
+
* the 409 shape and silently break the one-click provider switch, which is the
|
| 68 |
+
* whole reason the backend sends a machine-readable body.
|
| 69 |
+
*/
|
| 70 |
+
export function parseLoginError(err: unknown): LoginError {
|
| 71 |
+
const res = (err as {
|
| 72 |
+
response?: {
|
| 73 |
+
status?: number;
|
| 74 |
+
data?: { detail?: unknown };
|
| 75 |
+
headers?: Record<string, string>;
|
| 76 |
+
};
|
| 77 |
+
})?.response;
|
| 78 |
const status = res?.status;
|
| 79 |
const detail = res?.data?.detail;
|
| 80 |
+
const retryAfter = Number(res?.headers?.["retry-after"]) || undefined;
|
| 81 |
|
| 82 |
// 409: the email belongs to the other provider. The body names it so we can
|
| 83 |
// offer a one-click switch rather than making the user guess.
|
|
|
|
| 86 |
if (d.code === "wrong_auth_provider" && d.provider) {
|
| 87 |
// The backend always sends provider_label; the map is a defensive
|
| 88 |
// fallback that must name the right provider, never a two-way guess.
|
| 89 |
+
const label = d.provider_label ?? AUTH_PROVIDER_LABELS[d.provider] ?? d.provider;
|
| 90 |
+
const isEmail = d.provider === "email";
|
|
|
|
| 91 |
return {
|
| 92 |
kind: "wrong_provider",
|
| 93 |
provider: d.provider,
|
| 94 |
providerLabel: label,
|
| 95 |
deleted: Boolean(d.deleted),
|
| 96 |
message: d.deleted
|
| 97 |
+
? isEmail
|
| 98 |
+
? "Your account is registered with an email and password. Sign in below to reactivate it."
|
| 99 |
+
: `Your account is registered with ${label}. Sign in with ${label} to reactivate it.`
|
| 100 |
+
: isEmail
|
| 101 |
+
? "You already have an account with this email. Sign in with your email to continue."
|
| 102 |
+
: `You already have an account with ${label}. Sign in with ${label} to continue.`,
|
| 103 |
+
};
|
| 104 |
+
}
|
| 105 |
+
if (d.code === "email_already_registered") {
|
| 106 |
+
return {
|
| 107 |
+
kind: "email_already_registered",
|
| 108 |
+
message: "You already have an account with this email. Sign in instead.",
|
| 109 |
};
|
| 110 |
}
|
| 111 |
}
|
|
|
|
| 114 |
return { kind: "account_deleted", message: "This account was deleted." };
|
| 115 |
}
|
| 116 |
|
| 117 |
+
// ─── Email + password ───────────────────��──────────────────────────────
|
| 118 |
+
if (status === 401 && detail === "invalid_credentials") {
|
| 119 |
+
return {
|
| 120 |
+
kind: "invalid_credentials",
|
| 121 |
+
// Deliberately ambiguous, mirroring the backend: this is the same response
|
| 122 |
+
// for a wrong password and an address with no account.
|
| 123 |
+
message: "That email and password don't match.",
|
| 124 |
+
};
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
if (
|
| 128 |
+
status === 422 &&
|
| 129 |
+
typeof detail === "string" &&
|
| 130 |
+
(detail.startsWith("password_too_") || detail.startsWith("password_needs_"))
|
| 131 |
+
) {
|
| 132 |
+
const messages: Record<string, string> = {
|
| 133 |
+
password_too_short: `Password must be at least ${MIN_PASSWORD_LENGTH} characters.`,
|
| 134 |
+
password_too_long: "That password is too long.",
|
| 135 |
+
password_needs_uppercase: "Password must include a capital letter.",
|
| 136 |
+
password_needs_special: "Password must include a special character.",
|
| 137 |
+
};
|
| 138 |
+
return {
|
| 139 |
+
kind: "password_policy",
|
| 140 |
+
message: messages[detail] ?? "That password doesn't meet the requirements.",
|
| 141 |
+
};
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
if (status === 400 && detail && typeof detail === "object") {
|
| 145 |
+
const d = detail as { code?: string; attempts_remaining?: number };
|
| 146 |
+
if (d.code === "code_invalid") {
|
| 147 |
+
const left = d.attempts_remaining;
|
| 148 |
+
return {
|
| 149 |
+
kind: "code_invalid",
|
| 150 |
+
attemptsRemaining: left,
|
| 151 |
+
message:
|
| 152 |
+
left === undefined
|
| 153 |
+
? "That code isn't right."
|
| 154 |
+
: `That code isn't right. ${left} attempt${left === 1 ? "" : "s"} left.`,
|
| 155 |
+
};
|
| 156 |
+
}
|
| 157 |
+
}
|
| 158 |
+
|
| 159 |
+
if (status === 400 && detail === "code_invalid") {
|
| 160 |
+
return { kind: "code_invalid", message: "That code isn't right." };
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
if (status === 400 && detail === "code_expired") {
|
| 164 |
+
return { kind: "code_expired", message: "That code has expired. Request a new one." };
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
if (status === 429 && detail === "code_attempts_exceeded") {
|
| 168 |
return {
|
| 169 |
+
kind: "code_burned",
|
| 170 |
+
message: "Too many incorrect codes. Start again to get a new one.",
|
|
|
|
| 171 |
};
|
| 172 |
}
|
| 173 |
|
| 174 |
+
if (status === 429 && detail === "resend_too_soon") {
|
| 175 |
return {
|
| 176 |
+
kind: "resend_cooldown",
|
| 177 |
+
retryAfter,
|
| 178 |
+
message: `Please wait ${retryAfter ?? 60}s before requesting another code.`,
|
| 179 |
+
};
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
if (status === 429 && detail === "too_many_attempts") {
|
| 183 |
+
const mins = retryAfter ? Math.max(1, Math.ceil(retryAfter / 60)) : null;
|
| 184 |
+
return {
|
| 185 |
+
kind: "rate_limited",
|
| 186 |
+
retryAfter,
|
| 187 |
+
message: mins
|
| 188 |
+
? `Too many attempts. Try again in ${mins} minute${mins === 1 ? "" : "s"}.`
|
| 189 |
+
: "Too many attempts. Please try again later.",
|
| 190 |
+
};
|
| 191 |
+
}
|
| 192 |
+
|
| 193 |
+
if (status === 400 && detail === "no_pending_registration") {
|
| 194 |
+
return {
|
| 195 |
+
kind: "generic",
|
| 196 |
+
message: "That registration expired. Please start again.",
|
| 197 |
+
};
|
| 198 |
+
}
|
| 199 |
+
|
| 200 |
+
if (status === 502 && detail === "email_send_failed") {
|
| 201 |
+
return {
|
| 202 |
+
kind: "generic",
|
| 203 |
+
message: "We couldn't send the email just now. Please try again in a moment.",
|
| 204 |
};
|
| 205 |
}
|
| 206 |
|
|
|
|
| 232 |
const redirectAfterLogin = usePostLoginRedirect();
|
| 233 |
|
| 234 |
const [signingIn, setSigningIn] = useState(false);
|
| 235 |
+
/** True while the in-flight request is a reactivation rather than a first
|
| 236 |
+
* sign-in, so the UI can say which one it is. */
|
| 237 |
+
const [reactivating, setReactivating] = useState(false);
|
| 238 |
const [error, setError] = useState<LoginError | null>(null);
|
| 239 |
/** Held so the account-deleted prompt can retry the same credential. */
|
| 240 |
+
const [pending, setPending] = useState<{ credential: string } | null>(null);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 241 |
|
| 242 |
const finish = useCallback(
|
| 243 |
async (token: string, user: Parameters<typeof login>[1]) => {
|
|
|
|
| 263 |
} catch (err) {
|
| 264 |
const parsed = parseLoginError(err);
|
| 265 |
if (parsed.kind === "account_deleted") {
|
| 266 |
+
setPending({ credential: response.credential });
|
| 267 |
}
|
| 268 |
setError(parsed);
|
| 269 |
setSigningIn(false);
|
|
|
|
| 272 |
[finish]
|
| 273 |
);
|
| 274 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 275 |
/** Confirm reactivation of a soft-deleted account, reusing the held credential. */
|
| 276 |
const reactivate = useCallback(async () => {
|
| 277 |
if (!pending) return;
|
| 278 |
setSigningIn(true);
|
| 279 |
+
setReactivating(true);
|
| 280 |
setError(null);
|
| 281 |
try {
|
| 282 |
+
const res = await googleLogin(pending.credential, true);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 283 |
setPending(null);
|
| 284 |
await finish(res.data.access_token, res.data.user);
|
| 285 |
} catch (err) {
|
|
|
|
| 288 |
message: getErrorMessage(err, "Failed to reactivate account."),
|
| 289 |
});
|
| 290 |
setSigningIn(false);
|
| 291 |
+
setReactivating(false);
|
| 292 |
}
|
| 293 |
}, [pending, finish]);
|
| 294 |
|
| 295 |
+
/** Dismiss the current error without clearing the in-flight sign-in state. */
|
| 296 |
+
const dismissError = useCallback(() => {
|
| 297 |
+
setError(null);
|
| 298 |
+
setPending(null);
|
| 299 |
+
setReactivating(false);
|
| 300 |
+
}, []);
|
| 301 |
+
|
| 302 |
const reset = useCallback(() => {
|
| 303 |
setError(null);
|
| 304 |
setPending(null);
|
| 305 |
setSigningIn(false);
|
| 306 |
+
setReactivating(false);
|
| 307 |
}, []);
|
| 308 |
|
| 309 |
return {
|
| 310 |
signInWithGoogle,
|
|
|
|
|
|
|
| 311 |
signingIn,
|
| 312 |
error,
|
| 313 |
reactivate,
|
| 314 |
+
reactivating,
|
| 315 |
+
dismissError,
|
| 316 |
reset,
|
| 317 |
/** Google sign-in failed inside GIS, before any token reached us. */
|
| 318 |
onGoogleError: useCallback(
|
frontend/src/lib/appleSignIn.ts
DELETED
|
@@ -1,116 +0,0 @@
|
|
| 1 |
-
/**
|
| 2 |
-
* Sign in with Apple, via Apple's official JS SDK loaded on demand.
|
| 3 |
-
*
|
| 4 |
-
* We use the popup flow so the browser hands us an identity token in-page,
|
| 5 |
-
* exactly like Google Identity Services gives us a credential — no server
|
| 6 |
-
* redirect, and the same shape of call site for both providers.
|
| 7 |
-
*
|
| 8 |
-
* Apple returns the user's NAME only on the very first authorization, in the
|
| 9 |
-
* response's `user` field rather than inside the token. Callers must forward it
|
| 10 |
-
* to the backend on that first sign-in or the name is lost forever.
|
| 11 |
-
*/
|
| 12 |
-
|
| 13 |
-
const APPLE_SDK_URL =
|
| 14 |
-
"https://appleid.cdn-apple.com/appleauth/static/jsapi/appleid/1/en_US/appleid.auth.js";
|
| 15 |
-
|
| 16 |
-
export interface AppleSignInResult {
|
| 17 |
-
identityToken: string;
|
| 18 |
-
/** Present only on the user's first authorization for this Services ID. */
|
| 19 |
-
user?: { name?: { firstName?: string; lastName?: string } };
|
| 20 |
-
}
|
| 21 |
-
|
| 22 |
-
interface AppleAuthResponse {
|
| 23 |
-
authorization?: { id_token?: string };
|
| 24 |
-
user?: { name?: { firstName?: string; lastName?: string } };
|
| 25 |
-
}
|
| 26 |
-
|
| 27 |
-
declare global {
|
| 28 |
-
interface Window {
|
| 29 |
-
AppleID?: {
|
| 30 |
-
auth: {
|
| 31 |
-
init: (config: Record<string, unknown>) => void;
|
| 32 |
-
signIn: () => Promise<AppleAuthResponse>;
|
| 33 |
-
};
|
| 34 |
-
};
|
| 35 |
-
}
|
| 36 |
-
}
|
| 37 |
-
|
| 38 |
-
/** Raised when the user closes the Apple popup — not a real failure. */
|
| 39 |
-
export class AppleSignInCancelled extends Error {
|
| 40 |
-
constructor() {
|
| 41 |
-
super("Apple sign-in cancelled");
|
| 42 |
-
this.name = "AppleSignInCancelled";
|
| 43 |
-
}
|
| 44 |
-
}
|
| 45 |
-
|
| 46 |
-
let sdkPromise: Promise<void> | null = null;
|
| 47 |
-
|
| 48 |
-
function loadAppleSdk(): Promise<void> {
|
| 49 |
-
if (window.AppleID) return Promise.resolve();
|
| 50 |
-
// Cache the in-flight load so two buttons don't inject two script tags.
|
| 51 |
-
if (sdkPromise) return sdkPromise;
|
| 52 |
-
|
| 53 |
-
sdkPromise = new Promise<void>((resolve, reject) => {
|
| 54 |
-
const existing = document.querySelector<HTMLScriptElement>(
|
| 55 |
-
`script[src="${APPLE_SDK_URL}"]`
|
| 56 |
-
);
|
| 57 |
-
if (existing) {
|
| 58 |
-
existing.addEventListener("load", () => resolve());
|
| 59 |
-
existing.addEventListener("error", () => reject(new Error("Apple SDK failed to load")));
|
| 60 |
-
return;
|
| 61 |
-
}
|
| 62 |
-
const script = document.createElement("script");
|
| 63 |
-
script.src = APPLE_SDK_URL;
|
| 64 |
-
script.async = true;
|
| 65 |
-
script.onload = () => resolve();
|
| 66 |
-
script.onerror = () => {
|
| 67 |
-
sdkPromise = null; // allow a retry on the next click
|
| 68 |
-
reject(new Error("Apple SDK failed to load"));
|
| 69 |
-
};
|
| 70 |
-
document.head.appendChild(script);
|
| 71 |
-
});
|
| 72 |
-
return sdkPromise;
|
| 73 |
-
}
|
| 74 |
-
|
| 75 |
-
export function isAppleSignInConfigured(): boolean {
|
| 76 |
-
return Boolean(import.meta.env.VITE_APPLE_CLIENT_ID);
|
| 77 |
-
}
|
| 78 |
-
|
| 79 |
-
/**
|
| 80 |
-
* Open Apple's sign-in popup and resolve with the identity token.
|
| 81 |
-
*
|
| 82 |
-
* Throws AppleSignInCancelled if the user dismissed the popup, so callers can
|
| 83 |
-
* stay silent instead of showing an error for a deliberate action.
|
| 84 |
-
*/
|
| 85 |
-
export async function signInWithApple(): Promise<AppleSignInResult> {
|
| 86 |
-
const clientId = import.meta.env.VITE_APPLE_CLIENT_ID;
|
| 87 |
-
if (!clientId) throw new Error("Apple sign-in is not configured");
|
| 88 |
-
|
| 89 |
-
await loadAppleSdk();
|
| 90 |
-
if (!window.AppleID) throw new Error("Apple SDK failed to load");
|
| 91 |
-
|
| 92 |
-
window.AppleID.auth.init({
|
| 93 |
-
clientId,
|
| 94 |
-
scope: "name email",
|
| 95 |
-
// Apple validates this against the Services ID's registered Return URLs;
|
| 96 |
-
// an unregistered origin is rejected outright.
|
| 97 |
-
redirectURI: window.location.origin,
|
| 98 |
-
usePopup: true,
|
| 99 |
-
});
|
| 100 |
-
|
| 101 |
-
let response: AppleAuthResponse;
|
| 102 |
-
try {
|
| 103 |
-
response = await window.AppleID.auth.signIn();
|
| 104 |
-
} catch (err: unknown) {
|
| 105 |
-
const code = (err as { error?: string })?.error;
|
| 106 |
-
if (code === "popup_closed_by_user" || code === "user_cancelled_authorize") {
|
| 107 |
-
throw new AppleSignInCancelled();
|
| 108 |
-
}
|
| 109 |
-
throw new Error("Apple sign-in failed. Please try again.");
|
| 110 |
-
}
|
| 111 |
-
|
| 112 |
-
const identityToken = response?.authorization?.id_token;
|
| 113 |
-
if (!identityToken) throw new Error("Apple sign-in returned no identity token");
|
| 114 |
-
|
| 115 |
-
return { identityToken, user: response.user };
|
| 116 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
frontend/src/lib/microsoftSignIn.ts
DELETED
|
@@ -1,93 +0,0 @@
|
|
| 1 |
-
/**
|
| 2 |
-
* Sign in with Microsoft, via MSAL loaded on demand.
|
| 3 |
-
*
|
| 4 |
-
* Uses the popup flow so the browser hands us an ID token in-page, exactly like
|
| 5 |
-
* Google Identity Services gives us a credential and Apple gives us an identity
|
| 6 |
-
* token — same shape of call site for all three providers.
|
| 7 |
-
*
|
| 8 |
-
* MSAL is ~40KB gzipped, so it is imported dynamically inside the click handler
|
| 9 |
-
* rather than at module scope: visitors who never sign in never download it.
|
| 10 |
-
*/
|
| 11 |
-
import type { PublicClientApplication } from "@azure/msal-browser";
|
| 12 |
-
|
| 13 |
-
export interface MicrosoftSignInResult {
|
| 14 |
-
idToken: string;
|
| 15 |
-
}
|
| 16 |
-
|
| 17 |
-
/** Raised when the user closes the MSAL popup — not a real failure. */
|
| 18 |
-
export class MicrosoftSignInCancelled extends Error {
|
| 19 |
-
constructor() {
|
| 20 |
-
super("Microsoft sign-in cancelled");
|
| 21 |
-
this.name = "MicrosoftSignInCancelled";
|
| 22 |
-
}
|
| 23 |
-
}
|
| 24 |
-
|
| 25 |
-
// MSAL throws these when the user dismisses or blocks the popup.
|
| 26 |
-
const CANCEL_CODES = new Set([
|
| 27 |
-
"user_cancelled",
|
| 28 |
-
"popup_window_error",
|
| 29 |
-
"empty_window_error",
|
| 30 |
-
]);
|
| 31 |
-
|
| 32 |
-
let msalPromise: Promise<PublicClientApplication> | null = null;
|
| 33 |
-
|
| 34 |
-
async function getMsal(): Promise<PublicClientApplication> {
|
| 35 |
-
const clientId = import.meta.env.VITE_MICROSOFT_CLIENT_ID;
|
| 36 |
-
if (!clientId) throw new Error("Microsoft sign-in is not configured");
|
| 37 |
-
|
| 38 |
-
// Cache the initialized instance so a second click doesn't re-download or
|
| 39 |
-
// re-initialize; MSAL requires initialize() before any auth call in v3+.
|
| 40 |
-
if (!msalPromise) {
|
| 41 |
-
msalPromise = (async () => {
|
| 42 |
-
const { PublicClientApplication: PCA } = await import("@azure/msal-browser");
|
| 43 |
-
const instance = new PCA({
|
| 44 |
-
auth: {
|
| 45 |
-
clientId,
|
| 46 |
-
// "common" accepts personal Microsoft accounts (outlook.com,
|
| 47 |
-
// hotmail.com, live.com) and any organization's Microsoft 365 tenant.
|
| 48 |
-
authority: "https://login.microsoftonline.com/common",
|
| 49 |
-
redirectUri: window.location.origin,
|
| 50 |
-
},
|
| 51 |
-
cache: {
|
| 52 |
-
// sessionStorage, not localStorage: MSAL's own account cache should
|
| 53 |
-
// not outlive the tab or sit alongside our long-lived b2v_token.
|
| 54 |
-
cacheLocation: "sessionStorage",
|
| 55 |
-
},
|
| 56 |
-
});
|
| 57 |
-
await instance.initialize();
|
| 58 |
-
return instance;
|
| 59 |
-
})().catch((err) => {
|
| 60 |
-
msalPromise = null; // allow a retry on the next click
|
| 61 |
-
throw err;
|
| 62 |
-
});
|
| 63 |
-
}
|
| 64 |
-
return msalPromise;
|
| 65 |
-
}
|
| 66 |
-
|
| 67 |
-
export function isMicrosoftSignInConfigured(): boolean {
|
| 68 |
-
return Boolean(import.meta.env.VITE_MICROSOFT_CLIENT_ID);
|
| 69 |
-
}
|
| 70 |
-
|
| 71 |
-
/**
|
| 72 |
-
* Open Microsoft's sign-in popup and resolve with the ID token.
|
| 73 |
-
*
|
| 74 |
-
* Throws MicrosoftSignInCancelled if the user dismissed the popup, so callers
|
| 75 |
-
* can stay silent instead of showing an error for a deliberate action.
|
| 76 |
-
*/
|
| 77 |
-
export async function signInWithMicrosoft(): Promise<MicrosoftSignInResult> {
|
| 78 |
-
const msal = await getMsal();
|
| 79 |
-
|
| 80 |
-
let result;
|
| 81 |
-
try {
|
| 82 |
-
result = await msal.loginPopup({ scopes: ["openid", "profile", "email"] });
|
| 83 |
-
} catch (err: unknown) {
|
| 84 |
-
const code = (err as { errorCode?: string })?.errorCode;
|
| 85 |
-
if (code && CANCEL_CODES.has(code)) {
|
| 86 |
-
throw new MicrosoftSignInCancelled();
|
| 87 |
-
}
|
| 88 |
-
throw new Error("Microsoft sign-in failed. Please try again.");
|
| 89 |
-
}
|
| 90 |
-
|
| 91 |
-
if (!result?.idToken) throw new Error("Microsoft sign-in returned no ID token");
|
| 92 |
-
return { idToken: result.idToken };
|
| 93 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
frontend/src/pages/AuthPage.tsx
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { useEffect } from "react";
|
| 2 |
+
import { useLocation, useNavigate } from "react-router-dom";
|
| 3 |
+
|
| 4 |
+
import PublicHeader from "../components/public/PublicHeader";
|
| 5 |
+
import AuthFlow from "../components/auth/AuthFlow";
|
| 6 |
+
import { useAuth } from "../hooks/useAuth";
|
| 7 |
+
|
| 8 |
+
interface AuthPageProps {
|
| 9 |
+
/**
|
| 10 |
+
* Which route rendered this page. Kept so the two paths stay distinguishable
|
| 11 |
+
* (and linkable), but it no longer forces a form: both open on sign-up, and
|
| 12 |
+
* the toggle inside the flow switches to sign-in.
|
| 13 |
+
*/
|
| 14 |
+
mode?: "signin" | "signup";
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
/**
|
| 18 |
+
* Full-page sign-in / sign-up, with the site header.
|
| 19 |
+
*
|
| 20 |
+
* Renders the same AuthFlow as the modal, so every stage — password, OTP,
|
| 21 |
+
* forgot-password, the reactivation prompt — behaves identically on both
|
| 22 |
+
* surfaces. Plain CTAs (Landing, Pricing, PdfLanding) route here; the in-place
|
| 23 |
+
* tool gates still use the modal, because navigating away would discard the
|
| 24 |
+
* half-filled form they are gating.
|
| 25 |
+
*/
|
| 26 |
+
export default function AuthPage(_props: AuthPageProps) {
|
| 27 |
+
const { user, loading } = useAuth();
|
| 28 |
+
const navigate = useNavigate();
|
| 29 |
+
const location = useLocation();
|
| 30 |
+
|
| 31 |
+
// Someone already signed in has no business here — send them on rather than
|
| 32 |
+
// showing a form that would immediately bounce them.
|
| 33 |
+
useEffect(() => {
|
| 34 |
+
if (!loading && user) navigate("/dashboard", { replace: true });
|
| 35 |
+
}, [user, loading, navigate]);
|
| 36 |
+
|
| 37 |
+
return (
|
| 38 |
+
<div className="min-h-screen bg-white">
|
| 39 |
+
<PublicHeader />
|
| 40 |
+
|
| 41 |
+
{/* Centred in the viewport minus the header, and borderless: on a full
|
| 42 |
+
page the card outline reads as a modal that forgot to close. */}
|
| 43 |
+
<main className="flex min-h-[calc(100vh-4rem)] items-center justify-center px-4 py-12">
|
| 44 |
+
<div className="w-full max-w-lg rounded-2xl bg-white px-6 py-8 sm:px-10">
|
| 45 |
+
{/* No `mode` or copy override: both routes fall through to AuthFlow's
|
| 46 |
+
signup default and its mode-derived DEFAULT_COPY, so /signin opens
|
| 47 |
+
on the sign-up form too. Returning users take the "Already have an
|
| 48 |
+
account? Sign in" toggle inside the flow. */}
|
| 49 |
+
<AuthFlow key={location.pathname} variant="page" />
|
| 50 |
+
</div>
|
| 51 |
+
</main>
|
| 52 |
+
</div>
|
| 53 |
+
);
|
| 54 |
+
}
|
frontend/src/pages/FreeTemplatesPage.tsx
CHANGED
|
@@ -4,7 +4,6 @@ import PublicHeader from "../components/public/PublicHeader";
|
|
| 4 |
import PublicFooter from "../components/public/PublicFooter";
|
| 5 |
import Seo from "../components/seo/Seo";
|
| 6 |
import { useAuth } from "../hooks/useAuth";
|
| 7 |
-
import { useLoginModal } from "../contexts/LoginModalContext";
|
| 8 |
import { useNavigate } from "react-router-dom";
|
| 9 |
import { BACKEND_URL } from "../api/client";
|
| 10 |
import { templateProfiles } from "../content/marketingBase";
|
|
@@ -66,7 +65,7 @@ const TEMPLATE_DISPLAY: Record<string, string> = {
|
|
| 66 |
};
|
| 67 |
|
| 68 |
function DownloadModal({ slug, onClose, onDownloadStarted }: ModalProps) {
|
| 69 |
-
const
|
| 70 |
const [error, setError] = useState<string | null>(null);
|
| 71 |
|
| 72 |
const displayName = slug ? (TEMPLATE_DISPLAY[slug] ?? slug) : "";
|
|
@@ -78,7 +77,7 @@ function DownloadModal({ slug, onClose, onDownloadStarted }: ModalProps) {
|
|
| 78 |
localStorage.setItem(PENDING_DOWNLOAD_KEY, JSON.stringify(slug));
|
| 79 |
onDownloadStarted(slug);
|
| 80 |
onClose();
|
| 81 |
-
|
| 82 |
};
|
| 83 |
|
| 84 |
if (!slug) return null;
|
|
|
|
| 4 |
import PublicFooter from "../components/public/PublicFooter";
|
| 5 |
import Seo from "../components/seo/Seo";
|
| 6 |
import { useAuth } from "../hooks/useAuth";
|
|
|
|
| 7 |
import { useNavigate } from "react-router-dom";
|
| 8 |
import { BACKEND_URL } from "../api/client";
|
| 9 |
import { templateProfiles } from "../content/marketingBase";
|
|
|
|
| 65 |
};
|
| 66 |
|
| 67 |
function DownloadModal({ slug, onClose, onDownloadStarted }: ModalProps) {
|
| 68 |
+
const navigate = useNavigate();
|
| 69 |
const [error, setError] = useState<string | null>(null);
|
| 70 |
|
| 71 |
const displayName = slug ? (TEMPLATE_DISPLAY[slug] ?? slug) : "";
|
|
|
|
| 77 |
localStorage.setItem(PENDING_DOWNLOAD_KEY, JSON.stringify(slug));
|
| 78 |
onDownloadStarted(slug);
|
| 79 |
onClose();
|
| 80 |
+
navigate("/signin");
|
| 81 |
};
|
| 82 |
|
| 83 |
if (!slug) return null;
|
frontend/src/pages/Landing.tsx
CHANGED
|
@@ -2,7 +2,6 @@ import { useState, useEffect, useRef, useMemo } from "react";
|
|
| 2 |
import { Link, useNavigate, useSearchParams } from "react-router-dom";
|
| 3 |
import { useAuth } from "../hooks/useAuth";
|
| 4 |
import { useScrollReveal } from "../hooks/useScrollReveal";
|
| 5 |
-
import { useLoginModal } from "../contexts/LoginModalContext";
|
| 6 |
import FullTemplateShowcase from "../components/FullTemplateShowcase";
|
| 7 |
import CoverflowCarousel, { type CoverflowTemplate, type CoverflowOrientation } from "../components/CoverflowCarousel";
|
| 8 |
import OrientationToggle from "../components/OrientationToggle";
|
|
@@ -456,7 +455,6 @@ function LandingDemoSection({ demos }: { demos: DemoVideo[] }) {
|
|
| 456 |
export default function Landing() {
|
| 457 |
const { user } = useAuth();
|
| 458 |
const navigate = useNavigate();
|
| 459 |
-
const { openLogin } = useLoginModal();
|
| 460 |
const [searchParams] = useSearchParams();
|
| 461 |
const [demos, setDemos] = useState<DemoVideo[]>(INITIAL_DEMOS);
|
| 462 |
const [navOpen, setNavOpen] = useState(false);
|
|
@@ -543,8 +541,8 @@ export default function Landing() {
|
|
| 543 |
// Auto-open sign-in when redirected here with ?signin=1
|
| 544 |
useEffect(() => {
|
| 545 |
if (searchParams.get("signin") !== "1") return;
|
| 546 |
-
|
| 547 |
-
}, [searchParams,
|
| 548 |
|
| 549 |
// Auto-fetch OG images for demos that don't have one; fall back to YouTube thumbnail
|
| 550 |
useEffect(() => {
|
|
@@ -574,7 +572,7 @@ export default function Landing() {
|
|
| 574 |
|
| 575 |
// Every sign-in CTA opens the shared login modal, which owns provider choice,
|
| 576 |
// error recovery, and the in-app-browser escape flow.
|
| 577 |
-
const handleGenerateClick = () =>
|
| 578 |
|
| 579 |
// "Explore the MCP connector" CTA: go straight there if signed in, otherwise
|
| 580 |
// sign in and route to /mcp-connector once authenticated.
|
|
@@ -584,7 +582,7 @@ export default function Landing() {
|
|
| 584 |
return;
|
| 585 |
}
|
| 586 |
localStorage.setItem("b2v_pending_mcp", "1");
|
| 587 |
-
|
| 588 |
};
|
| 589 |
|
| 590 |
// "Try AI presenters" CTA: avatars are configured per-project, there's no
|
|
@@ -596,7 +594,7 @@ export default function Landing() {
|
|
| 596 |
navigate("/dashboard");
|
| 597 |
return;
|
| 598 |
}
|
| 599 |
-
|
| 600 |
};
|
| 601 |
|
| 602 |
return (
|
|
@@ -1196,7 +1194,7 @@ export default function Landing() {
|
|
| 1196 |
<div className="flex flex-col items-center gap-3 px-8 py-6 rounded-2xl border border-white/70" style={{ background: "rgba(255,255,255,0.55)", backdropFilter: "blur(20px)", WebkitBackdropFilter: "blur(20px)", boxShadow: "0 4px 24px rgba(0,0,0,0.06), inset 0 1px 0 rgba(255,255,255,0.90)" }}>
|
| 1197 |
<button
|
| 1198 |
type="button"
|
| 1199 |
-
onClick={() =>
|
| 1200 |
className="inline-flex h-10 items-center justify-center rounded-full bg-purple-600 px-8 text-sm font-medium text-white transition hover:bg-purple-700"
|
| 1201 |
>
|
| 1202 |
Get started free
|
|
|
|
| 2 |
import { Link, useNavigate, useSearchParams } from "react-router-dom";
|
| 3 |
import { useAuth } from "../hooks/useAuth";
|
| 4 |
import { useScrollReveal } from "../hooks/useScrollReveal";
|
|
|
|
| 5 |
import FullTemplateShowcase from "../components/FullTemplateShowcase";
|
| 6 |
import CoverflowCarousel, { type CoverflowTemplate, type CoverflowOrientation } from "../components/CoverflowCarousel";
|
| 7 |
import OrientationToggle from "../components/OrientationToggle";
|
|
|
|
| 455 |
export default function Landing() {
|
| 456 |
const { user } = useAuth();
|
| 457 |
const navigate = useNavigate();
|
|
|
|
| 458 |
const [searchParams] = useSearchParams();
|
| 459 |
const [demos, setDemos] = useState<DemoVideo[]>(INITIAL_DEMOS);
|
| 460 |
const [navOpen, setNavOpen] = useState(false);
|
|
|
|
| 541 |
// Auto-open sign-in when redirected here with ?signin=1
|
| 542 |
useEffect(() => {
|
| 543 |
if (searchParams.get("signin") !== "1") return;
|
| 544 |
+
navigate("/signin");
|
| 545 |
+
}, [searchParams, navigate]);
|
| 546 |
|
| 547 |
// Auto-fetch OG images for demos that don't have one; fall back to YouTube thumbnail
|
| 548 |
useEffect(() => {
|
|
|
|
| 572 |
|
| 573 |
// Every sign-in CTA opens the shared login modal, which owns provider choice,
|
| 574 |
// error recovery, and the in-app-browser escape flow.
|
| 575 |
+
const handleGenerateClick = () => navigate("/signin");
|
| 576 |
|
| 577 |
// "Explore the MCP connector" CTA: go straight there if signed in, otherwise
|
| 578 |
// sign in and route to /mcp-connector once authenticated.
|
|
|
|
| 582 |
return;
|
| 583 |
}
|
| 584 |
localStorage.setItem("b2v_pending_mcp", "1");
|
| 585 |
+
navigate("/signin");
|
| 586 |
};
|
| 587 |
|
| 588 |
// "Try AI presenters" CTA: avatars are configured per-project, there's no
|
|
|
|
| 594 |
navigate("/dashboard");
|
| 595 |
return;
|
| 596 |
}
|
| 597 |
+
navigate("/signin");
|
| 598 |
};
|
| 599 |
|
| 600 |
return (
|
|
|
|
| 1194 |
<div className="flex flex-col items-center gap-3 px-8 py-6 rounded-2xl border border-white/70" style={{ background: "rgba(255,255,255,0.55)", backdropFilter: "blur(20px)", WebkitBackdropFilter: "blur(20px)", boxShadow: "0 4px 24px rgba(0,0,0,0.06), inset 0 1px 0 rgba(255,255,255,0.90)" }}>
|
| 1195 |
<button
|
| 1196 |
type="button"
|
| 1197 |
+
onClick={() => navigate("/signin")}
|
| 1198 |
className="inline-flex h-10 items-center justify-center rounded-full bg-purple-600 px-8 text-sm font-medium text-white transition hover:bg-purple-700"
|
| 1199 |
>
|
| 1200 |
Get started free
|
frontend/src/pages/PdfLanding.tsx
CHANGED
|
@@ -2,7 +2,6 @@ import { useEffect, useMemo, useState, useRef } from "react";
|
|
| 2 |
import { Link, useNavigate, useSearchParams } from "react-router-dom";
|
| 3 |
import { useAuth } from "../hooks/useAuth";
|
| 4 |
import { useScrollReveal } from "../hooks/useScrollReveal";
|
| 5 |
-
import { useLoginModal } from "../contexts/LoginModalContext";
|
| 6 |
import { getBrand, markPdfOrigin, setSessionBrand } from "../brand/brand";
|
| 7 |
import Seo from "../components/seo/Seo";
|
| 8 |
import { homepageSchema } from "../seo/schema";
|
|
@@ -183,7 +182,6 @@ export default function PdfLanding() {
|
|
| 183 |
const { user } = useAuth();
|
| 184 |
const navigate = useNavigate();
|
| 185 |
const [searchParams] = useSearchParams();
|
| 186 |
-
const { openLogin } = useLoginModal();
|
| 187 |
|
| 188 |
const [navOpen, setNavOpen] = useState(false);
|
| 189 |
const [accountDeletedOpen, setAccountDeletedOpen] = useState(false);
|
|
@@ -269,7 +267,7 @@ export default function PdfLanding() {
|
|
| 269 |
);
|
| 270 |
|
| 271 |
// The shared login modal owns provider choice and the in-app-browser escape.
|
| 272 |
-
const handleGenerateClick = () =>
|
| 273 |
|
| 274 |
/** Hero CTA: signed-in users go straight to the upload form, others sign in first. */
|
| 275 |
const handleHeroStart = () => {
|
|
@@ -283,7 +281,7 @@ export default function PdfLanding() {
|
|
| 283 |
const authButton = (width = "300") => (
|
| 284 |
<button
|
| 285 |
type="button"
|
| 286 |
-
onClick={() =>
|
| 287 |
style={{ width: `${width}px`, maxWidth: "100%" }}
|
| 288 |
className="inline-flex h-11 items-center justify-center rounded-full bg-purple-600 px-6 text-sm font-medium text-white transition hover:bg-purple-700"
|
| 289 |
>
|
|
|
|
| 2 |
import { Link, useNavigate, useSearchParams } from "react-router-dom";
|
| 3 |
import { useAuth } from "../hooks/useAuth";
|
| 4 |
import { useScrollReveal } from "../hooks/useScrollReveal";
|
|
|
|
| 5 |
import { getBrand, markPdfOrigin, setSessionBrand } from "../brand/brand";
|
| 6 |
import Seo from "../components/seo/Seo";
|
| 7 |
import { homepageSchema } from "../seo/schema";
|
|
|
|
| 182 |
const { user } = useAuth();
|
| 183 |
const navigate = useNavigate();
|
| 184 |
const [searchParams] = useSearchParams();
|
|
|
|
| 185 |
|
| 186 |
const [navOpen, setNavOpen] = useState(false);
|
| 187 |
const [accountDeletedOpen, setAccountDeletedOpen] = useState(false);
|
|
|
|
| 267 |
);
|
| 268 |
|
| 269 |
// The shared login modal owns provider choice and the in-app-browser escape.
|
| 270 |
+
const handleGenerateClick = () => navigate("/signin");
|
| 271 |
|
| 272 |
/** Hero CTA: signed-in users go straight to the upload form, others sign in first. */
|
| 273 |
const handleHeroStart = () => {
|
|
|
|
| 281 |
const authButton = (width = "300") => (
|
| 282 |
<button
|
| 283 |
type="button"
|
| 284 |
+
onClick={() => navigate("/signin")}
|
| 285 |
style={{ width: `${width}px`, maxWidth: "100%" }}
|
| 286 |
className="inline-flex h-11 items-center justify-center rounded-full bg-purple-600 px-6 text-sm font-medium text-white transition hover:bg-purple-700"
|
| 287 |
>
|
frontend/src/pages/Pricing.tsx
CHANGED
|
@@ -12,7 +12,6 @@ import {
|
|
| 12 |
import type { BillingCycle, PlanKey } from "../api/billing";
|
| 13 |
import { useAuth } from "../hooks/useAuth";
|
| 14 |
import { useErrorModal, getErrorMessage } from "../contexts/ErrorModalContext";
|
| 15 |
-
import { useLoginModal } from "../contexts/LoginModalContext";
|
| 16 |
import PublicHeader from "../components/public/PublicHeader";
|
| 17 |
import PublicFooter from "../components/public/PublicFooter";
|
| 18 |
import Seo from "../components/seo/Seo";
|
|
@@ -53,7 +52,6 @@ export default function Pricing() {
|
|
| 53 |
const navigate = useNavigate();
|
| 54 |
const [searchParams] = useSearchParams();
|
| 55 |
const { showError } = useErrorModal();
|
| 56 |
-
const { openLogin } = useLoginModal();
|
| 57 |
const [checkoutLoading, setCheckoutLoading] = useState(false);
|
| 58 |
const [billingCycle, setBillingCycle] = useState<BillingCycle>("monthly");
|
| 59 |
const [subscription, setSubscription] = useState<SubscriptionDetail | null>(null);
|
|
@@ -363,7 +361,7 @@ export default function Pricing() {
|
|
| 363 |
<div className="flex justify-center">
|
| 364 |
<button
|
| 365 |
type="button"
|
| 366 |
-
onClick={() =>
|
| 367 |
className="inline-flex h-10 items-center justify-center rounded-full bg-purple-600 px-6 text-sm font-medium text-white transition hover:bg-purple-700"
|
| 368 |
style={{ width: "190px", maxWidth: "100%" }}
|
| 369 |
>
|
|
@@ -393,7 +391,7 @@ export default function Pricing() {
|
|
| 393 |
<div className="flex justify-center">
|
| 394 |
<button
|
| 395 |
type="button"
|
| 396 |
-
onClick={() =>
|
| 397 |
className="inline-flex h-10 items-center justify-center rounded-full bg-purple-600 px-6 text-sm font-medium text-white transition hover:bg-purple-700"
|
| 398 |
style={{ width: "190px", maxWidth: "100%" }}
|
| 399 |
>
|
|
@@ -474,7 +472,7 @@ export default function Pricing() {
|
|
| 474 |
<div className="flex justify-center">
|
| 475 |
<button
|
| 476 |
type="button"
|
| 477 |
-
onClick={() =>
|
| 478 |
className="inline-flex h-10 items-center justify-center rounded-full bg-purple-600 px-6 text-sm font-medium text-white transition hover:bg-purple-700"
|
| 479 |
style={{ width: "190px", maxWidth: "100%" }}
|
| 480 |
>
|
|
@@ -571,7 +569,7 @@ export default function Pricing() {
|
|
| 571 |
<div className="flex justify-center">
|
| 572 |
<button
|
| 573 |
type="button"
|
| 574 |
-
onClick={() =>
|
| 575 |
className="inline-flex h-10 items-center justify-center rounded-full bg-purple-600 px-6 text-sm font-medium text-white transition hover:bg-purple-700"
|
| 576 |
style={{ width: "190px", maxWidth: "100%" }}
|
| 577 |
>
|
|
@@ -682,7 +680,7 @@ export default function Pricing() {
|
|
| 682 |
<div className="flex justify-center">
|
| 683 |
<button
|
| 684 |
type="button"
|
| 685 |
-
onClick={() =>
|
| 686 |
className="inline-flex h-10 items-center justify-center rounded-full bg-purple-600 px-6 text-sm font-medium text-white transition hover:bg-purple-700"
|
| 687 |
style={{ width: "190px", maxWidth: "100%" }}
|
| 688 |
>
|
|
|
|
| 12 |
import type { BillingCycle, PlanKey } from "../api/billing";
|
| 13 |
import { useAuth } from "../hooks/useAuth";
|
| 14 |
import { useErrorModal, getErrorMessage } from "../contexts/ErrorModalContext";
|
|
|
|
| 15 |
import PublicHeader from "../components/public/PublicHeader";
|
| 16 |
import PublicFooter from "../components/public/PublicFooter";
|
| 17 |
import Seo from "../components/seo/Seo";
|
|
|
|
| 52 |
const navigate = useNavigate();
|
| 53 |
const [searchParams] = useSearchParams();
|
| 54 |
const { showError } = useErrorModal();
|
|
|
|
| 55 |
const [checkoutLoading, setCheckoutLoading] = useState(false);
|
| 56 |
const [billingCycle, setBillingCycle] = useState<BillingCycle>("monthly");
|
| 57 |
const [subscription, setSubscription] = useState<SubscriptionDetail | null>(null);
|
|
|
|
| 361 |
<div className="flex justify-center">
|
| 362 |
<button
|
| 363 |
type="button"
|
| 364 |
+
onClick={() => navigate("/signin")}
|
| 365 |
className="inline-flex h-10 items-center justify-center rounded-full bg-purple-600 px-6 text-sm font-medium text-white transition hover:bg-purple-700"
|
| 366 |
style={{ width: "190px", maxWidth: "100%" }}
|
| 367 |
>
|
|
|
|
| 391 |
<div className="flex justify-center">
|
| 392 |
<button
|
| 393 |
type="button"
|
| 394 |
+
onClick={() => navigate("/signin")}
|
| 395 |
className="inline-flex h-10 items-center justify-center rounded-full bg-purple-600 px-6 text-sm font-medium text-white transition hover:bg-purple-700"
|
| 396 |
style={{ width: "190px", maxWidth: "100%" }}
|
| 397 |
>
|
|
|
|
| 472 |
<div className="flex justify-center">
|
| 473 |
<button
|
| 474 |
type="button"
|
| 475 |
+
onClick={() => navigate("/signin")}
|
| 476 |
className="inline-flex h-10 items-center justify-center rounded-full bg-purple-600 px-6 text-sm font-medium text-white transition hover:bg-purple-700"
|
| 477 |
style={{ width: "190px", maxWidth: "100%" }}
|
| 478 |
>
|
|
|
|
| 569 |
<div className="flex justify-center">
|
| 570 |
<button
|
| 571 |
type="button"
|
| 572 |
+
onClick={() => navigate("/signin")}
|
| 573 |
className="inline-flex h-10 items-center justify-center rounded-full bg-purple-600 px-6 text-sm font-medium text-white transition hover:bg-purple-700"
|
| 574 |
style={{ width: "190px", maxWidth: "100%" }}
|
| 575 |
>
|
|
|
|
| 680 |
<div className="flex justify-center">
|
| 681 |
<button
|
| 682 |
type="button"
|
| 683 |
+
onClick={() => navigate("/signin")}
|
| 684 |
className="inline-flex h-10 items-center justify-center rounded-full bg-purple-600 px-6 text-sm font-medium text-white transition hover:bg-purple-700"
|
| 685 |
style={{ width: "190px", maxWidth: "100%" }}
|
| 686 |
>
|