Files
Business-Management/backend/app/routers/profile.py
T
curo1305 343f12259c Add profile feature, input sanitization, and stronger security checks
Backend:
- app/core/sanitize.py: shared sanitize_str, normalize_email, validate_phone,
  validate_date_of_birth — applied to every user-supplied DB-bound input
- app/schemas/user.py: sanitize full_name, normalize email on UserCreate
- app/models/profile.py: profiles table (position, phone, dob, address, updated_at)
- app/models/user.py: Profile back-ref, is_superuser admin-role comment
- app/schemas/profile.py: ProfileRead/ProfileUpdate with full sanitization
- app/routers/profile.py: GET+PUT /api/profile/me (lazy profile creation)
- app/main.py: register /api/profile router
- alembic migration 676084df61d1: create profiles table

Frontend:
- components/Nav.tsx: shared nav (Dashboard | Profile | Logout)
- pages/ProfilePage.tsx: profile view + inline edit form with error handling
- pages/DashboardPage.tsx: use Nav component
- api/client.ts: ProfileData type, getProfile, updateProfile
- App.tsx: /profile private route

Security:
- scripts/security_check.py: tighter SQL injection patterns (f-string/format/%
  in execute/query/text()), new SANIT category for raw request→DB patterns

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-13 18:15:47 +02:00

49 lines
1.5 KiB
Python

from fastapi import APIRouter, Depends
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.database import get_db
from app.deps import get_current_user
from app.models.profile import Profile
from app.models.user import User
from app.schemas.profile import ProfileRead, ProfileUpdate
router = APIRouter()
async def _get_or_create_profile(user: User, db: AsyncSession) -> Profile:
"""Return the user's profile, creating an empty one on first access."""
result = await db.execute(select(Profile).where(Profile.user_id == user.id))
profile = result.scalar_one_or_none()
if profile is None:
profile = Profile(user_id=user.id)
db.add(profile)
await db.commit()
await db.refresh(profile)
return profile
@router.get("/me", response_model=ProfileRead)
async def get_my_profile(
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
) -> Profile:
return await _get_or_create_profile(current_user, db)
@router.put("/me", response_model=ProfileRead)
async def update_my_profile(
body: ProfileUpdate,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
) -> Profile:
profile = await _get_or_create_profile(current_user, db)
# Only update fields that were explicitly provided in the request body.
for field, value in body.model_dump(exclude_unset=True).items():
setattr(profile, field, value)
await db.commit()
await db.refresh(profile)
return profile