From 4c4b3768a8f2b482f71598e56e44fbebace87cff Mon Sep 17 00:00:00 2001 From: joaothuguenin Date: Sat, 3 Oct 2026 21:16:50 -0300 Subject: [PATCH 1/2] feat: implementada a feature de alteracao de nome de perfil --- .../users/integration/test_user_routes.py | 174 +++++++++++++++++ backend/app/users/routes.py | 24 ++- backend/app/users/schemas.py | 9 + frontend/src/features/auth/api.ts | 9 + frontend/src/features/auth/auth-provider.tsx | 8 +- .../profile/components/profile-identity.tsx | 184 ++++++++++++++++++ .../profile/components/profile-page.tsx | 34 +--- 7 files changed, 408 insertions(+), 34 deletions(-) create mode 100644 backend/app/tests/users/integration/test_user_routes.py create mode 100644 frontend/src/features/profile/components/profile-identity.tsx diff --git a/backend/app/tests/users/integration/test_user_routes.py b/backend/app/tests/users/integration/test_user_routes.py new file mode 100644 index 00000000..97b6461a --- /dev/null +++ b/backend/app/tests/users/integration/test_user_routes.py @@ -0,0 +1,174 @@ +"""Testes dos endpoints de usuário autenticado (/api/v1/user/me).""" + +from __future__ import annotations + +import pytest +from sqlalchemy.ext.asyncio import AsyncSession + +from app.auth import services as auth_services +from app.auth.scopes import Scope +from app.auth.security import verify_password + +URL = "/api/v1/user/me" + + +def _auth(user, scopes=(Scope.PROFILE, Scope.EMAIL)) -> dict[str, str]: + token = auth_services.create_access_token(user.id, list(scopes)) + return {"Authorization": f"Bearer {token}"} + + +# --------------------------------------------------------------------------- +# Proteção +# --------------------------------------------------------------------------- + + +async def test_update_name_without_authorization_returns_401(db_client): + r = await db_client.patch(URL, json={"name": "Novo Nome"}) + assert r.status_code == 401 + + +async def test_update_name_without_profile_scope_returns_401( + db_client, regular_user, db_session: AsyncSession +): + original_name = regular_user.name + + r = await db_client.patch( + URL, json={"name": "Novo Nome"}, headers=_auth(regular_user, [Scope.EMAIL]) + ) + + assert r.status_code == 401 + await db_session.refresh(regular_user) + assert regular_user.name == original_name + + +async def test_update_name_of_deleted_user_returns_401(db_client, deleted_user_factory): + deleted = await deleted_user_factory() + + r = await db_client.patch(URL, json={"name": "Novo Nome"}, headers=_auth(deleted)) + + assert r.status_code == 401 + + +# --------------------------------------------------------------------------- +# Sucesso +# --------------------------------------------------------------------------- + + +async def test_user_can_update_own_name( + db_client, regular_user, db_session: AsyncSession +): + r = await db_client.patch( + URL, json={"name": "Ada Lovelace"}, headers=_auth(regular_user) + ) + + assert r.status_code == 200, r.text + body = r.json() + assert body["name"] == "Ada Lovelace" + assert body["id"] == str(regular_user.id) + assert body["email"] == regular_user.email + assert "password" not in body and "password_hash" not in body + + await db_session.refresh(regular_user) + assert regular_user.name == "Ada Lovelace" + + +async def test_updated_name_is_returned_by_me_endpoint(db_client, regular_user): + headers = _auth(regular_user) + + await db_client.patch(URL, json={"name": "Grace Hopper"}, headers=headers) + r = await db_client.get("/api/v1/auth/me", headers=headers) + + assert r.status_code == 200, r.text + assert r.json()["name"] == "Grace Hopper" + + +async def test_update_name_strips_surrounding_whitespace(db_client, regular_user): + r = await db_client.patch( + URL, json={"name": " Linus Torvalds "}, headers=_auth(regular_user) + ) + + assert r.status_code == 200, r.text + assert r.json()["name"] == "Linus Torvalds" + + +async def test_update_name_accepts_max_length(db_client, regular_user): + name = "a" * 255 + + r = await db_client.patch(URL, json={"name": name}, headers=_auth(regular_user)) + + assert r.status_code == 200, r.text + assert r.json()["name"] == name + + +async def test_update_name_does_not_change_other_fields( + db_client, regular_user, db_session: AsyncSession +): + email = regular_user.email + password_hash = regular_user.password_hash + + r = await db_client.patch( + URL, json={"name": "Outro Nome"}, headers=_auth(regular_user) + ) + + assert r.status_code == 200, r.text + await db_session.refresh(regular_user) + assert regular_user.email == email + assert regular_user.password_hash == password_hash + assert verify_password("password123", regular_user.password_hash) + assert regular_user.is_admin is False + assert regular_user.is_verified is False + + +# --------------------------------------------------------------------------- +# Validação +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "payload", + [ + {}, + {"name": None}, + {"name": ""}, + {"name": " "}, + {"name": "a" * 256}, + {"name": 123}, + ], +) +async def test_update_name_rejects_invalid_name( + db_client, regular_user, db_session: AsyncSession, payload +): + original_name = regular_user.name + + r = await db_client.patch(URL, json=payload, headers=_auth(regular_user)) + + assert r.status_code == 422 + await db_session.refresh(regular_user) + assert regular_user.name == original_name + + +@pytest.mark.parametrize( + "extra", + [ + {"email": "hacker@example.com"}, + {"password": "brand-new-pass"}, + {"is_admin": True}, + {"is_verified": True}, + ], +) +async def test_update_name_rejects_other_fields( + db_client, regular_user, db_session: AsyncSession, extra +): + email = regular_user.email + original_name = regular_user.name + + r = await db_client.patch( + URL, json={"name": "Novo Nome", **extra}, headers=_auth(regular_user) + ) + + assert r.status_code == 422 + await db_session.refresh(regular_user) + assert regular_user.email == email + assert regular_user.name == original_name + assert regular_user.is_admin is False + assert regular_user.is_verified is False diff --git a/backend/app/users/routes.py b/backend/app/users/routes.py index f5d42a9b..d6ca43b3 100644 --- a/backend/app/users/routes.py +++ b/backend/app/users/routes.py @@ -1,11 +1,15 @@ from typing import Annotated -from fastapi import APIRouter, Depends, status +from fastapi import APIRouter, Depends, Security, status from sqlalchemy.ext.asyncio import AsyncSession +from app.auth.dependencies import get_current_user +from app.auth.scopes import Scope from app.core.database import get_session +from app.core.exceptions.app_errors import UnauthorizedError from app.users import services -from app.users.schemas import UserCreate +from app.users.models import User +from app.users.schemas import UserCreate, UserMe, UserNameUpdate, UserUpdate router = APIRouter(tags=["user"]) @@ -18,3 +22,19 @@ async def signup_with_password( user = await services.create_user(db_session, user_info) return user + + +@router.patch("/me", response_model=UserMe) +async def update_my_name( + db_session: Annotated[AsyncSession, Depends(get_session)], + current_user: Annotated[User, Security(get_current_user, scopes=[Scope.PROFILE])], + user_in: UserNameUpdate, +): + """Altera o nome do usuário autenticado. O e-mail não pode ser alterado aqui.""" + await services.update_user(db_session, current_user, UserUpdate(name=user_in.name)) + await db_session.commit() + + user = await services.get_user_profile_by_id(db_session, current_user.id) + if user is None: + raise UnauthorizedError(detail="Inexistent or inactive user") + return user diff --git a/backend/app/users/schemas.py b/backend/app/users/schemas.py index 44d2a355..9061db45 100644 --- a/backend/app/users/schemas.py +++ b/backend/app/users/schemas.py @@ -30,6 +30,15 @@ class UserUpdate(BaseModel): password: Password | None = None +class UserNameUpdate(BaseModel): + # alteração do próprio nome pelo usuário autenticado: nome obrigatório e + # nenhum outro campo aceito (e-mail, senha e privilégios não podem ser + # alterados por esta via) + model_config = ConfigDict(extra="forbid") + + name: Name + + class AdminUserCreate(UserCreate): # criação feita por um admin: pode definir os privilégios já na criação is_admin: bool = False diff --git a/frontend/src/features/auth/api.ts b/frontend/src/features/auth/api.ts index d1b22abf..e883d153 100644 --- a/frontend/src/features/auth/api.ts +++ b/frontend/src/features/auth/api.ts @@ -93,6 +93,15 @@ export async function getCurrentUser(): Promise { return mapUser(await requestApi('/auth/me')) } +export async function updateMyName(name: string): Promise { + return mapUser( + await requestApi('/user/me', { + method: 'PATCH', + body: JSON.stringify({ name }), + }), + ) +} + export async function restoreSession(): Promise { try { await refresh() diff --git a/frontend/src/features/auth/auth-provider.tsx b/frontend/src/features/auth/auth-provider.tsx index f7a2f0d1..4a7cafef 100644 --- a/frontend/src/features/auth/auth-provider.tsx +++ b/frontend/src/features/auth/auth-provider.tsx @@ -9,7 +9,7 @@ import { type ReactNode, } from 'react' -import { login, logout, register, restoreSession } from './api' +import { login, logout, register, restoreSession, updateMyName } from './api' import type { LoginInput, RegisterInput, User } from './types' type AuthContextValue = { @@ -18,6 +18,7 @@ type AuthContextValue = { login: (input: LoginInput) => Promise register: (input: RegisterInput) => Promise logout: () => Promise + updateName: (name: string) => Promise } const AuthContext = createContext(null) @@ -51,6 +52,11 @@ export function AuthProvider({ children }: { children: ReactNode }) { await logout() setUser(null) }, + async updateName(name) { + const updated = await updateMyName(name) + setUser(updated) + return updated + }, }), [loading, user], ) diff --git a/frontend/src/features/profile/components/profile-identity.tsx b/frontend/src/features/profile/components/profile-identity.tsx new file mode 100644 index 00000000..f59c032a --- /dev/null +++ b/frontend/src/features/profile/components/profile-identity.tsx @@ -0,0 +1,184 @@ +'use client' + +import { zodResolver } from '@hookform/resolvers/zod' +import { CheckCircle2, Mail, Pencil } from 'lucide-react' +import { useState } from 'react' +import { useForm } from 'react-hook-form' +import { z } from 'zod' + +import { Avatar, AvatarFallback } from '@/components/ui/avatar' +import { Button } from '@/components/ui/button' +import { + Form, + FormControl, + FormField, + FormItem, + FormLabel, + FormMessage, +} from '@/components/ui/form' +import { Label } from '@/components/ui/label' +import { useAuth } from '@/features/auth/auth-provider' +import type { User } from '@/features/auth/types' +import { SemanaButton } from '@/features/semana/components/semana-button' +import { SemanaInput } from '@/features/semana/components/semana-input' + +// Same rules as the backend: required after trimming, at most 255 characters. +const schema = z.object({ + name: z + .string() + .trim() + .min(1, 'Digite seu nome.') + .max(255, 'O nome deve ter no máximo 255 caracteres.'), +}) + +type Values = z.infer + +function initials(name: string) { + return name + .split(' ') + .slice(0, 2) + .map((part) => part[0]) + .join('') + .toUpperCase() +} + +export function ProfileIdentity({ user }: { user: User }) { + const { updateName } = useAuth() + const [editing, setEditing] = useState(false) + const [saved, setSaved] = useState(false) + const [error, setError] = useState() + const form = useForm({ + resolver: zodResolver(schema), + defaultValues: { name: user.name }, + }) + + function startEditing() { + form.reset({ name: user.name }) + setError(undefined) + setSaved(false) + setEditing(true) + } + + function cancelEditing() { + setError(undefined) + setEditing(false) + } + + async function submit(values: Values) { + setError(undefined) + + if (values.name === user.name) { + setEditing(false) + return + } + + try { + await updateName(values.name) + setSaved(true) + setEditing(false) + } catch { + setError('Não foi possível salvar seu nome. Tente novamente.') + } + } + + return ( +
+
+ + + {initials(user.name)} + + +
+

