From a3361e88b3fa87a605a332171eef9815f4d62ebd Mon Sep 17 00:00:00 2001
From: dlmeneguin
Date: Sat, 3 Oct 2026 10:29:48 -0300
Subject: [PATCH 1/3] feat(auth): adiciona login e cadastro com Google e Github
---
backend/.env.example | 12 +-
backend/README.md | 10 +
...0bee973af24_add_oauth_provider_to_users.py | 35 +++
backend/app/auth/oauth/__init__.py | 1 +
backend/app/auth/oauth/routes.py | 259 ++++++++++++++++++
backend/app/auth/services.py | 2 +-
backend/app/core/config.py | 7 +
backend/app/main.py | 2 +
.../auth/integration/test_oauth_routes.py | 193 +++++++++++++
backend/app/users/models.py | 2 +
backend/entrypoint.sh | 6 +-
backend/pyproject.toml | 2 +
backend/uv.lock | 17 +-
frontend/src/app/semana/(site)/login/page.tsx | 24 +-
frontend/src/features/auth/README.md | 7 +
.../features/auth/components/login-form.tsx | 4 +
.../auth/components/oauth-buttons.tsx | 30 ++
.../auth/components/register-form.tsx | 4 +
18 files changed, 611 insertions(+), 6 deletions(-)
create mode 100644 backend/alembic/versions/e0bee973af24_add_oauth_provider_to_users.py
create mode 100644 backend/app/auth/oauth/__init__.py
create mode 100644 backend/app/auth/oauth/routes.py
create mode 100644 backend/app/tests/auth/integration/test_oauth_routes.py
create mode 100644 frontend/src/features/auth/components/oauth-buttons.tsx
diff --git a/backend/.env.example b/backend/.env.example
index 1ad2f4ca..669592f4 100644
--- a/backend/.env.example
+++ b/backend/.env.example
@@ -5,4 +5,14 @@ SECRET_KEY=change_this_to_a_secure_random_key_in_production
# JWT access/id tokens fields
ISSUER=http://localhost:8000
-AUDIENCE=symcomp-frontend
\ No newline at end of file
+AUDIENCE=symcomp-frontend
+
+#oAuth
+GOOGLE_CLIENT_ID=
+GOOGLE_CLIENT_SECRET=
+
+GITHUB_CLIENT_ID=
+GITHUB_CLIENT_SECRET=
+
+OAUTH_REDIRECT_BASE=http://localhost:8000
+FRONTEND_BASE_URL=http://localhost:3000
\ No newline at end of file
diff --git a/backend/README.md b/backend/README.md
index 2cb4ed52..b5a3af27 100644
--- a/backend/README.md
+++ b/backend/README.md
@@ -63,3 +63,13 @@ $ uv run alembic upgrade head
5. Commit your changes.
Commit together: SQLAlchemy model changes, migration files (under `alembic/versions/`) and tests for new behaviour. In new environments, `alembic upgrade head` builds the full schema from zero.
+
+### Login social (Google e GitHub)
+
+Defina no ambiente do backend `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET`,
+`GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET`, `OAUTH_REDIRECT_BASE` (origem pública
+que encaminha `/api` ao backend) e `FRONTEND_BASE_URL`. Cadastre nos consoles OAuth
+as callbacks `/api/v1/auth/oauth/google/callback` e
+`/api/v1/auth/oauth/github/callback` sob essa origem. Execute `alembic upgrade head`
+para adicionar `users.oauth_provider`. O login exige e-mail verificado; e-mails já
+associados a contas com senha não são vinculados automaticamente.
diff --git a/backend/alembic/versions/e0bee973af24_add_oauth_provider_to_users.py b/backend/alembic/versions/e0bee973af24_add_oauth_provider_to_users.py
new file mode 100644
index 00000000..b52f0723
--- /dev/null
+++ b/backend/alembic/versions/e0bee973af24_add_oauth_provider_to_users.py
@@ -0,0 +1,35 @@
+"""add oauth provider to users
+
+Revision ID: e0bee973af24
+Revises: 4f21ac9d7b30
+Create Date: 2026-10-02 13:52:42.044097
+
+"""
+
+from collections.abc import Sequence
+
+import sqlalchemy as sa
+
+from alembic import op
+
+# revision identifiers, used by Alembic.
+revision: str = "e0bee973af24"
+down_revision: str | Sequence[str] | None = "4f21ac9d7b30"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+
+def upgrade() -> None:
+ """Upgrade schema."""
+ # ### commands auto generated by Alembic - please adjust! ###
+ op.add_column(
+ "users", sa.Column("oauth_provider", sa.String(length=16), nullable=True)
+ )
+ # ### end Alembic commands ###
+
+
+def downgrade() -> None:
+ """Downgrade schema."""
+ # ### commands auto generated by Alembic - please adjust! ###
+ op.drop_column("users", "oauth_provider")
+ # ### end Alembic commands ###
diff --git a/backend/app/auth/oauth/__init__.py b/backend/app/auth/oauth/__init__.py
new file mode 100644
index 00000000..c0e158ca
--- /dev/null
+++ b/backend/app/auth/oauth/__init__.py
@@ -0,0 +1 @@
+"""OAuth login integrations."""
diff --git a/backend/app/auth/oauth/routes.py b/backend/app/auth/oauth/routes.py
new file mode 100644
index 00000000..8ea5e2dc
--- /dev/null
+++ b/backend/app/auth/oauth/routes.py
@@ -0,0 +1,259 @@
+from __future__ import annotations
+
+import logging
+import secrets
+from typing import Annotated
+from urllib.parse import urlencode
+
+import httpx
+from fastapi import APIRouter, Depends, Request
+from fastapi.responses import RedirectResponse
+from itsdangerous import BadSignature, URLSafeTimedSerializer
+from sqlalchemy import func, select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.auth import services as auth_services
+from app.auth.scopes import DEFAULT_SCOPES, Scope
+from app.core.config import AppEnv, get_settings
+from app.core.database import get_session
+from app.users.models import User
+
+logger = logging.getLogger(__name__)
+router = APIRouter(prefix="/oauth", tags=["auth"])
+STATE_COOKIE = "oauth_state"
+
+
+def _serializer():
+ return URLSafeTimedSerializer(
+ get_settings().secret_key.get_secret_value(), salt="oauth-state"
+ )
+
+
+def _credentials(provider: str):
+ s = get_settings()
+ if provider == "google":
+ return (
+ s.google_client_id,
+ s.google_client_secret.get_secret_value()
+ if s.google_client_secret
+ else None,
+ )
+ if provider == "github":
+ return (
+ s.github_client_id,
+ s.github_client_secret.get_secret_value()
+ if s.github_client_secret
+ else None,
+ )
+ return None, None
+
+
+@router.get("/{provider}/login")
+async def oauth_login(provider: str):
+ frontend = str(get_settings().frontend_base_url).rstrip("/")
+ if provider not in ("google", "github"):
+ return RedirectResponse(
+ f"{frontend}/semana/login?error=invalid_provider", status_code=303
+ )
+
+ client_id, _ = _credentials(provider)
+ if not client_id:
+ return RedirectResponse(
+ f"{frontend}/semana/login?error=provider_unavailable", status_code=303
+ )
+
+ state = secrets.token_urlsafe(32)
+ signed = _serializer().dumps({"state": state, "provider": provider})
+ callback = f"{str(get_settings().oauth_redirect_base).rstrip('/')}/api/v1/auth/oauth/{provider}/callback"
+ if provider == "google":
+ params = {
+ "client_id": client_id,
+ "redirect_uri": callback,
+ "response_type": "code",
+ "scope": "openid email profile",
+ "state": state,
+ "prompt": "select_account",
+ }
+ url = "https://accounts.google.com/o/oauth2/v2/auth?" + urlencode(params)
+ else:
+ params = {
+ "client_id": client_id,
+ "redirect_uri": callback,
+ "scope": "read:user user:email",
+ "state": state,
+ }
+ url = "https://github.com/login/oauth/authorize?" + urlencode(params)
+
+ redirect = RedirectResponse(url, status_code=302)
+ redirect.set_cookie(
+ STATE_COOKIE,
+ signed,
+ httponly=True,
+ secure=get_settings().app_env == AppEnv.production,
+ samesite="lax",
+ max_age=600,
+ )
+ return redirect
+
+
+@router.get("/{provider}/callback")
+async def oauth_callback(
+ provider: str,
+ request: Request,
+ db: Annotated[AsyncSession, Depends(get_session)],
+):
+ frontend = str(get_settings().frontend_base_url).rstrip("/")
+
+ def fail(code: str):
+ r = RedirectResponse(f"{frontend}/semana/login?error={code}", status_code=303)
+ r.delete_cookie(STATE_COOKIE)
+ return r
+
+ if provider not in ("google", "github"):
+ return fail("invalid_provider")
+
+ client_id, client_secret = _credentials(provider)
+ if not client_id or not client_secret:
+ return fail("provider_unavailable")
+
+ try:
+ signed = _serializer().loads(request.cookies.get(STATE_COOKIE, ""), max_age=600)
+ except BadSignature:
+ logger.warning("OAuth state cookie has bad or expired signature")
+ return fail("oauth_state")
+
+ if signed.get("provider") != provider or not secrets.compare_digest(
+ signed.get("state", ""), request.query_params.get("state", "")
+ ):
+ logger.warning("OAuth state verification failed for provider: %s", provider)
+ return fail("oauth_state")
+
+ code = request.query_params.get("code")
+ if not code or request.query_params.get("error"):
+ logger.info(
+ "OAuth authorization denied or cancelled for provider: %s", provider
+ )
+ return fail("oauth_denied")
+
+ callback = f"{str(get_settings().oauth_redirect_base).rstrip('/')}/api/v1/auth/oauth/{provider}/callback"
+ try:
+ async with httpx.AsyncClient(
+ timeout=12, headers={"Accept": "application/json"}
+ ) as client:
+ if provider == "google":
+ token_res = await client.post(
+ "https://oauth2.googleapis.com/token",
+ data={
+ "code": code,
+ "client_id": client_id,
+ "client_secret": client_secret,
+ "redirect_uri": callback,
+ "grant_type": "authorization_code",
+ },
+ )
+ token_res.raise_for_status()
+ id_token = token_res.json()["id_token"]
+ claims_res = await client.get(
+ "https://oauth2.googleapis.com/tokeninfo",
+ params={"id_token": id_token},
+ )
+ claims_res.raise_for_status()
+ profile = claims_res.json()
+ if profile.get("aud") != client_id or profile.get("iss") not in (
+ "accounts.google.com",
+ "https://accounts.google.com",
+ ):
+ logger.warning("Google ID token validation mismatch (aud/iss)")
+ return fail("oauth_invalid_profile")
+ email = profile.get("email", "")
+ verified = profile.get("email_verified") in (True, "true")
+ name = profile.get("name") or email.split("@", 1)[0]
+ else:
+ token_res = await client.post(
+ "https://github.com/login/oauth/access_token",
+ headers={"Accept": "application/json"},
+ data={
+ "code": code,
+ "client_id": client_id,
+ "client_secret": client_secret,
+ "redirect_uri": callback,
+ },
+ )
+ token_res.raise_for_status()
+ access = token_res.json().get("access_token")
+ if not access:
+ return fail("oauth_profile")
+ headers = {
+ "Authorization": f"Bearer {access}",
+ "Accept": "application/vnd.github+json",
+ "X-GitHub-Api-Version": "2022-11-28",
+ }
+ user_res = await client.get(
+ "https://api.github.com/user", headers=headers
+ )
+ emails_res = await client.get(
+ "https://api.github.com/user/emails", headers=headers
+ )
+ user_res.raise_for_status()
+ emails_res.raise_for_status()
+ profile = user_res.json()
+ chosen = next(
+ (
+ e
+ for e in emails_res.json()
+ if e.get("primary") and e.get("verified")
+ ),
+ None,
+ )
+ email = chosen.get("email", "") if chosen else ""
+ verified = bool(chosen)
+ name = (
+ profile.get("name")
+ or profile.get("login")
+ or email.split("@", 1)[0]
+ )
+ 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]
+ if not email or not verified or not name:
+ return fail("oauth_unverified_email" if not verified else "oauth_profile")
+
+ user = await db.scalar(
+ select(User).where(func.lower(User.email) == email).with_for_update()
+ )
+ if user is not None and user.deleted_at is None and user.oauth_provider is None:
+ return fail("email_exists")
+ if user is not None and user.deleted_at is not None:
+ user.deleted_at = None
+ user.name = name
+ user.password_hash = None
+ user.oauth_provider = provider
+ user.is_admin = False
+ user.is_verified = True
+ elif user is None:
+ user = User(
+ email=email,
+ name=name,
+ password_hash=None,
+ oauth_provider=provider,
+ is_verified=True,
+ is_admin=False,
+ )
+ db.add(user)
+ await db.flush()
+ else:
+ # OAuth-origin accounts may authenticate with either configured provider.
+ user.is_verified = True
+
+ scopes = list(DEFAULT_SCOPES)
+ if user.is_admin:
+ scopes.append(Scope.ADMIN)
+
+ refresh = await auth_services.create_refresh_token(db, user.id, scopes)
+ redirect = RedirectResponse(f"{frontend}/semana/perfil", status_code=303)
+ redirect.set_cookie(**auth_services.build_refresh_token_cookie(refresh))
+ redirect.delete_cookie(STATE_COOKIE)
+ return redirect
diff --git a/backend/app/auth/services.py b/backend/app/auth/services.py
index 6e4f1377..6b16fa49 100644
--- a/backend/app/auth/services.py
+++ b/backend/app/auth/services.py
@@ -32,7 +32,7 @@ async def authenticate(db_session: AsyncSession, email: str, password: str):
if user is None:
return None
- if not verify_password(password, user.password_hash):
+ if user.password_hash is None or not verify_password(password, user.password_hash):
return None
return user
diff --git a/backend/app/core/config.py b/backend/app/core/config.py
index 4ca2a73f..21f7a6b5 100644
--- a/backend/app/core/config.py
+++ b/backend/app/core/config.py
@@ -83,6 +83,13 @@ class Settings(BaseSettings):
description="Identificador do cliente que consome o id_token (claim 'aud')",
)
+ google_client_id: str | None = None
+ google_client_secret: SecretStr | None = None
+ github_client_id: str | None = None
+ github_client_secret: SecretStr | None = None
+ oauth_redirect_base: AnyHttpUrl = Field(default="http://localhost:8000")
+ frontend_base_url: AnyHttpUrl = Field(default="http://localhost:3000")
+
media_root: Path = Field(
# o default aqui assume /backend/app/core/config.py como caminho deste arquivo
# se isso mudar, é bom atualizar
diff --git a/backend/app/main.py b/backend/app/main.py
index e5969a95..56554d9b 100644
--- a/backend/app/main.py
+++ b/backend/app/main.py
@@ -7,6 +7,7 @@
from app.atividade.routes import admin_router as atividade_admin_router
from app.atividade.routes import attendance_router as atividade_attendance_router
from app.atividade.routes import router as atividade_router
+from app.auth.oauth.routes import router as oauth_router
from app.auth.routes import router as auth_router
from app.challenges.admin_routes import router as challenge_admin_router
from app.challenges.routes import router as challenge_router
@@ -54,6 +55,7 @@ async def lifespan(app: FastAPI):
app.include_router(health_router, prefix="/api/v1")
app.include_router(auth_router, prefix="/api/v1/auth")
+app.include_router(oauth_router, prefix="/api/v1/auth")
app.include_router(user_router, prefix="/api/v1/user")
app.include_router(semana_router, prefix="/api/v1")
app.include_router(semana_admin_router, prefix="/api/v1")
diff --git a/backend/app/tests/auth/integration/test_oauth_routes.py b/backend/app/tests/auth/integration/test_oauth_routes.py
new file mode 100644
index 00000000..ca3762fc
--- /dev/null
+++ b/backend/app/tests/auth/integration/test_oauth_routes.py
@@ -0,0 +1,193 @@
+from unittest.mock import MagicMock, patch
+
+import pytest
+from httpx2 import AsyncClient
+from itsdangerous import URLSafeTimedSerializer
+from pydantic import SecretStr
+from sqlalchemy import select
+
+from app.core.config import Settings
+from app.users.models import User
+
+
+def _make_state_cookie(settings: Settings, provider: str, state: str) -> str:
+ serializer = URLSafeTimedSerializer(
+ settings.secret_key.get_secret_value(), salt="oauth-state"
+ )
+ return serializer.dumps({"state": state, "provider": provider})
+
+
+@pytest.mark.asyncio
+async def test_oauth_login_redirects_to_google(
+ db_client: AsyncClient, test_settings: Settings
+):
+ test_settings.google_client_id = "test-google-id"
+ test_settings.google_client_secret = SecretStr("test-google-secret")
+
+ response = await db_client.get(
+ "/api/v1/auth/oauth/google/login", follow_redirects=False
+ )
+
+ assert response.status_code == 302
+ location = response.headers.get("Location", "")
+ assert location.startswith("https://accounts.google.com/o/oauth2/v2/auth?")
+ assert "client_id=test-google-id" in location
+ assert "response_type=code" in location
+ assert "scope=openid+email+profile" in location
+ assert response.cookies.get("oauth_state") is not None
+
+
+@pytest.mark.asyncio
+async def test_oauth_login_unavailable_when_missing_credentials(
+ db_client: AsyncClient, test_settings: Settings
+):
+ test_settings.google_client_id = None
+ test_settings.google_client_secret = None
+
+ response = await db_client.get(
+ "/api/v1/auth/oauth/google/login", follow_redirects=False
+ )
+
+ assert response.status_code == 303
+ location = response.headers.get("Location", "")
+ assert "error=provider_unavailable" in location
+
+
+@pytest.mark.asyncio
+async def test_oauth_login_invalid_provider(
+ db_client: AsyncClient, test_settings: Settings
+):
+ response = await db_client.get(
+ "/api/v1/auth/oauth/facebook/login", follow_redirects=False
+ )
+
+ assert response.status_code == 303
+ location = response.headers.get("Location", "")
+ assert "error=invalid_provider" in location
+
+
+@pytest.mark.asyncio
+async def test_oauth_callback_invalid_state(
+ db_client: AsyncClient, test_settings: Settings
+):
+ test_settings.google_client_id = "test-google-id"
+ test_settings.google_client_secret = SecretStr("test-google-secret")
+
+ db_client.cookies.set("oauth_state", "bad-signature")
+ response = await db_client.get(
+ "/api/v1/auth/oauth/google/callback",
+ params={"code": "123", "state": "invalid-state"},
+ follow_redirects=False,
+ )
+
+ assert response.status_code == 303
+ assert "error=oauth_state" in response.headers.get("Location", "")
+
+
+@pytest.mark.asyncio
+async def test_oauth_callback_denied(db_client: AsyncClient, test_settings: Settings):
+ test_settings.google_client_id = "test-google-id"
+ test_settings.google_client_secret = SecretStr("test-google-secret")
+
+ state = "secure-random-state"
+ cookie_val = _make_state_cookie(test_settings, "google", state)
+
+ db_client.cookies.set("oauth_state", cookie_val)
+ response = await db_client.get(
+ "/api/v1/auth/oauth/google/callback",
+ params={"error": "access_denied", "state": state},
+ follow_redirects=False,
+ )
+
+ assert response.status_code == 303
+ assert "error=oauth_denied" in response.headers.get("Location", "")
+
+
+@pytest.mark.asyncio
+async def test_oauth_callback_google_success_creates_user(
+ db_client: AsyncClient, db_session, test_settings: Settings
+):
+ test_settings.google_client_id = "test-google-id"
+ test_settings.google_client_secret = SecretStr("test-google-secret")
+
+ state = "random-oauth-state-1234"
+ cookie_val = _make_state_cookie(test_settings, "google", state)
+
+ mock_token_resp = MagicMock()
+ mock_token_resp.json.return_value = {"id_token": "fake-google-jwt"}
+ mock_token_resp.raise_for_status.return_value = None
+
+ mock_claims_resp = MagicMock()
+ mock_claims_resp.json.return_value = {
+ "aud": "test-google-id",
+ "iss": "https://accounts.google.com",
+ "email": "oauth.user@example.com",
+ "email_verified": True,
+ "name": "OAuth User",
+ }
+ mock_claims_resp.raise_for_status.return_value = None
+
+ db_client.cookies.set("oauth_state", cookie_val)
+ 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": "valid-auth-code", "state": state},
+ follow_redirects=False,
+ )
+
+ assert response.status_code == 303
+ assert response.headers.get("Location", "").endswith("/semana/perfil")
+ assert response.cookies.get("refresh_token") is not None
+
+ user = await db_session.scalar(
+ select(User).where(User.email == "oauth.user@example.com")
+ )
+ assert user is not None
+ assert user.name == "OAuth User"
+ assert user.oauth_provider == "google"
+ assert user.is_verified is True
+ assert user.password_hash is None
+
+
+@pytest.mark.asyncio
+async def test_oauth_callback_cannot_override_existing_password_user(
+ db_client: AsyncClient, user_factory, test_settings: Settings
+):
+ await user_factory(email="existing-pwd@example.com")
+
+ test_settings.google_client_id = "test-google-id"
+ test_settings.google_client_secret = SecretStr("test-google-secret")
+
+ state = "state-conflict"
+ cookie_val = _make_state_cookie(test_settings, "google", state)
+
+ mock_token_resp = MagicMock()
+ mock_token_resp.json.return_value = {"id_token": "fake-jwt"}
+ mock_token_resp.raise_for_status.return_value = None
+
+ mock_claims_resp = MagicMock()
+ mock_claims_resp.json.return_value = {
+ "aud": "test-google-id",
+ "iss": "https://accounts.google.com",
+ "email": "existing-pwd@example.com",
+ "email_verified": True,
+ "name": "Imposter",
+ }
+ mock_claims_resp.raise_for_status.return_value = None
+
+ db_client.cookies.set("oauth_state", cookie_val)
+ 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": "code", "state": state},
+ follow_redirects=False,
+ )
+
+ assert response.status_code == 303
+ assert "error=email_exists" in response.headers.get("Location", "")
diff --git a/backend/app/users/models.py b/backend/app/users/models.py
index 196ab8ca..74a35aab 100644
--- a/backend/app/users/models.py
+++ b/backend/app/users/models.py
@@ -27,6 +27,8 @@ class User(Base, UUIDPKMixin, TimestampsMixin):
# podem não ter senha própria.
password_hash: Mapped[str | None] = mapped_column(String(255), nullable=True)
+ oauth_provider: Mapped[str | None] = mapped_column(String(16), nullable=True)
+
is_admin: Mapped[bool] = mapped_column(
Boolean, nullable=False, default=False, server_default="false"
)
diff --git a/backend/entrypoint.sh b/backend/entrypoint.sh
index 46831189..2d2aeaa0 100644
--- a/backend/entrypoint.sh
+++ b/backend/entrypoint.sh
@@ -1,5 +1,9 @@
#!/bin/sh
set -e
+if [ "$APP_ENV" = "dev" ] && command -v uv >/dev/null 2>&1; then
+ uv sync --frozen --link-mode=copy
+fi
+
alembic upgrade head
-exec "$@"
\ No newline at end of file
+exec "$@"
diff --git a/backend/pyproject.toml b/backend/pyproject.toml
index f712292c..67e21509 100644
--- a/backend/pyproject.toml
+++ b/backend/pyproject.toml
@@ -10,6 +10,8 @@ dependencies = [
"fastapi[standard]>=0.141.1",
"pwdlib[argon2]>=0.2.0",
"PyJWT>=2.13.0",
+ "httpx>=0.28.1",
+ "itsdangerous>=2.2.0",
"sqlalchemy>=2.0.51",
]
diff --git a/backend/uv.lock b/backend/uv.lock
index 90262489..cc81ee1d 100644
--- a/backend/uv.lock
+++ b/backend/uv.lock
@@ -179,6 +179,8 @@ dependencies = [
{ name = "alembic" },
{ name = "asyncpg" },
{ name = "fastapi", extra = ["standard"] },
+ { name = "httpx" },
+ { name = "itsdangerous" },
{ name = "pwdlib", extra = ["argon2"] },
{ name = "pyjwt" },
{ name = "sqlalchemy" },
@@ -197,6 +199,8 @@ requires-dist = [
{ name = "alembic", specifier = ">=1.18.5" },
{ name = "asyncpg", specifier = ">=0.31.0" },
{ name = "fastapi", extras = ["standard"], specifier = ">=0.141.1" },
+ { name = "httpx", specifier = ">=0.28.1" },
+ { name = "itsdangerous", specifier = ">=2.2.0" },
{ name = "pwdlib", extras = ["argon2"], specifier = ">=0.2.0" },
{ name = "pyjwt", specifier = ">=2.13.0" },
{ name = "sqlalchemy", specifier = ">=2.0.51" },
@@ -659,8 +663,8 @@ name = "httpcore2"
version = "2.12.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
- { name = "h11" },
- { name = "truststore" },
+ { name = "h11", marker = "python_full_version < '3.12' or sys_platform != 'emscripten'" },
+ { name = "truststore", marker = "python_full_version < '3.12' or sys_platform != 'emscripten'" },
]
sdist = { url = "https://files.pythonhosted.org/packages/be/ad/f4f0e57345f1870f3e8cb624e058d7eca6e5a27d33bcc3311d9b618734cd/httpcore2-2.12.0.tar.gz", hash = "sha256:9293522bba0aa7c4c8e9e3f040c16575bd8868e155a77fa30c7a9085a5eae648", size = 67548, upload-time = "2026-08-18T13:22:08.211Z" }
wheels = [
@@ -769,6 +773,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/cb/b1/3846dd7f199d53cb17f49cba7e651e9ce294d8497c8c150530ed11865bb8/iniconfig-2.3.0-py3-none-any.whl", hash = "sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12", size = 7484, upload-time = "2025-10-18T21:55:41.639Z" },
]
+[[package]]
+name = "itsdangerous"
+version = "2.2.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/9c/cb/8ac0172223afbccb63986cc25049b154ecfb5e85932587206f42317be31d/itsdangerous-2.2.0.tar.gz", hash = "sha256:e0050c0b7da1eea53ffaf149c0cfbb5c6e2e2b69c4bef22c81fa6eb73e5f6173", size = 54410, upload-time = "2024-04-16T21:28:15.614Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/04/96/92447566d16df59b2a776c0fb82dbc4d9e07cd95062562af01e408583fc4/itsdangerous-2.2.0-py3-none-any.whl", hash = "sha256:c6242fc49e35958c8b15141343aa660db5fc54d4f13a1db01a3f5891b98700ef", size = 16234, upload-time = "2024-04-16T21:28:14.499Z" },
+]
+
[[package]]
name = "jinja2"
version = "3.1.6"
diff --git a/frontend/src/app/semana/(site)/login/page.tsx b/frontend/src/app/semana/(site)/login/page.tsx
index 9f902358..9529f267 100644
--- a/frontend/src/app/semana/(site)/login/page.tsx
+++ b/frontend/src/app/semana/(site)/login/page.tsx
@@ -1,7 +1,24 @@
import { AuthCard } from '@/features/auth/components/auth-card'
import { LoginForm } from '@/features/auth/components/login-form'
-export default function LoginPage() {
+const oauthErrors: Record = {
+ provider_unavailable: 'Este método de login ainda não está configurado.',
+ invalid_provider: 'Provedor de autenticação inválido.',
+ oauth_state: 'A tentativa de login expirou ou é inválida. Tente novamente.',
+ oauth_denied: 'A autenticação foi cancelada.',
+ oauth_invalid_profile: 'Não foi possível validar sua conta no provedor.',
+ oauth_profile: 'O provedor não forneceu os dados necessários.',
+ oauth_unverified_email: 'Confirme seu e-mail no provedor antes de continuar.',
+ oauth_provider_error: 'O provedor não concluiu a autenticação. Tente novamente.',
+ email_exists: 'Este e-mail já possui cadastro. Entre usando e-mail e senha.',
+}
+
+export default async function LoginPage({
+ searchParams,
+}: {
+ searchParams: Promise<{ error?: string }>
+}) {
+ const { error } = await searchParams
return (
+ {error && oauthErrors[error] && (
+
+ {oauthErrors[error]}
+
+ )}
)
diff --git a/frontend/src/features/auth/README.md b/frontend/src/features/auth/README.md
index 0a0c334f..5aab0f4a 100644
--- a/frontend/src/features/auth/README.md
+++ b/frontend/src/features/auth/README.md
@@ -3,3 +3,10 @@
The client uses the FastAPI auth endpoints under `/api/v1`. Access tokens stay
in memory; the backend refresh token remains an HttpOnly cookie and restores a
session when the Semana shell loads.
+
+OAuth login is handled by the API at `/api/v1/auth/oauth/{google|github}/login`.
+Configure the provider credentials in the backend environment and register callback
+URLs `/api/v1/auth/oauth/google/callback` and `/api/v1/auth/oauth/github/callback`
+under the public API origin. OAuth accounts are marked in `users.oauth_provider`;
+verified email is required, and an existing password account is never linked by email.
+Google and GitHub can both authenticate an OAuth-origin account with the same verified email.
diff --git a/frontend/src/features/auth/components/login-form.tsx b/frontend/src/features/auth/components/login-form.tsx
index 4ca69104..accdb17a 100644
--- a/frontend/src/features/auth/components/login-form.tsx
+++ b/frontend/src/features/auth/components/login-form.tsx
@@ -17,6 +17,7 @@ import {
import { useAuth } from '@/features/auth/auth-provider'
import { SemanaButton } from '@/features/semana/components/semana-button'
import { SemanaInput } from '@/features/semana/components/semana-input'
+import { OAuthButtons } from './oauth-buttons'
const schema = z.object({
email: z.string().email('Digite um e-mail válido.'),
@@ -97,6 +98,9 @@ export function LoginForm() {
{form.formState.isSubmitting ? 'Entrando…' : 'Entrar'}
+
+
+
)
}
diff --git a/frontend/src/features/auth/components/oauth-buttons.tsx b/frontend/src/features/auth/components/oauth-buttons.tsx
new file mode 100644
index 00000000..ea6aa995
--- /dev/null
+++ b/frontend/src/features/auth/components/oauth-buttons.tsx
@@ -0,0 +1,30 @@
+'use client'
+
+import { FaGithub, FaGoogle } from 'react-icons/fa'
+
+export function OAuthButtons() {
+ return (
+
+ )
+}
diff --git a/frontend/src/features/auth/components/register-form.tsx b/frontend/src/features/auth/components/register-form.tsx
index d6af3f90..99610e2b 100644
--- a/frontend/src/features/auth/components/register-form.tsx
+++ b/frontend/src/features/auth/components/register-form.tsx
@@ -17,6 +17,7 @@ import {
import { useAuth } from '@/features/auth/auth-provider'
import { SemanaButton } from '@/features/semana/components/semana-button'
import { SemanaInput } from '@/features/semana/components/semana-input'
+import { OAuthButtons } from './oauth-buttons'
const schema = z.object({
name: z.string().trim().min(1, 'Digite seu nome.').max(255),
@@ -113,6 +114,9 @@ export function RegisterForm() {
{form.formState.isSubmitting ? 'Criando conta…' : 'Criar conta'}
+
+
+
)
}
From d25905add4b165a38bc8c2c5426abe869e68617d Mon Sep 17 00:00:00 2001
From: dlmeneguin
Date: Sat, 3 Oct 2026 11:02:34 -0300
Subject: [PATCH 2/3] fix(auth): Conserta a ultrapassagem dos rates limits
durante testes
---
backend/app/core/rate_limit.py | 11 +++++++++++
backend/app/tests/conftest.py | 7 +++++++
2 files changed, 18 insertions(+)
diff --git a/backend/app/core/rate_limit.py b/backend/app/core/rate_limit.py
index 4f0c9f6d..474d1642 100644
--- a/backend/app/core/rate_limit.py
+++ b/backend/app/core/rate_limit.py
@@ -1,7 +1,10 @@
+from __future__ import annotations
+
import time
from collections import defaultdict
from collections.abc import Callable
from re import fullmatch
+from typing import ClassVar
from fastapi import Request
from fastapi.responses import JSONResponse
@@ -19,11 +22,19 @@
class RateLimitMiddleware:
# ponytail: process-local limits; use Redis when running multiple workers/instances.
+ _instances: ClassVar[list[RateLimitMiddleware]] = []
+
def __init__(self, app: Callable):
self.app = app
self.requests: defaultdict[tuple[str, str, str], list[float]] = defaultdict(
list
)
+ RateLimitMiddleware._instances.append(self)
+
+ @classmethod
+ def reset_all(cls) -> None:
+ for instance in cls._instances:
+ instance.requests.clear()
async def __call__(self, scope, receive, send):
if scope["type"] != "http":
diff --git a/backend/app/tests/conftest.py b/backend/app/tests/conftest.py
index 3b6df366..2c482d8a 100644
--- a/backend/app/tests/conftest.py
+++ b/backend/app/tests/conftest.py
@@ -14,6 +14,13 @@
from app.users.schemas import UserCreate
+@pytest.fixture(autouse=True)
+def reset_rate_limits():
+ RateLimitMiddleware.reset_all()
+ yield
+ RateLimitMiddleware.reset_all()
+
+
@pytest.fixture
def test_settings() -> Settings:
settings = get_settings()
From 17ad1f477db8b6578a925daecba652161fc084d9 Mon Sep 17 00:00:00 2001
From: wate
Date: Sat, 3 Oct 2026 15:32:18 -0300
Subject: [PATCH 3/3] fix(auth): block oauth account collisions
Co-authored-by: Codex
---
...0bee973af24_add_oauth_provider_to_users.py | 2 +-
backend/app/auth/oauth/routes.py | 34 +++++++------------
.../auth/integration/test_oauth_routes.py | 24 +++++++++++--
.../features/auth/components/login-form.tsx | 6 ++--
.../auth/components/oauth-buttons.tsx | 16 ++++-----
.../auth/components/register-form.tsx | 6 ++--
6 files changed, 48 insertions(+), 40 deletions(-)
diff --git a/backend/alembic/versions/e0bee973af24_add_oauth_provider_to_users.py b/backend/alembic/versions/e0bee973af24_add_oauth_provider_to_users.py
index b52f0723..eae018ea 100644
--- a/backend/alembic/versions/e0bee973af24_add_oauth_provider_to_users.py
+++ b/backend/alembic/versions/e0bee973af24_add_oauth_provider_to_users.py
@@ -14,7 +14,7 @@
# revision identifiers, used by Alembic.
revision: str = "e0bee973af24"
-down_revision: str | Sequence[str] | None = "4f21ac9d7b30"
+down_revision: str | Sequence[str] | None = "b81f3c2a6d40"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None
diff --git a/backend/app/auth/oauth/routes.py b/backend/app/auth/oauth/routes.py
index 8ea5e2dc..6eedb158 100644
--- a/backend/app/auth/oauth/routes.py
+++ b/backend/app/auth/oauth/routes.py
@@ -224,29 +224,19 @@ def fail(code: str):
user = await db.scalar(
select(User).where(func.lower(User.email) == email).with_for_update()
)
- if user is not None and user.deleted_at is None and user.oauth_provider is None:
+ if user is not None:
return fail("email_exists")
- if user is not None and user.deleted_at is not None:
- user.deleted_at = None
- user.name = name
- user.password_hash = None
- user.oauth_provider = provider
- user.is_admin = False
- user.is_verified = True
- elif user is None:
- user = User(
- email=email,
- name=name,
- password_hash=None,
- oauth_provider=provider,
- is_verified=True,
- is_admin=False,
- )
- db.add(user)
- await db.flush()
- else:
- # OAuth-origin accounts may authenticate with either configured provider.
- user.is_verified = True
+
+ user = User(
+ email=email,
+ name=name,
+ password_hash=None,
+ oauth_provider=provider,
+ is_verified=True,
+ is_admin=False,
+ )
+ db.add(user)
+ await db.flush()
scopes = list(DEFAULT_SCOPES)
if user.is_admin:
diff --git a/backend/app/tests/auth/integration/test_oauth_routes.py b/backend/app/tests/auth/integration/test_oauth_routes.py
index ca3762fc..e46be051 100644
--- a/backend/app/tests/auth/integration/test_oauth_routes.py
+++ b/backend/app/tests/auth/integration/test_oauth_routes.py
@@ -153,10 +153,25 @@ async def test_oauth_callback_google_success_creates_user(
@pytest.mark.asyncio
-async def test_oauth_callback_cannot_override_existing_password_user(
- db_client: AsyncClient, user_factory, test_settings: Settings
+@pytest.mark.parametrize(
+ ("oauth_provider", "deleted"),
+ [(None, False), ("github", False), (None, True)],
+)
+async def test_oauth_callback_blocks_existing_email(
+ db_client: AsyncClient,
+ db_session,
+ deleted_user_factory,
+ user_factory,
+ test_settings: Settings,
+ oauth_provider: str | None,
+ deleted: bool,
):
- await user_factory(email="existing-pwd@example.com")
+ 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
+ await db_session.flush()
test_settings.google_client_id = "test-google-id"
test_settings.google_client_secret = SecretStr("test-google-secret")
@@ -191,3 +206,6 @@ async def test_oauth_callback_cannot_override_existing_password_user(
assert response.status_code == 303
assert "error=email_exists" in response.headers.get("Location", "")
+ assert user.oauth_provider == oauth_provider
+ assert user.password_hash is not None
+ assert (user.deleted_at is not None) is deleted
diff --git a/frontend/src/features/auth/components/login-form.tsx b/frontend/src/features/auth/components/login-form.tsx
index accdb17a..4ea0bbf7 100644
--- a/frontend/src/features/auth/components/login-form.tsx
+++ b/frontend/src/features/auth/components/login-form.tsx
@@ -53,6 +53,9 @@ export function LoginForm() {
return (
-
-
-
)
}
diff --git a/frontend/src/features/auth/components/oauth-buttons.tsx b/frontend/src/features/auth/components/oauth-buttons.tsx
index ea6aa995..3157ec38 100644
--- a/frontend/src/features/auth/components/oauth-buttons.tsx
+++ b/frontend/src/features/auth/components/oauth-buttons.tsx
@@ -5,14 +5,6 @@ import { FaGithub, FaGoogle } from 'react-icons/fa'
export function OAuthButtons() {
return (
)
}
diff --git a/frontend/src/features/auth/components/register-form.tsx b/frontend/src/features/auth/components/register-form.tsx
index 99610e2b..207e501a 100644
--- a/frontend/src/features/auth/components/register-form.tsx
+++ b/frontend/src/features/auth/components/register-form.tsx
@@ -56,6 +56,9 @@ export function RegisterForm() {
return (
-
-
-
)
}