auth.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. from __future__ import annotations
  2. import secrets
  3. from datetime import datetime, timedelta
  4. from typing import Annotated
  5. from fastapi import Depends, Header, HTTPException, status
  6. from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
  7. from jose import JWTError, jwt
  8. from passlib.context import CryptContext
  9. from sqlalchemy import select
  10. from sqlalchemy.ext.asyncio import AsyncSession
  11. from backend.app.core.database import async_session, get_db
  12. from backend.app.models.api_key import APIKey
  13. from backend.app.models.settings import Settings
  14. from backend.app.models.user import User
  15. # Password hashing
  16. # Use pbkdf2_sha256 instead of bcrypt to avoid 72-byte limit and passlib initialization issues
  17. # pbkdf2_sha256 is a secure password hashing algorithm without bcrypt's limitations
  18. pwd_context = CryptContext(schemes=["pbkdf2_sha256"], deprecated="auto")
  19. # JWT settings
  20. SECRET_KEY = "bambuddy-secret-key-change-in-production" # TODO: Move to settings/env
  21. ALGORITHM = "HS256"
  22. ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24 * 7 # 7 days
  23. # HTTP Bearer token
  24. security = HTTPBearer(auto_error=False)
  25. def verify_password(plain_password: str, hashed_password: str) -> bool:
  26. """Verify a password against a hash.
  27. Uses pbkdf2_sha256 which handles long passwords automatically.
  28. """
  29. return pwd_context.verify(plain_password, hashed_password)
  30. def get_password_hash(password: str) -> str:
  31. """Hash a password.
  32. Uses pbkdf2_sha256 which is secure and has no password length limit.
  33. """
  34. return pwd_context.hash(password)
  35. def create_access_token(data: dict, expires_delta: timedelta | None = None) -> str:
  36. """Create a JWT access token."""
  37. to_encode = data.copy()
  38. if expires_delta:
  39. expire = datetime.utcnow() + expires_delta
  40. else:
  41. expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  42. to_encode.update({"exp": expire})
  43. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  44. return encoded_jwt
  45. async def get_user_by_username(db: AsyncSession, username: str) -> User | None:
  46. """Get a user by username."""
  47. result = await db.execute(select(User).where(User.username == username))
  48. return result.scalar_one_or_none()
  49. async def authenticate_user(db: AsyncSession, username: str, password: str) -> User | None:
  50. """Authenticate a user by username and password."""
  51. user = await get_user_by_username(db, username)
  52. if not user:
  53. return None
  54. if not verify_password(password, user.password_hash):
  55. return None
  56. if not user.is_active:
  57. return None
  58. return user
  59. async def is_auth_enabled(db: AsyncSession) -> bool:
  60. """Check if authentication is enabled."""
  61. try:
  62. result = await db.execute(select(Settings).where(Settings.key == "auth_enabled"))
  63. setting = result.scalar_one_or_none()
  64. if setting is None:
  65. return False
  66. return setting.value.lower() == "true"
  67. except Exception:
  68. # If settings table doesn't exist or query fails, assume auth is disabled
  69. return False
  70. async def get_current_user_optional(
  71. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  72. ) -> User | None:
  73. """Get the current authenticated user from JWT token, or None if not authenticated."""
  74. if credentials is None:
  75. return None
  76. try:
  77. token = credentials.credentials
  78. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  79. username: str = payload.get("sub")
  80. if username is None:
  81. return None
  82. except JWTError:
  83. return None
  84. async with async_session() as db:
  85. user = await get_user_by_username(db, username)
  86. if user is None or not user.is_active:
  87. return None
  88. return user
  89. async def get_current_user(
  90. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  91. ) -> User:
  92. """Get the current authenticated user from JWT token."""
  93. credentials_exception = HTTPException(
  94. status_code=status.HTTP_401_UNAUTHORIZED,
  95. detail="Could not validate credentials",
  96. headers={"WWW-Authenticate": "Bearer"},
  97. )
  98. if credentials is None:
  99. raise credentials_exception
  100. try:
  101. token = credentials.credentials
  102. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  103. username: str = payload.get("sub")
  104. if username is None:
  105. raise credentials_exception
  106. except JWTError:
  107. raise credentials_exception
  108. async with async_session() as db:
  109. user = await get_user_by_username(db, username)
  110. if user is None:
  111. raise credentials_exception
  112. if not user.is_active:
  113. raise HTTPException(
  114. status_code=status.HTTP_403_FORBIDDEN,
  115. detail="User account is disabled",
  116. )
  117. return user
  118. async def get_current_active_user(current_user: Annotated[User, Depends(get_current_user)]) -> User:
  119. """Get the current active user (alias for clarity)."""
  120. return current_user
  121. async def require_auth_if_enabled(
  122. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  123. ) -> User | None:
  124. """Require authentication if auth is enabled, otherwise return None."""
  125. async with async_session() as db:
  126. auth_enabled = await is_auth_enabled(db)
  127. if not auth_enabled:
  128. return None
  129. if credentials is None:
  130. raise HTTPException(
  131. status_code=status.HTTP_401_UNAUTHORIZED,
  132. detail="Authentication required",
  133. headers={"WWW-Authenticate": "Bearer"},
  134. )
  135. try:
  136. token = credentials.credentials
  137. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  138. username: str = payload.get("sub")
  139. if username is None:
  140. raise HTTPException(
  141. status_code=status.HTTP_401_UNAUTHORIZED,
  142. detail="Could not validate credentials",
  143. headers={"WWW-Authenticate": "Bearer"},
  144. )
  145. except JWTError:
  146. raise HTTPException(
  147. status_code=status.HTTP_401_UNAUTHORIZED,
  148. detail="Could not validate credentials",
  149. headers={"WWW-Authenticate": "Bearer"},
  150. )
  151. user = await get_user_by_username(db, username)
  152. if user is None or not user.is_active:
  153. raise HTTPException(
  154. status_code=status.HTTP_401_UNAUTHORIZED,
  155. detail="Could not validate credentials",
  156. headers={"WWW-Authenticate": "Bearer"},
  157. )
  158. return user
  159. def require_role(required_role: str):
  160. """Dependency factory for role-based access control."""
  161. async def role_checker(current_user: Annotated[User, Depends(get_current_user)]) -> User:
  162. if current_user.role != required_role:
  163. raise HTTPException(
  164. status_code=status.HTTP_403_FORBIDDEN,
  165. detail=f"Requires {required_role} role",
  166. )
  167. return current_user
  168. return role_checker
  169. def require_admin_if_auth_enabled():
  170. """Dependency factory that requires admin role if auth is enabled."""
  171. async def admin_checker(
  172. current_user: Annotated[User | None, Depends(require_auth_if_enabled)] = None,
  173. ) -> User | None:
  174. if current_user is None:
  175. return None # Auth not enabled, allow access
  176. if current_user.role != "admin":
  177. raise HTTPException(
  178. status_code=status.HTTP_403_FORBIDDEN,
  179. detail="Requires admin role",
  180. )
  181. return current_user
  182. return admin_checker
  183. def generate_api_key() -> tuple[str, str, str]:
  184. """Generate a new API key.
  185. Returns:
  186. tuple: (full_key, key_hash, key_prefix)
  187. - full_key: The complete API key (only shown once on creation)
  188. - key_hash: Hashed version for storage and verification
  189. - key_prefix: First 8 characters for display purposes
  190. """
  191. # Generate a secure random API key (32 bytes = 64 hex characters)
  192. full_key = f"bb_{secrets.token_urlsafe(32)}"
  193. key_hash = get_password_hash(full_key)
  194. key_prefix = full_key[:8] + "..." if len(full_key) > 8 else full_key
  195. return full_key, key_hash, key_prefix
  196. async def get_api_key(
  197. authorization: Annotated[str | None, Header(alias="Authorization")] = None,
  198. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  199. db: AsyncSession = Depends(get_db),
  200. ) -> APIKey:
  201. """Get and validate API key from request headers.
  202. Checks both 'Authorization: Bearer <key>' and 'X-API-Key: <key>' headers.
  203. """
  204. api_key_value = None
  205. if x_api_key:
  206. api_key_value = x_api_key
  207. elif authorization and authorization.startswith("Bearer "):
  208. api_key_value = authorization.replace("Bearer ", "")
  209. if not api_key_value:
  210. raise HTTPException(
  211. status_code=status.HTTP_401_UNAUTHORIZED,
  212. detail="API key required. Provide 'X-API-Key' header or 'Authorization: Bearer <key>'",
  213. )
  214. # Get all API keys and check them
  215. result = await db.execute(select(APIKey).where(APIKey.enabled.is_(True)))
  216. api_keys = result.scalars().all()
  217. for api_key in api_keys:
  218. # Check if key matches (verify against hash)
  219. if verify_password(api_key_value, api_key.key_hash):
  220. # Check expiration
  221. if api_key.expires_at and api_key.expires_at < datetime.now():
  222. raise HTTPException(
  223. status_code=status.HTTP_401_UNAUTHORIZED,
  224. detail="API key has expired",
  225. )
  226. # Update last_used timestamp
  227. api_key.last_used = datetime.now()
  228. await db.commit()
  229. return api_key
  230. raise HTTPException(
  231. status_code=status.HTTP_401_UNAUTHORIZED,
  232. detail="Invalid API key",
  233. )
  234. def check_permission(api_key: APIKey, permission: str) -> None:
  235. """Check if API key has the required permission.
  236. Args:
  237. api_key: The API key object
  238. permission: One of 'queue', 'control_printer', 'read_status'
  239. Raises:
  240. HTTPException: If permission is not granted
  241. """
  242. permission_map = {
  243. "queue": "can_queue",
  244. "control_printer": "can_control_printer",
  245. "read_status": "can_read_status",
  246. }
  247. if permission not in permission_map:
  248. raise HTTPException(
  249. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  250. detail=f"Unknown permission: {permission}",
  251. )
  252. attr_name = permission_map[permission]
  253. if not getattr(api_key, attr_name, False):
  254. raise HTTPException(
  255. status_code=status.HTTP_403_FORBIDDEN,
  256. detail=f"API key does not have '{permission}' permission",
  257. )
  258. def check_printer_access(api_key: APIKey, printer_id: int) -> None:
  259. """Check if API key has access to the specified printer.
  260. Args:
  261. api_key: The API key object
  262. printer_id: The printer ID to check access for
  263. Raises:
  264. HTTPException: If access is denied
  265. """
  266. # If printer_ids is None or empty, access to all printers
  267. if api_key.printer_ids is None or len(api_key.printer_ids) == 0:
  268. return
  269. # Check if printer_id is in allowed list
  270. if printer_id not in api_key.printer_ids:
  271. raise HTTPException(
  272. status_code=status.HTTP_403_FORBIDDEN,
  273. detail=f"API key does not have access to printer {printer_id}",
  274. )
  275. # Convenience dependencies - these are functions that return Depends objects
  276. def RequireAdmin():
  277. """Dependency that requires admin role."""
  278. return Depends(require_role("admin"))
  279. def RequireAdminIfAuthEnabled():
  280. """Dependency that requires admin role if auth is enabled."""
  281. return Depends(require_admin_if_auth_enabled())