oauth.py 12 KB

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