diff --git a/backend/app/auth.py b/backend/app/auth.py new file mode 100644 index 0000000..63d9d34 --- /dev/null +++ b/backend/app/auth.py @@ -0,0 +1,43 @@ +from datetime import datetime, timedelta, timezone +from typing import Optional +from fastapi import Depends, HTTPException, status +from fastapi.security import OAuth2PasswordBearer +from jose import JWTError, jwt +from passlib.context import CryptContext +from pydantic import BaseModel +SECRET_KEY = 'change-me-in-production' +ALGORITHM = 'HS256' +ACCESS_TOKEN_EXPIRE_MINUTES = 120 +pwd_context = CryptContext(schemes=['bcrypt'], deprecated='auto') +oauth2_scheme = OAuth2PasswordBearer(tokenUrl='/auth/token') +class Token(BaseModel): access_token: str; token_type: str = 'bearer' +class TokenData(BaseModel): username: Optional[str] = None +class User(BaseModel): username: str; disabled: bool = False; role: str = 'viewer' +class UserInDB(User): hashed_password: str +fake_users_db = {'admin': {'username': 'admin', 'hashed_password': pwd_context.hash('admin123'), 'disabled': False, 'role': 'admin'}, 'viewer': {'username': 'viewer', 'hashed_password': pwd_context.hash('viewer123'), 'disabled': False, 'role': 'viewer'}} +def verify_password(plain_password: str, hashed_password: str) -> bool: return pwd_context.verify(plain_password, hashed_password) +def get_user(username: str) -> Optional[UserInDB]: + user = fake_users_db.get(username) + return UserInDB(**user) if user else None +def authenticate_user(username: str, password: str) -> Optional[UserInDB]: + user = get_user(username) + return user if user and verify_password(password, user.hashed_password) else None +def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str: + to_encode = data.copy() + expire = datetime.now(timezone.utc) + (expires_delta or timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)) + to_encode.update({'exp': expire}) + return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) +def get_current_user(token: str = Depends(oauth2_scheme)) -> User: + credentials_exception = HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail='Could not validate credentials', headers={'WWW-Authenticate': 'Bearer'}) + try: + payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) + username: str = payload.get('sub') + if username is None: raise credentials_exception + except JWTError: + raise credentials_exception + user = get_user(username) + if user is None: raise credentials_exception + return User(username=user.username, disabled=user.disabled, role=user.role) +def get_current_active_user(current_user: User = Depends(get_current_user)) -> User: + if current_user.disabled: raise HTTPException(status_code=400, detail='Inactive user') + return current_user diff --git a/backend/app/main.py b/backend/app/main.py index 09b0992..7f546f1 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -1,26 +1,9 @@ from fastapi import FastAPI -from fastapi.middleware.cors import CORSMiddleware +from app.routes.auth import router as auth_router -from app.routers.discoveries import router as discoveries_router -from app.routers.health import router as health_router -from app.routers.inventory import router as inventory_router -from app.routers.jobs import router as jobs_router -from app.routers.objects import router as objects_router -from app.routers.relations import router as relations_router +app = FastAPI(title='NetMapper API') +app.include_router(auth_router) -app = FastAPI(title='NetMapper Backend', version='0.1.0') - -app.add_middleware( - CORSMiddleware, - allow_origins=['*'], - allow_credentials=True, - allow_methods=['*'], - allow_headers=['*'], -) - -app.include_router(health_router) -app.include_router(objects_router) -app.include_router(jobs_router) -app.include_router(discoveries_router) -app.include_router(inventory_router) -app.include_router(relations_router) +@app.get('/health') +async def health(): + return {'status': 'ok'} diff --git a/backend/app/routes/__init__.py b/backend/app/routes/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/app/routes/auth.py b/backend/app/routes/auth.py new file mode 100644 index 0000000..25e7ac2 --- /dev/null +++ b/backend/app/routes/auth.py @@ -0,0 +1,14 @@ +from datetime import timedelta +from fastapi import APIRouter, Depends, HTTPException, status +from fastapi.security import OAuth2PasswordRequestForm +from app.auth import ACCESS_TOKEN_EXPIRE_MINUTES, Token, authenticate_user, create_access_token, get_current_active_user +router = APIRouter(prefix='/auth', tags=['auth']) +@router.post('/token', response_model=Token) +async def login(form_data: OAuth2PasswordRequestForm = Depends()): + user = authenticate_user(form_data.username, form_data.password) + if not user: raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail='Incorrect username or password') + access_token = create_access_token({'sub': user.username, 'role': user.role}, timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)) + return Token(access_token=access_token) +@router.get('/me') +async def me(current_user=Depends(get_current_active_user)): + return {'username': current_user.username, 'role': current_user.role, 'disabled': current_user.disabled} diff --git a/backend/requirements.txt b/backend/requirements.txt index e5f295d..3625ee8 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -1,6 +1,5 @@ -fastapi==0.115.0 -uvicorn[standard]==0.30.6 -pydantic==2.9.2 -sqlalchemy==2.0.35 -psycopg[binary]==3.2.3 -redis==5.1.1 +fastapi +uvicorn[standard] +python-jose[cryptography] +passlib[bcrypt] +python-multipart diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 2e8dd76..b31e258 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1,229 +1,20 @@ -import { useState } from 'react'; +import { useEffect, useState } from 'react'; import { InventoryPage } from './pages/InventoryPage'; +import { LoginPage } from './pages/LoginPage'; import './app-shell.css'; type TabKey = 'overview' | 'inventory' | 'discovery' | 'topology' | 'options'; - -const tabs: { key: TabKey; label: string; description: string }[] = [ +const tabs = [ { key: 'overview', label: 'Overview', description: 'Stato generale del workspace NetMapper.' }, { key: 'inventory', label: 'Inventory', description: 'Tree fisico/logico e navigazione tra oggetti.' }, { key: 'discovery', label: 'Discovery', description: 'Pipeline e job di raccolta dati.' }, { key: 'topology', label: 'Topology', description: 'Vista futura della mappa multilivello.' }, { key: 'options', label: 'Options', description: 'Utenti, impostazioni, servizi di sistema e sicurezza.' }, -]; - -function ShellCard({ title, children, tone = 'default' }: { title: string; children: React.ReactNode; tone?: 'default' | 'accent' | 'warning' }) { - return ( -
-
-

{title}

-
-
{children}
-
- ); -} - -function OverviewTab() { - return ( -
- - - - - - - - - -
- ); -} - -function DiscoveryTab() { - return ( -
- - - - - - -
- ); -} - -function TopologyTab() { - return ( -
- - - - - - -
- ); -} - -function OptionsTab() { - return ( -
-
- -
    -
  • Utenti locali e ruoli applicativi.
  • -
  • Disattivazione account inattivi o non più autorizzati.
  • -
  • Storico accessi e audit trail amministrativo.
  • -
-
- -
    -
  • Parametri workspace e branding dell'istanza.
  • -
  • Configurazione discovery, inventory e policy future.
  • -
  • Feature flags per moduli sperimentali.
  • -
-
-
- -
- -
    -
  • La sezione Servizi viene assorbita nel menu Options.
  • -
  • Qui confluiranno terminale remoto, job runner e integrazioni di sistema.
  • -
  • Ogni funzione sensibile dovrà essere protetta da permessi espliciti.
  • -
-
- -
    -
  • Login obbligatorio per tutte le viste non pubbliche.
  • -
  • MFA per admin e per funzioni ad alto impatto.
  • -
  • Controlli server-side su ogni richiesta, deny-by-default e audit centralizzato.
  • -
-
-
- - -
-
- 1 -
- Authentication foundation -

Sessioni sicure, logout reale, protezione delle rotte e bootstrap identità all'avvio.

-
-
-
- 2 -
- Authorization model -

Ruoli base, policy per risorse sensibili e blocco di azioni per utenti non autorizzati.

-
-
-
- 3 -
- Remote access hardening -

Prima di un modulo tipo Termix: MFA, audit, approvazione esplicita e tracciamento comandi.

-
-
-
-
-
- ); -} - -function App() { - const [activeTab, setActiveTab] = useState('inventory'); - const currentTab = tabs.find((tab) => tab.key === activeTab)!; - - return ( -
- - -
-
-
-

{currentTab.label}

-

{currentTab.description}

-
-
- Book of truth - Auth roadmap -
-
- -
- -
-
- -
-
- -
-
- -
-
- -
-
-
- ); -} - -export default App; +] as const; +function ShellCard({ title, children, tone = 'default' }: { title: string; children: React.ReactNode; tone?: 'default' | 'accent' | 'warning' }) { return

{title}

{children}
; } +function OverviewTab(){ return
  • Frontend inventory collegato al backend.
  • Tree gerarchico e context panel attivi.
  • Navigazione tra parent, children e relazioni disponibile.
  • Reintegro layout persistente completato.
  • Roadmap di security e options introdotta.
  • Preparazione vista topology multilivello.
  • I moduli servizi confluiranno nel menu Options.
  • L'accesso dovrà essere autenticato prima delle integrazioni remote.
  • Serve hardening progressivo di sessione e permessi.
; } +function DiscoveryTab(){ return
  • Seed scan subnet.
  • Classificazione host e object binding.
  • Correlazione con relazioni inventory.
  • SNMP collector.
  • LLDP ingestion.
  • Port mapping inference.
; } +function TopologyTab(){ return
  • Vista fisica dispositivi.
  • Vista logica host / VM / container / app.
  • Layer networking e dipendenze.
  • Drag & drop dei contenitori.
  • Link fisici e logici cliccabili.
  • Focus node e highlight dei vicini.
; } +function OptionsTab(){ return
  • Utenti locali e ruoli applicativi.
  • Disattivazione account inattivi o non più autorizzati.
  • Storico accessi e audit trail amministrativo.
  • Parametri workspace e branding dell'istanza.
  • Configurazione discovery, inventory e policy future.
  • Feature flags per moduli sperimentali.
  • La sezione Servizi viene assorbita nel menu Options.
  • Qui confluiranno terminale remoto, job runner e integrazioni di sistema.
  • Ogni funzione sensibile dovrà essere protetta da permessi espliciti.
  • Login obbligatorio per tutte le viste non pubbliche.
  • MFA per admin e per funzioni ad alto impatto.
  • Controlli server-side su ogni richiesta, deny-by-default e audit centralizzato.
; } +function AppShell(){ const [activeTab,setActiveTab]=useState('inventory'); const currentTab=tabs.find((t)=>t.key===activeTab)!; return

{currentTab.label}

{currentTab.description}

Book of truthAuth roadmap
; } +export default function App(){ const [token,setToken]=useState(null); useEffect(()=>{const t=window.localStorage.getItem('nm_token'); if(t) setToken(t);},[]); const login=(nextToken:string)=>{window.localStorage.setItem('nm_token', nextToken); setToken(nextToken);}; const logout=()=>{window.localStorage.removeItem('nm_token'); setToken(null);}; if(!token) return ; return <>; } diff --git a/frontend/src/app-shell.css b/frontend/src/app-shell.css index a22ad5f..40054bc 100644 --- a/frontend/src/app-shell.css +++ b/frontend/src/app-shell.css @@ -1,207 +1,39 @@ -:root { - color-scheme: dark; - font-family: Inter, system-ui, sans-serif; - background: #0b1020; -} - -body { - margin: 0; - background: linear-gradient(180deg, #0b1020 0%, #111827 100%); - color: #e5e7eb; -} - -#root { - min-height: 100vh; -} - -.app-shell { - display: grid; - grid-template-columns: 280px minmax(0, 1fr); - min-height: 100vh; -} - -.app-sidebar { - border-right: 1px solid rgba(255,255,255,0.08); - background: rgba(2, 6, 23, 0.75); - backdrop-filter: blur(14px); - padding: 20px; - display: flex; - flex-direction: column; - gap: 20px; -} - -.app-brand { - display: flex; - align-items: center; - gap: 12px; -} - -.app-brand-mark { - width: 42px; - height: 42px; - border-radius: 12px; - display: grid; - place-items: center; - background: linear-gradient(135deg, #1d4ed8, #2563eb); - color: white; - font-weight: 700; -} - -.app-brand h1, -.app-header h2, -.shell-card h3 { - margin: 0; -} - -.app-brand p, -.app-header p { - margin: 4px 0 0; - color: #94a3b8; -} - -.app-nav { - display: flex; - flex-direction: column; - gap: 10px; -} - -.app-nav-item { - border: 1px solid rgba(255,255,255,0.08); - background: rgba(255,255,255,0.03); - border-radius: 12px; - padding: 12px 14px; - color: #e5e7eb; - text-align: left; - cursor: pointer; - display: flex; - flex-direction: column; - gap: 4px; -} - -.app-nav-item.active { - background: rgba(37, 99, 235, 0.16); - border-color: rgba(96, 165, 250, 0.35); -} - -.app-nav-item small { - color: #94a3b8; -} - -.app-sidebar-footer, -.app-header-actions { - display: flex; - flex-wrap: wrap; - gap: 8px; -} - -.app-main { - padding: 20px; -} - -.app-header { - display: flex; - justify-content: space-between; - align-items: flex-start; - gap: 16px; - margin-bottom: 20px; -} - -.shell-pill { - display: inline-flex; - align-items: center; - padding: 6px 10px; - border-radius: 999px; - background: rgba(255,255,255,0.08); - color: #cbd5e1; - font-size: 12px; -} - -.shell-grid { - display: grid; - grid-template-columns: repeat(3, minmax(0, 1fr)); - gap: 16px; -} - -.shell-grid.two-columns { - grid-template-columns: repeat(2, minmax(0, 1fr)); -} - -.shell-stack { - display: grid; - gap: 16px; -} - -.shell-card { - background: rgba(17, 24, 39, 0.88); - border: 1px solid rgba(255,255,255,0.08); - border-radius: 16px; - padding: 16px; -} - -.shell-card.accent { - border-color: rgba(96, 165, 250, 0.35); -} - -.shell-card.warning { - border-color: rgba(251, 191, 36, 0.35); -} - -.shell-card-body { - margin-top: 12px; -} - -.shell-list { - margin: 0; - padding-left: 18px; - display: grid; - gap: 8px; - color: #cbd5e1; -} - -.options-roadmap { - display: grid; - gap: 12px; -} - -.options-roadmap-item { - display: grid; - grid-template-columns: 40px minmax(0, 1fr); - gap: 12px; - align-items: start; - padding: 12px; - border-radius: 12px; - background: rgba(255,255,255,0.03); - border: 1px solid rgba(255,255,255,0.06); -} - -.options-roadmap-item p { - margin: 6px 0 0; - color: #94a3b8; -} - -.options-step { - width: 32px; - height: 32px; - border-radius: 999px; - display: grid; - place-items: center; - background: rgba(37, 99, 235, 0.18); - color: #bfdbfe; - font-weight: 700; -} - -@media (max-width: 1100px) { - .app-shell { - grid-template-columns: 1fr; - } - - .app-sidebar { - border-right: 0; - border-bottom: 1px solid rgba(255,255,255,0.08); - } - - .shell-grid, - .shell-grid.two-columns { - grid-template-columns: 1fr; - } -} +:root { color-scheme: dark; font-family: Inter, system-ui, sans-serif; background: #0b1020; } +body { margin: 0; background: linear-gradient(180deg, #0b1020 0%, #111827 100%); color: #e5e7eb; } +#root { min-height: 100vh; } +.logout-button { position: fixed; top: 16px; right: 16px; z-index: 50; border: 1px solid rgba(255,255,255,0.08); background: rgba(17,24,39,0.88); color: #e5e7eb; border-radius: 999px; padding: 10px 14px; } +.app-shell { display: grid; grid-template-columns: 280px minmax(0, 1fr); min-height: 100vh; } +.app-sidebar { border-right: 1px solid rgba(255,255,255,0.08); background: rgba(2, 6, 23, 0.75); backdrop-filter: blur(14px); padding: 20px; display: flex; flex-direction: column; gap: 20px; } +.app-brand { display: flex; align-items: center; gap: 12px; } +.app-brand-mark { width: 42px; height: 42px; border-radius: 12px; display: grid; place-items: center; background: linear-gradient(135deg, #1d4ed8, #2563eb); color: white; font-weight: 700; } +.app-brand h1, .app-header h2, .shell-card h3 { margin: 0; } +.app-brand p, .app-header p { margin: 4px 0 0; color: #94a3b8; } +.app-nav { display: flex; flex-direction: column; gap: 10px; } +.app-nav-item { border: 1px solid rgba(255,255,255,0.08); background: rgba(255,255,255,0.03); border-radius: 12px; padding: 12px 14px; color: #e5e7eb; text-align: left; cursor: pointer; display: flex; flex-direction: column; gap: 4px; } +.app-nav-item.active { background: rgba(37, 99, 235, 0.16); border-color: rgba(96, 165, 250, 0.35); } +.app-nav-item small { color: #94a3b8; } +.app-sidebar-footer, .app-header-actions { display: flex; flex-wrap: wrap; gap: 8px; } +.app-main { padding: 20px; } +.app-header { display: flex; justify-content: space-between; align-items: flex-start; gap: 16px; margin-bottom: 20px; } +.shell-pill { display: inline-flex; align-items: center; padding: 6px 10px; border-radius: 999px; background: rgba(255,255,255,0.08); color: #cbd5e1; font-size: 12px; } +.shell-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 16px; } +.shell-grid.two-columns { grid-template-columns: repeat(2, minmax(0, 1fr)); } +.shell-stack { display: grid; gap: 16px; } +.shell-card { background: rgba(17, 24, 39, 0.88); border: 1px solid rgba(255,255,255,0.08); border-radius: 16px; padding: 16px; } +.shell-card.accent { border-color: rgba(96, 165, 250, 0.35); } +.shell-card.warning { border-color: rgba(251, 191, 36, 0.35); } +.shell-card-body { margin-top: 12px; } +.shell-list { margin: 0; padding-left: 18px; display: grid; gap: 8px; color: #cbd5e1; } +.options-roadmap { display: grid; gap: 12px; } +.options-roadmap-item { display: grid; grid-template-columns: 40px minmax(0, 1fr); gap: 12px; align-items: start; padding: 12px; border-radius: 12px; background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.06); } +.options-roadmap-item p { margin: 6px 0 0; color: #94a3b8; } +.options-step { width: 32px; height: 32px; border-radius: 999px; display: grid; place-items: center; background: rgba(37, 99, 235, 0.18); color: #bfdbfe; font-weight: 700; } +.login-page { min-height: 100vh; display: grid; place-items: center; padding: 24px; } +.login-card { width: min(100%, 420px); background: rgba(17,24,39,0.92); border: 1px solid rgba(255,255,255,0.08); border-radius: 20px; padding: 24px; } +.login-eyebrow { color: #93c5fd; text-transform: uppercase; letter-spacing: 0.12em; font-size: 12px; } +.login-copy, .login-error { color: #94a3b8; } +.login-form { display: grid; gap: 12px; margin-top: 16px; } +.login-form label { display: grid; gap: 6px; } +.login-form input { border: 1px solid rgba(255,255,255,0.1); background: rgba(255,255,255,0.03); border-radius: 12px; padding: 12px 14px; } +.login-form button { border: 0; border-radius: 12px; padding: 12px 14px; background: #2563eb; color: white; font-weight: 600; } +@media (max-width: 1100px) { .app-shell { grid-template-columns: 1fr; } .app-sidebar { border-right: 0; border-bottom: 1px solid rgba(255,255,255,0.08); } .shell-grid, .shell-grid.two-columns { grid-template-columns: 1fr; } } diff --git a/frontend/src/lib/session.ts b/frontend/src/lib/session.ts new file mode 100644 index 0000000..38b20ab --- /dev/null +++ b/frontend/src/lib/session.ts @@ -0,0 +1,2 @@ +export type SessionUser = { username: string; role: string } | null; +export function getSessionUser(): SessionUser { return null; } diff --git a/frontend/src/pages/LoginPage.tsx b/frontend/src/pages/LoginPage.tsx new file mode 100644 index 0000000..dab8b44 --- /dev/null +++ b/frontend/src/pages/LoginPage.tsx @@ -0,0 +1,19 @@ +import { useState } from 'react'; + +type Props = { onLogin: (token: string) => void }; +export function LoginPage({ onLogin }: Props) { + const [username, setUsername] = useState('admin'); + const [password, setPassword] = useState('admin123'); + const [error, setError] = useState(''); + const [loading, setLoading] = useState(false); + const submit = async (e: React.FormEvent) => { + e.preventDefault(); setLoading(true); setError(''); + try { + const body = new URLSearchParams(); body.set('username', username); body.set('password', password); + const res = await fetch('/auth/token', { method: 'POST', body }); + if (!res.ok) throw new Error('Login fallito'); + const data = await res.json(); onLogin(data.access_token); + } catch (err) { setError(err instanceof Error ? err.message : 'Login fallito'); } finally { setLoading(false); } + }; + return

NetMapper auth

Accedi al book of truth

L'accesso è protetto per impedire lettura e modifica dei dati da terzi.

{error &&

{error}

}
; +}