auth.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  1. from __future__ import annotations
  2. import logging
  3. import os
  4. import secrets
  5. from datetime import datetime, timedelta
  6. from pathlib import Path
  7. from typing import Annotated
  8. import jwt
  9. from fastapi import Depends, Header, HTTPException, status
  10. from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
  11. from jwt.exceptions import PyJWTError as JWTError
  12. from passlib.context import CryptContext
  13. from sqlalchemy import select
  14. from sqlalchemy.ext.asyncio import AsyncSession
  15. from sqlalchemy.orm import selectinload
  16. from backend.app.core.database import async_session, get_db
  17. from backend.app.core.permissions import Permission
  18. from backend.app.models.api_key import APIKey
  19. from backend.app.models.settings import Settings
  20. from backend.app.models.user import User
  21. logger = logging.getLogger(__name__)
  22. # Password hashing
  23. # Use pbkdf2_sha256 instead of bcrypt to avoid 72-byte limit and passlib initialization issues
  24. # pbkdf2_sha256 is a secure password hashing algorithm without bcrypt's limitations
  25. pwd_context = CryptContext(schemes=["pbkdf2_sha256"], deprecated="auto")
  26. def _get_jwt_secret() -> str:
  27. """Get the JWT secret key from environment, file, or generate a new one.
  28. Priority:
  29. 1. JWT_SECRET_KEY environment variable
  30. 2. .jwt_secret file in data directory
  31. 3. Generate new random secret and save to file
  32. Returns:
  33. The JWT secret key
  34. """
  35. # 1. Check environment variable first
  36. env_secret = os.environ.get("JWT_SECRET_KEY")
  37. if env_secret:
  38. logger.info("Using JWT secret from JWT_SECRET_KEY environment variable")
  39. return env_secret
  40. # 2. Check for secret file in data directory
  41. # Use DATA_DIR env var (same as rest of app), fallback to data/ subdirectory
  42. data_dir_env = os.environ.get("DATA_DIR")
  43. if data_dir_env:
  44. data_dir = Path(data_dir_env)
  45. else:
  46. # Fallback to data/ subdirectory under project root (not project root itself!)
  47. data_dir = Path(__file__).parent.parent.parent.parent / "data"
  48. secret_file = data_dir / ".jwt_secret"
  49. if secret_file.exists():
  50. try:
  51. secret = secret_file.read_text().strip()
  52. if secret and len(secret) >= 32:
  53. logger.info("Using JWT secret from %s", secret_file)
  54. return secret
  55. except OSError as e:
  56. logger.warning("Failed to read JWT secret file: %s", e)
  57. # 3. Generate new random secret
  58. new_secret = secrets.token_urlsafe(64)
  59. # Try to save it
  60. try:
  61. data_dir.mkdir(parents=True, exist_ok=True)
  62. # Note: CodeQL flags this as "clear-text storage of sensitive information" but this is
  63. # intentional and secure - JWT secrets must be readable by the app, we set 0600 permissions,
  64. # and this is standard practice for self-hosted applications (same as .env files).
  65. secret_file.write_text(new_secret) # nosec B105 - intentional secure storage
  66. # Restrict permissions (owner read/write only)
  67. secret_file.chmod(0o600)
  68. logger.info("Generated new JWT secret and saved to %s", secret_file)
  69. except OSError as e:
  70. logger.warning(
  71. "Could not save JWT secret to file (%s). "
  72. "Secret will be regenerated on restart, invalidating existing tokens. "
  73. "Set JWT_SECRET_KEY environment variable for persistence.",
  74. e,
  75. )
  76. return new_secret
  77. # JWT settings
  78. SECRET_KEY = _get_jwt_secret()
  79. ALGORITHM = "HS256"
  80. ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24 * 7 # 7 days
  81. # HTTP Bearer token
  82. security = HTTPBearer(auto_error=False)
  83. def verify_password(plain_password: str, hashed_password: str) -> bool:
  84. """Verify a password against a hash.
  85. Uses pbkdf2_sha256 which handles long passwords automatically.
  86. """
  87. return pwd_context.verify(plain_password, hashed_password)
  88. def get_password_hash(password: str) -> str:
  89. """Hash a password.
  90. Uses pbkdf2_sha256 which is secure and has no password length limit.
  91. """
  92. return pwd_context.hash(password)
  93. def create_access_token(data: dict, expires_delta: timedelta | None = None) -> str:
  94. """Create a JWT access token."""
  95. to_encode = data.copy()
  96. if expires_delta:
  97. expire = datetime.utcnow() + expires_delta
  98. else:
  99. expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  100. to_encode.update({"exp": expire})
  101. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  102. return encoded_jwt
  103. async def get_user_by_username(db: AsyncSession, username: str) -> User | None:
  104. """Get a user by username with groups loaded for permission checks."""
  105. result = await db.execute(select(User).where(User.username == username).options(selectinload(User.groups)))
  106. return result.scalar_one_or_none()
  107. async def authenticate_user(db: AsyncSession, username: str, password: str) -> User | None:
  108. """Authenticate a user by username and password."""
  109. user = await get_user_by_username(db, username)
  110. if not user:
  111. return None
  112. if not verify_password(password, user.password_hash):
  113. return None
  114. if not user.is_active:
  115. return None
  116. return user
  117. async def is_auth_enabled(db: AsyncSession) -> bool:
  118. """Check if authentication is enabled."""
  119. try:
  120. result = await db.execute(select(Settings).where(Settings.key == "auth_enabled"))
  121. setting = result.scalar_one_or_none()
  122. if setting is None:
  123. return False
  124. return setting.value.lower() == "true"
  125. except Exception:
  126. # If settings table doesn't exist or query fails, assume auth is disabled
  127. return False
  128. async def _validate_api_key(db: AsyncSession, api_key_value: str) -> APIKey | None:
  129. """Validate an API key and return the APIKey object if valid, None otherwise.
  130. This is an internal helper used by auth functions to check API keys.
  131. """
  132. try:
  133. result = await db.execute(select(APIKey).where(APIKey.enabled.is_(True)))
  134. api_keys = result.scalars().all()
  135. for api_key in api_keys:
  136. if verify_password(api_key_value, api_key.key_hash):
  137. # Check expiration
  138. if api_key.expires_at and api_key.expires_at < datetime.now():
  139. return None # Expired
  140. # Update last_used timestamp
  141. api_key.last_used = datetime.now()
  142. await db.commit()
  143. return api_key
  144. except Exception as e:
  145. logger.warning("API key validation error: %s", e)
  146. return None
  147. async def get_current_user_optional(
  148. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  149. ) -> User | None:
  150. """Get the current authenticated user from JWT token, or None if not authenticated."""
  151. if credentials is None:
  152. return None
  153. try:
  154. token = credentials.credentials
  155. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  156. username: str = payload.get("sub")
  157. if username is None:
  158. return None
  159. except JWTError:
  160. return None
  161. async with async_session() as db:
  162. user = await get_user_by_username(db, username)
  163. if user is None or not user.is_active:
  164. return None
  165. return user
  166. async def get_current_user(
  167. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  168. ) -> User:
  169. """Get the current authenticated user from JWT token."""
  170. credentials_exception = HTTPException(
  171. status_code=status.HTTP_401_UNAUTHORIZED,
  172. detail="Could not validate credentials",
  173. headers={"WWW-Authenticate": "Bearer"},
  174. )
  175. if credentials is None:
  176. raise credentials_exception
  177. try:
  178. token = credentials.credentials
  179. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  180. username: str = payload.get("sub")
  181. if username is None:
  182. raise credentials_exception
  183. except JWTError:
  184. raise credentials_exception
  185. async with async_session() as db:
  186. user = await get_user_by_username(db, username)
  187. if user is None:
  188. raise credentials_exception
  189. if not user.is_active:
  190. raise HTTPException(
  191. status_code=status.HTTP_403_FORBIDDEN,
  192. detail="User account is disabled",
  193. )
  194. return user
  195. async def get_current_active_user(current_user: Annotated[User, Depends(get_current_user)]) -> User:
  196. """Get the current active user (alias for clarity)."""
  197. return current_user
  198. async def require_auth_if_enabled(
  199. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  200. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  201. ) -> User | None:
  202. """Require authentication if auth is enabled, otherwise return None.
  203. Accepts both JWT tokens (via Authorization: Bearer header) and API keys
  204. (via X-API-Key header or Authorization: Bearer bb_xxx).
  205. """
  206. async with async_session() as db:
  207. auth_enabled = await is_auth_enabled(db)
  208. if not auth_enabled:
  209. return None
  210. # Check for API key first (X-API-Key header)
  211. if x_api_key:
  212. api_key = await _validate_api_key(db, x_api_key)
  213. if api_key:
  214. return None # API key valid, allow access
  215. # Check for Bearer token (could be JWT or API key)
  216. if credentials is not None:
  217. token = credentials.credentials
  218. # Check if it's an API key (starts with bb_)
  219. if token.startswith("bb_"):
  220. api_key = await _validate_api_key(db, token)
  221. if api_key:
  222. return None # API key valid, allow access
  223. raise HTTPException(
  224. status_code=status.HTTP_401_UNAUTHORIZED,
  225. detail="Invalid API key",
  226. headers={"WWW-Authenticate": "Bearer"},
  227. )
  228. # Otherwise treat as JWT
  229. try:
  230. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  231. username: str = payload.get("sub")
  232. if username is None:
  233. raise HTTPException(
  234. status_code=status.HTTP_401_UNAUTHORIZED,
  235. detail="Could not validate credentials",
  236. headers={"WWW-Authenticate": "Bearer"},
  237. )
  238. except JWTError:
  239. raise HTTPException(
  240. status_code=status.HTTP_401_UNAUTHORIZED,
  241. detail="Could not validate credentials",
  242. headers={"WWW-Authenticate": "Bearer"},
  243. )
  244. user = await get_user_by_username(db, username)
  245. if user is None or not user.is_active:
  246. raise HTTPException(
  247. status_code=status.HTTP_401_UNAUTHORIZED,
  248. detail="Could not validate credentials",
  249. headers={"WWW-Authenticate": "Bearer"},
  250. )
  251. return user
  252. # No credentials provided
  253. raise HTTPException(
  254. status_code=status.HTTP_401_UNAUTHORIZED,
  255. detail="Authentication required",
  256. headers={"WWW-Authenticate": "Bearer"},
  257. )
  258. def require_role(required_role: str):
  259. """Dependency factory for role-based access control."""
  260. async def role_checker(current_user: Annotated[User, Depends(get_current_user)]) -> User:
  261. if current_user.role != required_role:
  262. raise HTTPException(
  263. status_code=status.HTTP_403_FORBIDDEN,
  264. detail=f"Requires {required_role} role",
  265. )
  266. return current_user
  267. return role_checker
  268. def require_admin_if_auth_enabled():
  269. """Dependency factory that requires admin role if auth is enabled."""
  270. async def admin_checker(
  271. current_user: Annotated[User | None, Depends(require_auth_if_enabled)] = None,
  272. ) -> User | None:
  273. if current_user is None:
  274. return None # Auth not enabled, allow access
  275. if current_user.role != "admin":
  276. raise HTTPException(
  277. status_code=status.HTTP_403_FORBIDDEN,
  278. detail="Requires admin role",
  279. )
  280. return current_user
  281. return admin_checker
  282. def generate_api_key() -> tuple[str, str, str]:
  283. """Generate a new API key.
  284. Returns:
  285. tuple: (full_key, key_hash, key_prefix)
  286. - full_key: The complete API key (only shown once on creation)
  287. - key_hash: Hashed version for storage and verification
  288. - key_prefix: First 8 characters for display purposes
  289. """
  290. # Generate a secure random API key (32 bytes = 64 hex characters)
  291. full_key = f"bb_{secrets.token_urlsafe(32)}"
  292. key_hash = get_password_hash(full_key)
  293. key_prefix = full_key[:8] + "..." if len(full_key) > 8 else full_key
  294. return full_key, key_hash, key_prefix
  295. async def get_api_key(
  296. authorization: Annotated[str | None, Header(alias="Authorization")] = None,
  297. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  298. db: AsyncSession = Depends(get_db),
  299. ) -> APIKey:
  300. """Get and validate API key from request headers.
  301. Checks both 'Authorization: Bearer <key>' and 'X-API-Key: <key>' headers.
  302. """
  303. api_key_value = None
  304. if x_api_key:
  305. api_key_value = x_api_key
  306. elif authorization and authorization.startswith("Bearer "):
  307. api_key_value = authorization.replace("Bearer ", "")
  308. if not api_key_value:
  309. raise HTTPException(
  310. status_code=status.HTTP_401_UNAUTHORIZED,
  311. detail="API key required. Provide 'X-API-Key' header or 'Authorization: Bearer <key>'",
  312. )
  313. # Get all API keys and check them
  314. result = await db.execute(select(APIKey).where(APIKey.enabled.is_(True)))
  315. api_keys = result.scalars().all()
  316. for api_key in api_keys:
  317. # Check if key matches (verify against hash)
  318. if verify_password(api_key_value, api_key.key_hash):
  319. # Check expiration
  320. if api_key.expires_at and api_key.expires_at < datetime.now():
  321. raise HTTPException(
  322. status_code=status.HTTP_401_UNAUTHORIZED,
  323. detail="API key has expired",
  324. )
  325. # Update last_used timestamp
  326. api_key.last_used = datetime.now()
  327. await db.commit()
  328. return api_key
  329. raise HTTPException(
  330. status_code=status.HTTP_401_UNAUTHORIZED,
  331. detail="Invalid API key",
  332. )
  333. def check_permission(api_key: APIKey, permission: str) -> None:
  334. """Check if API key has the required permission.
  335. Args:
  336. api_key: The API key object
  337. permission: One of 'queue', 'control_printer', 'read_status'
  338. Raises:
  339. HTTPException: If permission is not granted
  340. """
  341. permission_map = {
  342. "queue": "can_queue",
  343. "control_printer": "can_control_printer",
  344. "read_status": "can_read_status",
  345. }
  346. if permission not in permission_map:
  347. raise HTTPException(
  348. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  349. detail=f"Unknown permission: {permission}",
  350. )
  351. attr_name = permission_map[permission]
  352. if not getattr(api_key, attr_name, False):
  353. raise HTTPException(
  354. status_code=status.HTTP_403_FORBIDDEN,
  355. detail=f"API key does not have '{permission}' permission",
  356. )
  357. def check_printer_access(api_key: APIKey, printer_id: int) -> None:
  358. """Check if API key has access to the specified printer.
  359. Args:
  360. api_key: The API key object
  361. printer_id: The printer ID to check access for
  362. Raises:
  363. HTTPException: If access is denied
  364. """
  365. # If printer_ids is None or empty, access to all printers
  366. if api_key.printer_ids is None or len(api_key.printer_ids) == 0:
  367. return
  368. # Check if printer_id is in allowed list
  369. if printer_id not in api_key.printer_ids:
  370. raise HTTPException(
  371. status_code=status.HTTP_403_FORBIDDEN,
  372. detail=f"API key does not have access to printer {printer_id}",
  373. )
  374. # Convenience dependencies - these are functions that return Depends objects
  375. def RequireAdmin():
  376. """Dependency that requires admin role."""
  377. return Depends(require_role("admin"))
  378. def RequireAdminIfAuthEnabled():
  379. """Dependency that requires admin role if auth is enabled."""
  380. return Depends(require_admin_if_auth_enabled())
  381. def require_permission(*permissions: str | Permission):
  382. """Dependency factory that requires user to have ALL specified permissions.
  383. Accepts both JWT tokens (via Authorization: Bearer header) and API keys
  384. (via X-API-Key header or Authorization: Bearer bb_xxx).
  385. Args:
  386. *permissions: Permission strings or Permission enum values to require
  387. Returns:
  388. A dependency function that validates permissions
  389. """
  390. # Convert Permission enums to strings
  391. perm_strings = [p.value if isinstance(p, Permission) else p for p in permissions]
  392. async def permission_checker(
  393. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  394. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  395. ) -> User | None:
  396. async with async_session() as db:
  397. # Check for API key first (X-API-Key header)
  398. if x_api_key:
  399. api_key = await _validate_api_key(db, x_api_key)
  400. if api_key:
  401. return None # API key valid, allow access
  402. credentials_exception = HTTPException(
  403. status_code=status.HTTP_401_UNAUTHORIZED,
  404. detail="Could not validate credentials",
  405. headers={"WWW-Authenticate": "Bearer"},
  406. )
  407. if credentials is None:
  408. raise credentials_exception
  409. token = credentials.credentials
  410. # Check if it's an API key (starts with bb_)
  411. if token.startswith("bb_"):
  412. api_key = await _validate_api_key(db, token)
  413. if api_key:
  414. return None # API key valid, allow access
  415. raise HTTPException(
  416. status_code=status.HTTP_401_UNAUTHORIZED,
  417. detail="Invalid API key",
  418. headers={"WWW-Authenticate": "Bearer"},
  419. )
  420. # Otherwise treat as JWT
  421. try:
  422. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  423. username: str = payload.get("sub")
  424. if username is None:
  425. raise credentials_exception
  426. except JWTError:
  427. raise credentials_exception
  428. user = await get_user_by_username(db, username)
  429. if user is None or not user.is_active:
  430. raise credentials_exception
  431. if not user.has_all_permissions(*perm_strings):
  432. raise HTTPException(
  433. status_code=status.HTTP_403_FORBIDDEN,
  434. detail=f"Missing required permissions: {', '.join(perm_strings)}",
  435. )
  436. return user
  437. return permission_checker
  438. def require_permission_if_auth_enabled(*permissions: str | Permission):
  439. """Dependency factory that checks permissions only if auth is enabled.
  440. This provides backward compatibility - when auth is disabled, all access is allowed.
  441. Accepts both JWT tokens (via Authorization: Bearer header) and API keys
  442. (via X-API-Key header or Authorization: Bearer bb_xxx).
  443. Args:
  444. *permissions: Permission strings or Permission enum values to require
  445. Returns:
  446. A dependency function that validates permissions if auth is enabled
  447. """
  448. # Convert Permission enums to strings
  449. perm_strings = [p.value if isinstance(p, Permission) else p for p in permissions]
  450. async def permission_checker(
  451. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  452. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  453. ) -> User | None:
  454. async with async_session() as db:
  455. auth_enabled = await is_auth_enabled(db)
  456. if not auth_enabled:
  457. return None # Auth disabled, allow access
  458. # Check for API key first (X-API-Key header)
  459. if x_api_key:
  460. api_key = await _validate_api_key(db, x_api_key)
  461. if api_key:
  462. return None # API key valid, allow access
  463. # Check for Bearer token (could be JWT or API key)
  464. if credentials is not None:
  465. token = credentials.credentials
  466. # Check if it's an API key (starts with bb_)
  467. if token.startswith("bb_"):
  468. api_key = await _validate_api_key(db, token)
  469. if api_key:
  470. return None # API key valid, allow access
  471. raise HTTPException(
  472. status_code=status.HTTP_401_UNAUTHORIZED,
  473. detail="Invalid API key",
  474. headers={"WWW-Authenticate": "Bearer"},
  475. )
  476. # Otherwise treat as JWT
  477. try:
  478. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  479. username: str = payload.get("sub")
  480. if username is None:
  481. raise HTTPException(
  482. status_code=status.HTTP_401_UNAUTHORIZED,
  483. detail="Could not validate credentials",
  484. headers={"WWW-Authenticate": "Bearer"},
  485. )
  486. except JWTError:
  487. raise HTTPException(
  488. status_code=status.HTTP_401_UNAUTHORIZED,
  489. detail="Could not validate credentials",
  490. headers={"WWW-Authenticate": "Bearer"},
  491. )
  492. user = await get_user_by_username(db, username)
  493. if user is None or not user.is_active:
  494. raise HTTPException(
  495. status_code=status.HTTP_401_UNAUTHORIZED,
  496. detail="Could not validate credentials",
  497. headers={"WWW-Authenticate": "Bearer"},
  498. )
  499. if not user.has_all_permissions(*perm_strings):
  500. raise HTTPException(
  501. status_code=status.HTTP_403_FORBIDDEN,
  502. detail=f"Missing required permissions: {', '.join(perm_strings)}",
  503. )
  504. return user
  505. # No credentials provided
  506. raise HTTPException(
  507. status_code=status.HTTP_401_UNAUTHORIZED,
  508. detail="Authentication required",
  509. headers={"WWW-Authenticate": "Bearer"},
  510. )
  511. return permission_checker
  512. def RequirePermission(*permissions: str | Permission):
  513. """Convenience dependency that requires ALL specified permissions."""
  514. return Depends(require_permission(*permissions))
  515. def RequirePermissionIfAuthEnabled(*permissions: str | Permission):
  516. """Convenience dependency that requires permissions if auth is enabled."""
  517. return Depends(require_permission_if_auth_enabled(*permissions))
  518. def require_ownership_permission(
  519. all_permission: str | Permission,
  520. own_permission: str | Permission,
  521. ):
  522. """Dependency factory for ownership-based permission checks.
  523. - User with `all_permission` can modify any item
  524. - User with `own_permission` can only modify items where created_by_id == user.id
  525. - Ownerless items (created_by_id = null) require `all_permission`
  526. - API keys (via X-API-Key header or Bearer bb_xxx) get full access (can_modify_all=True)
  527. Returns:
  528. A dependency function that returns (user, can_modify_all).
  529. - can_modify_all=True: user can modify any item
  530. - can_modify_all=False: user can only modify their own items
  531. """
  532. all_perm = all_permission.value if isinstance(all_permission, Permission) else all_permission
  533. own_perm = own_permission.value if isinstance(own_permission, Permission) else own_permission
  534. async def checker(
  535. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  536. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  537. ) -> tuple[User | None, bool]:
  538. """Returns (user, can_modify_all).
  539. - can_modify_all=True: user can modify any item
  540. - can_modify_all=False: user can only modify their own items
  541. """
  542. async with async_session() as db:
  543. auth_enabled = await is_auth_enabled(db)
  544. if not auth_enabled:
  545. return None, True # Auth disabled, allow all
  546. # Check for API key first (X-API-Key header)
  547. if x_api_key:
  548. api_key = await _validate_api_key(db, x_api_key)
  549. if api_key:
  550. return None, True # API key valid, allow all
  551. # Check for Bearer token (could be JWT or API key)
  552. if credentials is not None:
  553. token = credentials.credentials
  554. # Check if it's an API key (starts with bb_)
  555. if token.startswith("bb_"):
  556. api_key = await _validate_api_key(db, token)
  557. if api_key:
  558. return None, True # API key valid, allow all
  559. raise HTTPException(
  560. status_code=status.HTTP_401_UNAUTHORIZED,
  561. detail="Invalid API key",
  562. headers={"WWW-Authenticate": "Bearer"},
  563. )
  564. # Otherwise treat as JWT
  565. try:
  566. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  567. username: str = payload.get("sub")
  568. if username is None:
  569. raise HTTPException(
  570. status_code=status.HTTP_401_UNAUTHORIZED,
  571. detail="Could not validate credentials",
  572. headers={"WWW-Authenticate": "Bearer"},
  573. )
  574. except JWTError:
  575. raise HTTPException(
  576. status_code=status.HTTP_401_UNAUTHORIZED,
  577. detail="Could not validate credentials",
  578. headers={"WWW-Authenticate": "Bearer"},
  579. )
  580. user = await get_user_by_username(db, username)
  581. if user is None or not user.is_active:
  582. raise HTTPException(
  583. status_code=status.HTTP_401_UNAUTHORIZED,
  584. detail="Could not validate credentials",
  585. headers={"WWW-Authenticate": "Bearer"},
  586. )
  587. if user.has_permission(all_perm):
  588. return user, True
  589. if user.has_permission(own_perm):
  590. return user, False
  591. raise HTTPException(
  592. status_code=status.HTTP_403_FORBIDDEN,
  593. detail=f"Missing permission: {own_perm} or {all_perm}",
  594. )
  595. # No credentials provided
  596. raise HTTPException(
  597. status_code=status.HTTP_401_UNAUTHORIZED,
  598. detail="Authentication required",
  599. headers={"WWW-Authenticate": "Bearer"},
  600. )
  601. return checker