auth.py 12 KB

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