oauth.py 12 KB

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