oauth.py 10 KB

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