auth.py 12 KB

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