auth.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. import logging
  2. import uuid
  3. import jwt
  4. import base64
  5. import hmac
  6. import hashlib
  7. import requests
  8. from datetime import UTC, datetime, timedelta
  9. from typing import Optional, Union, List, Dict
  10. from open_webui.models.users import Users
  11. from open_webui.constants import ERROR_MESSAGES
  12. from open_webui.config import override_static
  13. from open_webui.env import WEBUI_SECRET_KEY, TRUSTED_SIGNATURE_KEY
  14. from fastapi import Depends, HTTPException, Request, Response, status
  15. from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
  16. from passlib.context import CryptContext
  17. logging.getLogger("passlib").setLevel(logging.ERROR)
  18. SESSION_SECRET = WEBUI_SECRET_KEY
  19. ALGORITHM = "HS256"
  20. ##############
  21. # Auth Utils
  22. ##############
  23. def verify_signature(payload: str, signature: str) -> bool:
  24. """
  25. Verifies the HMAC signature of the received payload.
  26. """
  27. try:
  28. expected_signature = base64.b64encode(
  29. hmac.new(TRUSTED_SIGNATURE_KEY, payload.encode(), hashlib.sha256).digest()
  30. ).decode()
  31. # Compare securely to prevent timing attacks
  32. return hmac.compare_digest(expected_signature, signature)
  33. except Exception:
  34. return False
  35. def get_license_data(app, key):
  36. if key:
  37. try:
  38. res = requests.post(
  39. "https://api.openwebui.com/api/v1/license",
  40. json={"key": key, "version": "1"},
  41. timeout=5,
  42. )
  43. if getattr(res, "ok", False):
  44. payload = getattr(res, "json", lambda: {})()
  45. for k, v in payload.items():
  46. if k == "resources":
  47. for p, c in v.items():
  48. globals().get("override_static", lambda a, b: None)(p, c)
  49. elif k == "user_count":
  50. setattr(app.state, "USER_COUNT", v)
  51. elif k == "webui_name":
  52. setattr(app.state, "WEBUI_NAME", v)
  53. return True
  54. else:
  55. print(
  56. f"License: retrieval issue: {getattr(res, 'text', 'unknown error')}"
  57. )
  58. except Exception as ex:
  59. print(f"License: Uncaught Exception: {ex}")
  60. return False
  61. bearer_security = HTTPBearer(auto_error=False)
  62. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  63. def verify_password(plain_password, hashed_password):
  64. return (
  65. pwd_context.verify(plain_password, hashed_password) if hashed_password else None
  66. )
  67. def get_password_hash(password):
  68. return pwd_context.hash(password)
  69. def create_token(data: dict, expires_delta: Union[timedelta, None] = None) -> str:
  70. payload = data.copy()
  71. if expires_delta:
  72. expire = datetime.now(UTC) + expires_delta
  73. payload.update({"exp": expire})
  74. encoded_jwt = jwt.encode(payload, SESSION_SECRET, algorithm=ALGORITHM)
  75. return encoded_jwt
  76. def decode_token(token: str) -> Optional[dict]:
  77. try:
  78. decoded = jwt.decode(token, SESSION_SECRET, algorithms=[ALGORITHM])
  79. return decoded
  80. except Exception:
  81. return None
  82. def extract_token_from_auth_header(auth_header: str):
  83. return auth_header[len("Bearer ") :]
  84. def create_api_key():
  85. key = str(uuid.uuid4()).replace("-", "")
  86. return f"sk-{key}"
  87. def get_http_authorization_cred(auth_header: str):
  88. try:
  89. scheme, credentials = auth_header.split(" ")
  90. return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials)
  91. except Exception:
  92. raise ValueError(ERROR_MESSAGES.INVALID_TOKEN)
  93. def get_current_user(
  94. request: Request,
  95. auth_token: HTTPAuthorizationCredentials = Depends(bearer_security),
  96. ):
  97. token = None
  98. if auth_token is not None:
  99. token = auth_token.credentials
  100. if token is None and "token" in request.cookies:
  101. token = request.cookies.get("token")
  102. if token is None:
  103. raise HTTPException(status_code=403, detail="Not authenticated")
  104. # auth by api key
  105. if token.startswith("sk-"):
  106. if not request.state.enable_api_key:
  107. raise HTTPException(
  108. status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.API_KEY_NOT_ALLOWED
  109. )
  110. if request.app.state.config.ENABLE_API_KEY_ENDPOINT_RESTRICTIONS:
  111. allowed_paths = [
  112. path.strip()
  113. for path in str(
  114. request.app.state.config.API_KEY_ALLOWED_ENDPOINTS
  115. ).split(",")
  116. ]
  117. if request.url.path not in allowed_paths:
  118. raise HTTPException(
  119. status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.API_KEY_NOT_ALLOWED
  120. )
  121. return get_current_user_by_api_key(token)
  122. # auth by jwt token
  123. try:
  124. data = decode_token(token)
  125. except Exception as e:
  126. raise HTTPException(
  127. status_code=status.HTTP_401_UNAUTHORIZED,
  128. detail="Invalid token",
  129. )
  130. if data is not None and "id" in data:
  131. user = Users.get_user_by_id(data["id"])
  132. if user is None:
  133. raise HTTPException(
  134. status_code=status.HTTP_401_UNAUTHORIZED,
  135. detail=ERROR_MESSAGES.INVALID_TOKEN,
  136. )
  137. else:
  138. Users.update_user_last_active_by_id(user.id)
  139. return user
  140. else:
  141. raise HTTPException(
  142. status_code=status.HTTP_401_UNAUTHORIZED,
  143. detail=ERROR_MESSAGES.UNAUTHORIZED,
  144. )
  145. def get_current_user_by_api_key(api_key: str):
  146. user = Users.get_user_by_api_key(api_key)
  147. if user is None:
  148. raise HTTPException(
  149. status_code=status.HTTP_401_UNAUTHORIZED,
  150. detail=ERROR_MESSAGES.INVALID_TOKEN,
  151. )
  152. else:
  153. Users.update_user_last_active_by_id(user.id)
  154. return user
  155. def get_verified_user(user=Depends(get_current_user)):
  156. if user.role not in {"user", "admin"}:
  157. raise HTTPException(
  158. status_code=status.HTTP_401_UNAUTHORIZED,
  159. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  160. )
  161. return user
  162. def get_admin_user(user=Depends(get_current_user)):
  163. if user.role != "admin":
  164. raise HTTPException(
  165. status_code=status.HTTP_401_UNAUTHORIZED,
  166. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  167. )
  168. return user