{user.name}

+

+

+
+ + +
+ + {editing ? ( +
+ + ( + + Nome + + + + + + )} + /> +
+ + +

+ O e-mail não pode ser alterado. +

+
+ {error && ( +

+ {error} +

+ )} +
+ + {form.formState.isSubmitting ? 'Salvando…' : 'Salvar'} + + +
+ + + ) : ( +
+ +

+ {saved && ( + <> +

+
+ )} +
+ ) +} diff --git a/frontend/src/features/profile/components/profile-page.tsx b/frontend/src/features/profile/components/profile-page.tsx index d434a7a9..5e94a111 100644 --- a/frontend/src/features/profile/components/profile-page.tsx +++ b/frontend/src/features/profile/components/profile-page.tsx @@ -1,22 +1,13 @@ 'use client' -import { CalendarCheck, CheckCircle2, Clock3, Mail, Trophy } from 'lucide-react' +import { CalendarCheck, Clock3, Trophy } from 'lucide-react' import { useRouter } from 'next/navigation' import { useEffect, useState } from 'react' -import { Avatar, AvatarFallback } from '@/components/ui/avatar' import { useAuth } from '@/features/auth/auth-provider' +import { ProfileIdentity } from '@/features/profile/components/profile-identity' import { getMyParticipation, type Participation } from '@/features/semana/api' -function initials(name: string) { - return name - .split(' ') - .slice(0, 2) - .map((part) => part[0]) - .join('') - .toUpperCase() -} - export function ProfilePage() { const router = useRouter() const { user, loading } = useAuth() @@ -53,26 +44,7 @@ export function ProfilePage() { -
-
- - - {initials(user.name)} - - -
-

{user.name}

-

-

-
- - -
-
+
From b173523d50ecafd69a572dcb93d965421b7aa033 Mon Sep 17 00:00:00 2001 From: wate Date: Sun, 4 Oct 2026 10:32:39 -0300 Subject: [PATCH 2/2] fix(auth): require email scope for profile update Co-authored-by: Codex --- .../tests/users/integration/test_user_routes.py | 14 ++++++++++++++ backend/app/users/routes.py | 4 +++- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/backend/app/tests/users/integration/test_user_routes.py b/backend/app/tests/users/integration/test_user_routes.py index 97b6461a..c2dfc802 100644 --- a/backend/app/tests/users/integration/test_user_routes.py +++ b/backend/app/tests/users/integration/test_user_routes.py @@ -41,6 +41,20 @@ async def test_update_name_without_profile_scope_returns_401( assert regular_user.name == original_name +async def test_update_name_without_email_scope_returns_401( + db_client, regular_user, db_session: AsyncSession +): + original_name = regular_user.name + + r = await db_client.patch( + URL, json={"name": "Novo Nome"}, headers=_auth(regular_user, [Scope.PROFILE]) + ) + + assert r.status_code == 401 + await db_session.refresh(regular_user) + assert regular_user.name == original_name + + async def test_update_name_of_deleted_user_returns_401(db_client, deleted_user_factory): deleted = await deleted_user_factory() diff --git a/backend/app/users/routes.py b/backend/app/users/routes.py index d6ca43b3..ab700632 100644 --- a/backend/app/users/routes.py +++ b/backend/app/users/routes.py @@ -27,7 +27,9 @@ async def signup_with_password( @router.patch("/me", response_model=UserMe) async def update_my_name( db_session: Annotated[AsyncSession, Depends(get_session)], - current_user: Annotated[User, Security(get_current_user, scopes=[Scope.PROFILE])], + current_user: Annotated[ + User, Security(get_current_user, scopes=[Scope.PROFILE, Scope.EMAIL]) + ], user_in: UserNameUpdate, ): """Altera o nome do usuário autenticado. O e-mail não pode ser alterado aqui."""