loreal-utilisation-dept/backend/app/auth/local.py
DJP 993e370cea feat: Forecast, Project Type Summary, Time Log Detail, AI Chat, filters v2, stats bar, RBAC
Brings the new app to full parity with the original L'Oréal SPA and
beyond. Backend 59/59 tests (was 40, +19). Frontend typecheck/lint/build
clean. Main entry chunk 15.76 KB gz (budget 30 KB).

Backend — new endpoints + services:
- POST /api/deliverable/parse        — parse Deliverable Summary CSV/XLSX
- POST /api/projectsummary/parse     — parse Project Summary CSV/XLSX
- GET  /api/timelog/rows             — paginated, searchable, sortable view
                                        over the parsed Zoho upload
- GET  /api/forecast                 — 4-week pipeline + capacity decision
- GET  /api/project-types            — hours/asset, duration, concentration
                                        per project type + auto-insights
- POST /api/chat                     — Claude API proxy. 503s gracefully
                                        when ANTHROPIC_API_KEY is unset.
                                        Prompt-cached system prompt;
                                        rate-limited 20/min/IP.
- GET  /api/auth/me now returns role.

Backend — services:
- zoho_parse.py: extracts ~20 fields (brand, division, hub, userRole,
  projectType, assetCount, projectStatus, project start/end dates,
  userAgency, employingCompany, sageJobProfile, …) with back-compat
  aliases so existing callers keep working.
- parse_store.py: in-process TTL-cached registry of parsed uploads keyed
  by content hash. Lets endpoints reference an upload without re-sending it.
- forecast.py: working-day overlap math, exit-rate, weekly throughput
  baseline, capacity decision string mirroring the original wording.
- project_types.py: per-type aggregation + concentration-risk insights.
- timelog_filters.py: server-side filter by brands/divisions/hubs/roles.
- ai_context.py: builds the dashboard context block fed to Claude.

Frontend — new pages + components:
- pages/Forecast.tsx                 — ComposedChart (stacked bars + line)
                                        + capacity-decision banner + table
- pages/ProjectTypeSummary.tsx       — sortable table + small trend chart
- pages/TimeLogDetail.tsx            — virtualised, searchable, sortable
                                        view over all parsed timelog rows
- components/ChatView.tsx            — floating side panel with Claude.
                                        6 preset prompts mirroring the
                                        original. Visible only for roles
                                        with chat access.
- components/ChatToggle.tsx          — bottom-right FAB.
- components/StatsBar.tsx            — always-visible: Time Entries /
                                        People / Projects / Total Hours /
                                        Date Range.
- hooks/useDataContext.tsx           — single source of truth for filter
                                        state + parsed upload + filter
                                        dimensions (brands/divs/hubs/
                                        roles derived from uploads).

Frontend — modified:
- App.tsx, Navbar.tsx                — 7 tabs + role gating per the
                                        original TAB_ACCESS matrix.
- hooks/useAuth.tsx                  — role + canAccess(tab).
- lib/filters.ts, FilterBar.tsx      — Brand / Division / Hub / Role
                                        multiselects added (additive — keep
                                        Department / Name / Billing).
- pages/Department, Resourcing,
  Bookings, Tutorial.tsx             — wired into DataContext; tutorial
                                        is now a single 9-step global tour
                                        mirroring the original's narrative.

Config:
- backend/.env.example: ADMIN_ROLE, ANTHROPIC_API_KEY, ANTHROPIC_MODEL.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-17 21:40:03 -04:00

51 lines
1.8 KiB
Python

"""Local auth — bcrypt-verified admin credential plus session-cookie check.
Decisions:
- passlib's bcrypt backend is used so we don't depend on the (deprecated)
bcrypt package interface details directly.
- DEV_AUTH_BYPASS short-circuits to a synthetic user; main.py logs a
WARNING at startup if it's enabled.
- verify_password and verify_session are both safe to call when
ADMIN_PASSWORD_BCRYPT is empty — they just return False / 401.
"""
from __future__ import annotations
from typing import Any
from fastapi import HTTPException, Request, status
from passlib.context import CryptContext
from app.auth.session import COOKIE_NAME, verify_signed
from app.config import settings
_pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
def verify_password(username: str, password: str) -> bool:
if not settings.ADMIN_PASSWORD_BCRYPT:
return False
if username != settings.ADMIN_USERNAME:
return False
try:
return _pwd_context.verify(password, settings.ADMIN_PASSWORD_BCRYPT)
except Exception:
# passlib raises on malformed hashes — treat as auth failure.
return False
def verify_session(request: Request) -> dict[str, Any]:
"""FastAPI dependency: returns {"username": ..., "mode": ..., "role": ...} or 401."""
if settings.DEV_AUTH_BYPASS:
return {"username": "dev", "mode": "bypass", "role": settings.ADMIN_ROLE}
cookie = request.cookies.get(COOKIE_NAME)
if not cookie:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Not authenticated")
username = verify_signed(cookie)
if not username:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Session expired")
return {"username": username, "mode": "local", "role": settings.ADMIN_ROLE}