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
12 changes: 11 additions & 1 deletion backend/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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
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
10 changes: 10 additions & 0 deletions backend/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Original file line number Diff line number Diff line change
@@ -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 = "b81f3c2a6d40"
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 ###
1 change: 1 addition & 0 deletions backend/app/auth/oauth/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""OAuth login integrations."""
249 changes: 249 additions & 0 deletions backend/app/auth/oauth/routes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,249 @@
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:
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()

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
2 changes: 1 addition & 1 deletion backend/app/auth/services.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 7 additions & 0 deletions backend/app/core/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 11 additions & 0 deletions backend/app/core/rate_limit.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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":
Expand Down
2 changes: 2 additions & 0 deletions backend/app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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")
Expand Down
Loading
Loading