Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
"""add oauth subject to users

Revision ID: f7c2d9a4e1b6
Revises: e0bee973af24
"""

from collections.abc import Sequence

import sqlalchemy as sa

from alembic import op

revision: str = "f7c2d9a4e1b6"
down_revision: str | Sequence[str] | None = "e0bee973af24"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None


def upgrade() -> None:
op.add_column(
"users", sa.Column("oauth_subject", sa.String(length=255), nullable=True)
)
op.create_unique_constraint(
"users_oauth_identity_key", "users", ["oauth_provider", "oauth_subject"]
)


def downgrade() -> None:
op.drop_constraint("users_oauth_identity_key", "users", type_="unique")
op.drop_column("users", "oauth_subject")
40 changes: 27 additions & 13 deletions backend/app/auth/oauth/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,7 @@ def fail(code: str):
email = profile.get("email", "")
verified = profile.get("email_verified") in (True, "true")
name = profile.get("name") or email.split("@", 1)[0]
subject = str(profile.get("sub", ""))
else:
token_res = await client.post(
"https://github.com/login/oauth/access_token",
Expand Down Expand Up @@ -212,31 +213,44 @@ def fail(code: str):
or profile.get("login")
or email.split("@", 1)[0]
)
subject = str(profile.get("id", ""))
except (httpx.HTTPError, KeyError, ValueError) as exc:
logger.warning("OAuth exchange error with provider %s: %s", provider, exc)
return fail("oauth_provider_error")

email = email.strip().lower()
name = " ".join(str(name).split())[:255]
subject = subject.strip()
if not email or not verified or not name:
return fail("oauth_unverified_email" if not verified else "oauth_profile")
if not subject:
return fail("oauth_profile")

user = await db.scalar(
select(User).where(func.lower(User.email) == email).with_for_update()
select(User)
.where(User.oauth_provider == provider, User.oauth_subject == subject)
.with_for_update()
)
if user is not None:
return fail("email_exists")
if user is None:
user = await db.scalar(
select(User).where(func.lower(User.email) == email).with_for_update()
)
if user is not None:
return fail("email_exists")

user = User(
email=email,
name=name,
password_hash=None,
oauth_provider=provider,
is_verified=True,
is_admin=False,
)
db.add(user)
await db.flush()
user = User(
email=email,
name=name,
password_hash=None,
oauth_provider=provider,
oauth_subject=subject,
is_verified=True,
is_admin=False,
)
db.add(user)
await db.flush()
elif user.deleted_at is not None:
return fail("email_exists")

scopes = list(DEFAULT_SCOPES)
if user.is_admin:
Expand Down
38 changes: 35 additions & 3 deletions backend/app/tests/auth/integration/test_oauth_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ async def test_oauth_callback_denied(db_client: AsyncClient, test_settings: Sett


@pytest.mark.asyncio
async def test_oauth_callback_google_success_creates_user(
async def test_oauth_callback_google_creates_and_reauthenticates_user(
db_client: AsyncClient, db_session, test_settings: Settings
):
test_settings.google_client_id = "test-google-id"
Expand All @@ -124,6 +124,7 @@ async def test_oauth_callback_google_success_creates_user(
"email": "oauth.user@example.com",
"email_verified": True,
"name": "OAuth User",
"sub": "google-user-id",
}
mock_claims_resp.raise_for_status.return_value = None

Expand All @@ -148,14 +149,41 @@ async def test_oauth_callback_google_success_creates_user(
assert user is not None
assert user.name == "OAuth User"
assert user.oauth_provider == "google"
assert user.oauth_subject == "google-user-id"
assert user.is_verified is True
assert user.password_hash is None

repeat_state = "returning-google-state"
db_client.cookies.set(
"oauth_state", _make_state_cookie(test_settings, "google", repeat_state)
)
with (
patch("httpx.AsyncClient.post", return_value=mock_token_resp),
patch("httpx.AsyncClient.get", return_value=mock_claims_resp),
):
response = await db_client.get(
"/api/v1/auth/oauth/google/callback",
params={"code": "returning-auth-code", "state": repeat_state},
follow_redirects=False,
)

assert response.status_code == 303
assert response.headers.get("Location", "").endswith("/semana/perfil")
returning_user = await db_session.scalar(
select(User).where(User.oauth_subject == "google-user-id")
)
assert returning_user is not None
assert returning_user.id == user.id


@pytest.mark.asyncio
@pytest.mark.parametrize(
("oauth_provider", "deleted"),
[(None, False), ("github", False), (None, True)],
("oauth_provider", "oauth_subject", "deleted"),
[
(None, None, False),
("github", "github-user-id", False),
("google", "google-user-id", True),
],
)
async def test_oauth_callback_blocks_existing_email(
db_client: AsyncClient,
Expand All @@ -164,13 +192,15 @@ async def test_oauth_callback_blocks_existing_email(
user_factory,
test_settings: Settings,
oauth_provider: str | None,
oauth_subject: str | None,
deleted: bool,
):
if deleted:
user = await deleted_user_factory(email="existing-pwd@example.com")
else:
user = await user_factory(email="existing-pwd@example.com")
user.oauth_provider = oauth_provider
user.oauth_subject = oauth_subject
await db_session.flush()

test_settings.google_client_id = "test-google-id"
Expand All @@ -190,6 +220,7 @@ async def test_oauth_callback_blocks_existing_email(
"email": "existing-pwd@example.com",
"email_verified": True,
"name": "Imposter",
"sub": "google-user-id",
}
mock_claims_resp.raise_for_status.return_value = None

Expand All @@ -207,5 +238,6 @@ async def test_oauth_callback_blocks_existing_email(
assert response.status_code == 303
assert "error=email_exists" in response.headers.get("Location", "")
assert user.oauth_provider == oauth_provider
assert user.oauth_subject == oauth_subject
assert user.password_hash is not None
assert (user.deleted_at is not None) is deleted
9 changes: 8 additions & 1 deletion backend/app/users/models.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from __future__ import annotations

from sqlalchemy import Boolean, String
from sqlalchemy import Boolean, String, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column

from app.core.mixins import TimestampsMixin, UUIDPKMixin
Expand All @@ -18,6 +18,12 @@ class User(Base, UUIDPKMixin, TimestampsMixin):
a partir do nome da classe ("User" -> "users").
"""

__table_args__ = (
UniqueConstraint(
"oauth_provider", "oauth_subject", name="users_oauth_identity_key"
),
)

email: Mapped[str] = mapped_column(
String(255), unique=True, index=True, nullable=False
)
Expand All @@ -28,6 +34,7 @@ class User(Base, UUIDPKMixin, TimestampsMixin):
password_hash: Mapped[str | None] = mapped_column(String(255), nullable=True)

oauth_provider: Mapped[str | None] = mapped_column(String(16), nullable=True)
oauth_subject: Mapped[str | None] = mapped_column(String(255), nullable=True)

is_admin: Mapped[bool] = mapped_column(
Boolean, nullable=False, default=False, server_default="false"
Expand Down
Loading