Files
headroom/app/auth.py
kristianwind 15bbe02277 Headroom: homelab capacity dashboard
- FastAPI app med 7 bundled module-typer (proxmox, esxi, truenas, splunk, linux, windows, http-json)
- Multi-instance support: flere instanser af samme modultype med adskilte assets
- Community/Enterprise licensing med admin enterprise-toggle
- Capacity forecasting, trends, what-if simulator, alert policies
- MCP server + LLM copilot integration
- Dockerfile + rune.yaml til Yggdrasil
2026-10-23 22:39:27 +02:00

152 lines
5.5 KiB
Python

"""Authentication: local users, signed session cookies and API keys."""
from __future__ import annotations
import time
from typing import Any, Dict, Optional
from fastapi import Depends, HTTPException, Request, Response
from . import db, licensing
from .util import now_iso
from .security import (
SESSION_TTL,
api_key_prefix,
hash_api_key,
sign_session,
verify_password,
verify_session,
)
COOKIE_NAME = "hr_session"
LOGIN_WINDOW = 300
LOGIN_LIMIT = 15
_ATTEMPTS: Dict[str, list] = {}
def _client_ip(request: Request) -> str:
return request.client.host if request.client else "unknown"
def login(username: str, password: str, request: Request, response: Response) -> Dict[str, Any]:
ip = _client_ip(request)
now = time.time()
attempts = [stamp for stamp in _ATTEMPTS.get(ip, []) if now - stamp < LOGIN_WINDOW]
if len(attempts) >= LOGIN_LIMIT:
raise HTTPException(status_code=429, detail="Too many login attempts. Wait a few minutes.")
row = db.query_one("SELECT * FROM users WHERE username=?", (username.strip(),))
if not row or not verify_password(password, row["password_hash"]):
attempts.append(now)
_ATTEMPTS[ip] = attempts
raise HTTPException(status_code=401, detail="Invalid username or password")
_ATTEMPTS.pop(ip, None)
token = sign_session(int(row["id"]))
response.set_cookie(
COOKIE_NAME,
token,
max_age=SESSION_TTL,
httponly=True,
samesite="lax",
path="/",
)
db.audit(row["username"], "login", target=ip)
return {"id": row["id"], "username": row["username"], "role": row["role"]}
def logout(response: Response) -> None:
response.delete_cookie(COOKIE_NAME, path="/")
def _api_key_user(request: Request) -> Optional[Dict[str, Any]]:
candidate = request.headers.get("x-api-key", "")
authorization = request.headers.get("authorization", "")
if not candidate and authorization.lower().startswith("bearer "):
token = authorization[7:].strip()
if token.startswith("hr_"):
candidate = token
if not candidate.startswith("hr_"):
return None
row = db.query_one("SELECT * FROM api_keys WHERE key_hash=?", (hash_api_key(candidate),))
if not row:
return None
db.execute("UPDATE api_keys SET last_used=? WHERE id=?", (now_iso(), row["id"]))
return {
"id": 0,
"username": f"api:{row['name']}",
"role": row["role"],
"auth": "api_key",
"api_key_id": row["id"],
}
def current_user(request: Request) -> Dict[str, Any]:
api_user = _api_key_user(request)
if api_user:
return api_user
token = request.cookies.get(COOKIE_NAME, "")
if not token:
authorization = request.headers.get("authorization", "")
if authorization.lower().startswith("bearer "):
token = authorization[7:].strip()
payload = verify_session(token) if token else None
if not payload:
raise HTTPException(status_code=401, detail="Authentication required")
row = db.query_one("SELECT * FROM users WHERE id=?", (payload["uid"],))
if not row:
raise HTTPException(status_code=401, detail="User no longer exists")
return {"id": row["id"], "username": row["username"], "role": row["role"], "auth": "session"}
def require_admin(user: Dict[str, Any] = Depends(current_user)) -> Dict[str, Any]:
if user.get("role") != "admin":
raise HTTPException(status_code=403, detail="Administrator role required")
return user
def require_operator(user: Dict[str, Any] = Depends(current_user)) -> Dict[str, Any]:
if user.get("role") not in ("admin", "operator"):
raise HTTPException(status_code=403, detail="Operator role required")
return user
def require_feature(feature: str, role: str = "viewer"):
def dependency(user: Dict[str, Any] = Depends(current_user)) -> Dict[str, Any]:
if role == "admin" and user.get("role") != "admin":
raise HTTPException(status_code=403, detail="Administrator role required")
if role == "operator" and user.get("role") not in ("admin", "operator"):
raise HTTPException(status_code=403, detail="Operator role required")
if not licensing.has_feature(feature):
raise HTTPException(
status_code=402,
detail={
"code": "upgrade_required",
"feature": feature,
"message": "This capability requires Headroom Enterprise. Start a trial or activate a license.",
},
)
return user
return dependency
def account(request: Request) -> Dict[str, Any]:
user = current_user(request)
status = licensing.status()
return {
"user": user,
"edition": status,
"site_name": db.get_setting("site_name", "Homelab HQ"),
"version": "1.0.0",
}
def change_password(user: Dict[str, Any], current_password: str, new_password: str) -> None:
if len(new_password) < 8:
raise HTTPException(status_code=400, detail="New password must be at least 8 characters")
row = db.query_one("SELECT * FROM users WHERE id=?", (user["id"],))
if not row or not verify_password(current_password, row["password_hash"]):
raise HTTPException(status_code=400, detail="Current password is incorrect")
from .security import hash_password
db.execute("UPDATE users SET password_hash=? WHERE id=?", (hash_password(new_password), user["id"]))
db.audit(user["username"], "password.change", target=user["username"])