auth.py 12 KB

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