oauth.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. import base64
  2. import logging
  3. import mimetypes
  4. import uuid
  5. import aiohttp
  6. from authlib.integrations.starlette_client import OAuth
  7. from authlib.oidc.core import UserInfo
  8. from fastapi import (
  9. HTTPException,
  10. status,
  11. )
  12. from starlette.responses import RedirectResponse
  13. from open_webui.apps.webui.models.auths import Auths
  14. from open_webui.apps.webui.models.users import Users
  15. from open_webui.config import (
  16. DEFAULT_USER_ROLE,
  17. ENABLE_OAUTH_SIGNUP,
  18. OAUTH_MERGE_ACCOUNTS_BY_EMAIL,
  19. OAUTH_PROVIDERS,
  20. ENABLE_OAUTH_ROLE_MANAGEMENT,
  21. OAUTH_ROLES_CLAIM,
  22. OAUTH_EMAIL_CLAIM,
  23. OAUTH_PICTURE_CLAIM,
  24. OAUTH_USERNAME_CLAIM,
  25. OAUTH_ALLOWED_ROLES,
  26. OAUTH_ADMIN_ROLES, WEBHOOK_URL, JWT_EXPIRES_IN, AppConfig,
  27. )
  28. from open_webui.constants import ERROR_MESSAGES
  29. from open_webui.env import WEBUI_SESSION_COOKIE_SAME_SITE, WEBUI_SESSION_COOKIE_SECURE
  30. from open_webui.utils.misc import parse_duration
  31. from open_webui.utils.utils import get_password_hash, create_token
  32. from open_webui.utils.webhook import post_webhook
  33. log = logging.getLogger(__name__)
  34. auth_manager_config = AppConfig()
  35. auth_manager_config.DEFAULT_USER_ROLE = DEFAULT_USER_ROLE
  36. auth_manager_config.ENABLE_OAUTH_SIGNUP = ENABLE_OAUTH_SIGNUP
  37. auth_manager_config.OAUTH_MERGE_ACCOUNTS_BY_EMAIL = OAUTH_MERGE_ACCOUNTS_BY_EMAIL
  38. auth_manager_config.ENABLE_OAUTH_ROLE_MANAGEMENT = ENABLE_OAUTH_ROLE_MANAGEMENT
  39. auth_manager_config.OAUTH_ROLES_CLAIM = OAUTH_ROLES_CLAIM
  40. auth_manager_config.OAUTH_EMAIL_CLAIM = OAUTH_EMAIL_CLAIM
  41. auth_manager_config.OAUTH_PICTURE_CLAIM = OAUTH_PICTURE_CLAIM
  42. auth_manager_config.OAUTH_USERNAME_CLAIM = OAUTH_USERNAME_CLAIM
  43. auth_manager_config.OAUTH_ALLOWED_ROLES = OAUTH_ALLOWED_ROLES
  44. auth_manager_config.OAUTH_ADMIN_ROLES = OAUTH_ADMIN_ROLES
  45. auth_manager_config.WEBHOOK_URL = WEBHOOK_URL
  46. auth_manager_config.JWT_EXPIRES_IN = JWT_EXPIRES_IN
  47. class OAuthManager:
  48. def __init__(self):
  49. self.oauth = OAuth()
  50. for provider_name, provider_config in OAUTH_PROVIDERS.items():
  51. self.oauth.register(
  52. name=provider_name,
  53. client_id=provider_config["client_id"],
  54. client_secret=provider_config["client_secret"],
  55. server_metadata_url=provider_config["server_metadata_url"],
  56. client_kwargs={
  57. "scope": provider_config["scope"],
  58. },
  59. redirect_uri=provider_config["redirect_uri"],
  60. )
  61. def get_client(self, provider_name):
  62. return self.oauth.create_client(provider_name)
  63. def get_user_role(self, user, user_data):
  64. if user and Users.get_num_users() == 1:
  65. # If the user is the only user, assign the role "admin" - actually repairs role for single user on login
  66. return "admin"
  67. if not user and Users.get_num_users() == 0:
  68. # If there are no users, assign the role "admin", as the first user will be an admin
  69. return "admin"
  70. if auth_manager_config.ENABLE_OAUTH_ROLE_MANAGEMENT:
  71. oauth_claim = auth_manager_config.OAUTH_ROLES_CLAIM
  72. oauth_allowed_roles = auth_manager_config.OAUTH_ALLOWED_ROLES
  73. oauth_admin_roles = auth_manager_config.OAUTH_ADMIN_ROLES
  74. oauth_roles = None
  75. role = "pending" # Default/fallback role if no matching roles are found
  76. # Next block extracts the roles from the user data, accepting nested claims of any depth
  77. if oauth_claim and oauth_allowed_roles and oauth_admin_roles:
  78. claim_data = user_data
  79. nested_claims = oauth_claim.split(".")
  80. for nested_claim in nested_claims:
  81. claim_data = claim_data.get(nested_claim, {})
  82. oauth_roles = claim_data if isinstance(claim_data, list) else None
  83. # If any roles are found, check if they match the allowed or admin roles
  84. if oauth_roles:
  85. # If role management is enabled, and matching roles are provided, use the roles
  86. for allowed_role in oauth_allowed_roles:
  87. # If the user has any of the allowed roles, assign the role "user"
  88. if allowed_role in oauth_roles:
  89. role = "user"
  90. break
  91. for admin_role in oauth_admin_roles:
  92. # If the user has any of the admin roles, assign the role "admin"
  93. if admin_role in oauth_roles:
  94. role = "admin"
  95. break
  96. else:
  97. if not user:
  98. # If role management is disabled, use the default role for new users
  99. role = auth_manager_config.DEFAULT_USER_ROLE
  100. else:
  101. # If role management is disabled, use the existing role for existing users
  102. role = user.role
  103. return role
  104. async def handle_login(self, provider, request):
  105. if provider not in OAUTH_PROVIDERS:
  106. raise HTTPException(404)
  107. # If the provider has a custom redirect URL, use that, otherwise automatically generate one
  108. redirect_uri = OAUTH_PROVIDERS[provider].get("redirect_uri") or request.url_for(
  109. "oauth_callback", provider=provider
  110. )
  111. client = self.get_client(provider)
  112. if client is None:
  113. raise HTTPException(404)
  114. return await client.authorize_redirect(request, redirect_uri)
  115. async def handle_callback(self, provider, request, response):
  116. if provider not in OAUTH_PROVIDERS:
  117. raise HTTPException(404)
  118. client = self.get_client(provider)
  119. try:
  120. token = await client.authorize_access_token(request)
  121. except Exception as e:
  122. log.warning(f"OAuth callback error: {e}")
  123. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  124. user_data: UserInfo = token["userinfo"]
  125. sub = user_data.get("sub")
  126. if not sub:
  127. log.warning(f"OAuth callback failed, sub is missing: {user_data}")
  128. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  129. provider_sub = f"{provider}@{sub}"
  130. email_claim = auth_manager_config.OAUTH_EMAIL_CLAIM
  131. email = user_data.get(email_claim, "").lower()
  132. # We currently mandate that email addresses are provided
  133. if not email:
  134. log.warning(f"OAuth callback failed, email is missing: {user_data}")
  135. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  136. # Check if the user exists
  137. user = Users.get_user_by_oauth_sub(provider_sub)
  138. if not user:
  139. # If the user does not exist, check if merging is enabled
  140. if auth_manager_config.OAUTH_MERGE_ACCOUNTS_BY_EMAIL.value:
  141. # Check if the user exists by email
  142. user = Users.get_user_by_email(email)
  143. if user:
  144. # Update the user with the new oauth sub
  145. Users.update_user_oauth_sub_by_id(user.id, provider_sub)
  146. if user:
  147. determined_role = self.get_user_role(user, user_data)
  148. if user.role != determined_role:
  149. Users.update_user_role_by_id(user.id, determined_role)
  150. if not user:
  151. # If the user does not exist, check if signups are enabled
  152. if auth_manager_config.ENABLE_OAUTH_SIGNUP.value:
  153. # Check if an existing user with the same email already exists
  154. existing_user = Users.get_user_by_email(user_data.get("email", "").lower())
  155. if existing_user:
  156. raise HTTPException(400, detail=ERROR_MESSAGES.EMAIL_TAKEN)
  157. picture_claim = auth_manager_config.OAUTH_PICTURE_CLAIM
  158. picture_url = user_data.get(picture_claim, "")
  159. if picture_url:
  160. # Download the profile image into a base64 string
  161. try:
  162. async with aiohttp.ClientSession() as session:
  163. async with session.get(picture_url) as resp:
  164. picture = await resp.read()
  165. base64_encoded_picture = base64.b64encode(picture).decode(
  166. "utf-8"
  167. )
  168. guessed_mime_type = mimetypes.guess_type(picture_url)[0]
  169. if guessed_mime_type is None:
  170. # assume JPG, browsers are tolerant enough of image formats
  171. guessed_mime_type = "image/jpeg"
  172. picture_url = f"data:{guessed_mime_type};base64,{base64_encoded_picture}"
  173. except Exception as e:
  174. log.error(f"Error downloading profile image '{picture_url}': {e}")
  175. picture_url = ""
  176. if not picture_url:
  177. picture_url = "/user.png"
  178. username_claim = auth_manager_config.OAUTH_USERNAME_CLAIM
  179. role = self.get_user_role(None, user_data)
  180. user = Auths.insert_new_auth(
  181. email=email,
  182. password=get_password_hash(
  183. str(uuid.uuid4())
  184. ), # Random password, not used
  185. name=user_data.get(username_claim, "User"),
  186. profile_image_url=picture_url,
  187. role=role,
  188. oauth_sub=provider_sub,
  189. )
  190. if auth_manager_config.WEBHOOK_URL:
  191. post_webhook(
  192. auth_manager_config.WEBHOOK_URL,
  193. auth_manager_config.WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  194. {
  195. "action": "signup",
  196. "message": auth_manager_config.WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  197. "user": user.model_dump_json(exclude_none=True),
  198. },
  199. )
  200. else:
  201. raise HTTPException(
  202. status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.ACCESS_PROHIBITED
  203. )
  204. jwt_token = create_token(
  205. data={"id": user.id},
  206. expires_delta=parse_duration(auth_manager_config.JWT_EXPIRES_IN),
  207. )
  208. # Set the cookie token
  209. response.set_cookie(
  210. key="token",
  211. value=jwt_token,
  212. httponly=True, # Ensures the cookie is not accessible via JavaScript
  213. samesite=WEBUI_SESSION_COOKIE_SAME_SITE,
  214. secure=WEBUI_SESSION_COOKIE_SECURE,
  215. )
  216. # Redirect back to the frontend with the JWT token
  217. redirect_url = f"{request.base_url}auth#token={jwt_token}"
  218. return RedirectResponse(url=redirect_url)
  219. oauth_manager = OAuthManager()