oauth.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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.models.auths import Auths
  14. from open_webui.models.users import Users
  15. from open_webui.models.groups import Groups, GroupModel, GroupUpdateForm
  16. from open_webui.config import (
  17. DEFAULT_USER_ROLE,
  18. ENABLE_OAUTH_SIGNUP,
  19. OAUTH_MERGE_ACCOUNTS_BY_EMAIL,
  20. OAUTH_PROVIDERS,
  21. ENABLE_OAUTH_ROLE_MANAGEMENT,
  22. ENABLE_OAUTH_GROUP_MANAGEMENT,
  23. OAUTH_ROLES_CLAIM,
  24. OAUTH_GROUPS_CLAIM,
  25. OAUTH_EMAIL_CLAIM,
  26. OAUTH_PICTURE_CLAIM,
  27. OAUTH_USERNAME_CLAIM,
  28. OAUTH_ALLOWED_ROLES,
  29. OAUTH_ADMIN_ROLES,
  30. OAUTH_ALLOWED_DOMAINS,
  31. WEBHOOK_URL,
  32. JWT_EXPIRES_IN,
  33. AppConfig,
  34. )
  35. from open_webui.constants import ERROR_MESSAGES, WEBHOOK_MESSAGES
  36. from open_webui.env import WEBUI_AUTH_COOKIE_SAME_SITE, WEBUI_AUTH_COOKIE_SECURE
  37. from open_webui.utils.misc import parse_duration
  38. from open_webui.utils.auth import get_password_hash, create_token
  39. from open_webui.utils.webhook import post_webhook
  40. log = logging.getLogger(__name__)
  41. auth_manager_config = AppConfig()
  42. auth_manager_config.DEFAULT_USER_ROLE = DEFAULT_USER_ROLE
  43. auth_manager_config.ENABLE_OAUTH_SIGNUP = ENABLE_OAUTH_SIGNUP
  44. auth_manager_config.OAUTH_MERGE_ACCOUNTS_BY_EMAIL = OAUTH_MERGE_ACCOUNTS_BY_EMAIL
  45. auth_manager_config.ENABLE_OAUTH_ROLE_MANAGEMENT = ENABLE_OAUTH_ROLE_MANAGEMENT
  46. auth_manager_config.ENABLE_OAUTH_GROUP_MANAGEMENT = ENABLE_OAUTH_GROUP_MANAGEMENT
  47. auth_manager_config.OAUTH_ROLES_CLAIM = OAUTH_ROLES_CLAIM
  48. auth_manager_config.OAUTH_GROUPS_CLAIM = OAUTH_GROUPS_CLAIM
  49. auth_manager_config.OAUTH_EMAIL_CLAIM = OAUTH_EMAIL_CLAIM
  50. auth_manager_config.OAUTH_PICTURE_CLAIM = OAUTH_PICTURE_CLAIM
  51. auth_manager_config.OAUTH_USERNAME_CLAIM = OAUTH_USERNAME_CLAIM
  52. auth_manager_config.OAUTH_ALLOWED_ROLES = OAUTH_ALLOWED_ROLES
  53. auth_manager_config.OAUTH_ADMIN_ROLES = OAUTH_ADMIN_ROLES
  54. auth_manager_config.OAUTH_ALLOWED_DOMAINS = OAUTH_ALLOWED_DOMAINS
  55. auth_manager_config.WEBHOOK_URL = WEBHOOK_URL
  56. auth_manager_config.JWT_EXPIRES_IN = JWT_EXPIRES_IN
  57. class OAuthManager:
  58. def __init__(self):
  59. self.oauth = OAuth()
  60. for _, provider_config in OAUTH_PROVIDERS.items():
  61. provider_config["register"](self.oauth)
  62. def get_client(self, provider_name):
  63. return self.oauth.create_client(provider_name)
  64. def get_user_role(self, user, user_data):
  65. if user and Users.get_num_users() == 1:
  66. # If the user is the only user, assign the role "admin" - actually repairs role for single user on login
  67. return "admin"
  68. if not user and Users.get_num_users() == 0:
  69. # If there are no users, assign the role "admin", as the first user will be an admin
  70. return "admin"
  71. if auth_manager_config.ENABLE_OAUTH_ROLE_MANAGEMENT:
  72. oauth_claim = auth_manager_config.OAUTH_ROLES_CLAIM
  73. oauth_allowed_roles = auth_manager_config.OAUTH_ALLOWED_ROLES
  74. oauth_admin_roles = auth_manager_config.OAUTH_ADMIN_ROLES
  75. oauth_roles = None
  76. role = (
  77. auth_manager_config.DEFAULT_USER_ROLE
  78. ) # Default/fallback role if no matching roles are found
  79. # Next block extracts the roles from the user data, accepting nested claims of any depth
  80. if oauth_claim and oauth_allowed_roles and oauth_admin_roles:
  81. claim_data = user_data
  82. nested_claims = oauth_claim.split(".")
  83. for nested_claim in nested_claims:
  84. claim_data = claim_data.get(nested_claim, {})
  85. oauth_roles = claim_data if isinstance(claim_data, list) else None
  86. # If any roles are found, check if they match the allowed or admin roles
  87. if oauth_roles:
  88. # If role management is enabled, and matching roles are provided, use the roles
  89. for allowed_role in oauth_allowed_roles:
  90. # If the user has any of the allowed roles, assign the role "user"
  91. if allowed_role in oauth_roles:
  92. role = "user"
  93. break
  94. for admin_role in oauth_admin_roles:
  95. # If the user has any of the admin roles, assign the role "admin"
  96. if admin_role in oauth_roles:
  97. role = "admin"
  98. break
  99. else:
  100. if not user:
  101. # If role management is disabled, use the default role for new users
  102. role = auth_manager_config.DEFAULT_USER_ROLE
  103. else:
  104. # If role management is disabled, use the existing role for existing users
  105. role = user.role
  106. return role
  107. def update_user_groups(self, user, user_data, default_permissions):
  108. oauth_claim = auth_manager_config.OAUTH_GROUPS_CLAIM
  109. user_oauth_groups: list[str] = user_data.get(oauth_claim, list())
  110. user_current_groups: list[GroupModel] = Groups.get_groups_by_member_id(user.id)
  111. all_available_groups: list[GroupModel] = Groups.get_groups()
  112. # Remove groups that user is no longer a part of
  113. for group_model in user_current_groups:
  114. if group_model.name not in user_oauth_groups:
  115. # Remove group from user
  116. user_ids = group_model.user_ids
  117. user_ids = [i for i in user_ids if i != user.id]
  118. # In case a group is created, but perms are never assigned to the group by hitting "save"
  119. group_permissions = group_model.permissions
  120. if not group_permissions:
  121. group_permissions = default_permissions
  122. update_form = GroupUpdateForm(
  123. name=group_model.name,
  124. description=group_model.description,
  125. permissions=group_permissions,
  126. user_ids=user_ids,
  127. )
  128. Groups.update_group_by_id(
  129. id=group_model.id, form_data=update_form, overwrite=False
  130. )
  131. # Add user to new groups
  132. for group_model in all_available_groups:
  133. if group_model.name in user_oauth_groups and not any(
  134. gm.name == group_model.name for gm in user_current_groups
  135. ):
  136. # Add user to group
  137. user_ids = group_model.user_ids
  138. user_ids.append(user.id)
  139. # In case a group is created, but perms are never assigned to the group by hitting "save"
  140. group_permissions = group_model.permissions
  141. if not group_permissions:
  142. group_permissions = default_permissions
  143. update_form = GroupUpdateForm(
  144. name=group_model.name,
  145. description=group_model.description,
  146. permissions=group_permissions,
  147. user_ids=user_ids,
  148. )
  149. Groups.update_group_by_id(
  150. id=group_model.id, form_data=update_form, overwrite=False
  151. )
  152. async def handle_login(self, provider, request):
  153. if provider not in OAUTH_PROVIDERS:
  154. raise HTTPException(404)
  155. # If the provider has a custom redirect URL, use that, otherwise automatically generate one
  156. redirect_uri = OAUTH_PROVIDERS[provider].get("redirect_uri") or request.url_for(
  157. "oauth_callback", provider=provider
  158. )
  159. client = self.get_client(provider)
  160. if client is None:
  161. raise HTTPException(404)
  162. return await client.authorize_redirect(request, redirect_uri)
  163. async def handle_callback(self, provider, request, response):
  164. if provider not in OAUTH_PROVIDERS:
  165. raise HTTPException(404)
  166. client = self.get_client(provider)
  167. try:
  168. token = await client.authorize_access_token(request)
  169. except Exception as e:
  170. log.warning(f"OAuth callback error: {e}")
  171. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  172. user_data: UserInfo = token.get("userinfo")
  173. if not user_data:
  174. user_data: UserInfo = await client.userinfo(token=token)
  175. if not user_data:
  176. log.warning(f"OAuth callback failed, user data is missing: {token}")
  177. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  178. sub = user_data.get(OAUTH_PROVIDERS[provider].get("sub_claim", "sub"))
  179. if not sub:
  180. log.warning(f"OAuth callback failed, sub is missing: {user_data}")
  181. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  182. provider_sub = f"{provider}@{sub}"
  183. email_claim = auth_manager_config.OAUTH_EMAIL_CLAIM
  184. email = user_data.get(email_claim, "").lower()
  185. # We currently mandate that email addresses are provided
  186. if not email:
  187. log.warning(f"OAuth callback failed, email is missing: {user_data}")
  188. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  189. if (
  190. "*" not in auth_manager_config.OAUTH_ALLOWED_DOMAINS
  191. and email.split("@")[-1] not in auth_manager_config.OAUTH_ALLOWED_DOMAINS
  192. ):
  193. log.warning(
  194. f"OAuth callback failed, e-mail domain is not in the list of allowed domains: {user_data}"
  195. )
  196. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  197. # Check if the user exists
  198. user = Users.get_user_by_oauth_sub(provider_sub)
  199. if not user:
  200. # If the user does not exist, check if merging is enabled
  201. if auth_manager_config.OAUTH_MERGE_ACCOUNTS_BY_EMAIL:
  202. # Check if the user exists by email
  203. user = Users.get_user_by_email(email)
  204. if user:
  205. # Update the user with the new oauth sub
  206. Users.update_user_oauth_sub_by_id(user.id, provider_sub)
  207. if user:
  208. determined_role = self.get_user_role(user, user_data)
  209. if user.role != determined_role:
  210. Users.update_user_role_by_id(user.id, determined_role)
  211. if not user:
  212. # If the user does not exist, check if signups are enabled
  213. if auth_manager_config.ENABLE_OAUTH_SIGNUP:
  214. # Check if an existing user with the same email already exists
  215. existing_user = Users.get_user_by_email(
  216. user_data.get("email", "").lower()
  217. )
  218. if existing_user:
  219. raise HTTPException(400, detail=ERROR_MESSAGES.EMAIL_TAKEN)
  220. picture_claim = auth_manager_config.OAUTH_PICTURE_CLAIM
  221. picture_url = user_data.get(
  222. picture_claim, OAUTH_PROVIDERS[provider].get("picture_url", "")
  223. )
  224. if picture_url:
  225. # Download the profile image into a base64 string
  226. try:
  227. access_token = token.get("access_token")
  228. get_kwargs = {}
  229. if access_token:
  230. get_kwargs["headers"] = {
  231. "Authorization": f"Bearer {access_token}",
  232. }
  233. async with aiohttp.ClientSession() as session:
  234. async with session.get(picture_url, **get_kwargs) as resp:
  235. picture = await resp.read()
  236. base64_encoded_picture = base64.b64encode(
  237. picture
  238. ).decode("utf-8")
  239. guessed_mime_type = mimetypes.guess_type(picture_url)[0]
  240. if guessed_mime_type is None:
  241. # assume JPG, browsers are tolerant enough of image formats
  242. guessed_mime_type = "image/jpeg"
  243. picture_url = f"data:{guessed_mime_type};base64,{base64_encoded_picture}"
  244. except Exception as e:
  245. log.error(
  246. f"Error downloading profile image '{picture_url}': {e}"
  247. )
  248. picture_url = ""
  249. if not picture_url:
  250. picture_url = "/user.png"
  251. username_claim = auth_manager_config.OAUTH_USERNAME_CLAIM
  252. name = user_data.get(username_claim)
  253. if not isinstance(user, str):
  254. name = email
  255. role = self.get_user_role(None, user_data)
  256. user = Auths.insert_new_auth(
  257. email=email,
  258. password=get_password_hash(
  259. str(uuid.uuid4())
  260. ), # Random password, not used
  261. name=name,
  262. profile_image_url=picture_url,
  263. role=role,
  264. oauth_sub=provider_sub,
  265. )
  266. if auth_manager_config.WEBHOOK_URL:
  267. post_webhook(
  268. auth_manager_config.WEBHOOK_URL,
  269. WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  270. {
  271. "action": "signup",
  272. "message": WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  273. "user": user.model_dump_json(exclude_none=True),
  274. },
  275. )
  276. else:
  277. raise HTTPException(
  278. status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.ACCESS_PROHIBITED
  279. )
  280. jwt_token = create_token(
  281. data={"id": user.id},
  282. expires_delta=parse_duration(auth_manager_config.JWT_EXPIRES_IN),
  283. )
  284. if auth_manager_config.ENABLE_OAUTH_GROUP_MANAGEMENT and user.role != "admin":
  285. self.update_user_groups(
  286. user=user,
  287. user_data=user_data,
  288. default_permissions=request.app.state.config.USER_PERMISSIONS,
  289. )
  290. # Set the cookie token
  291. response.set_cookie(
  292. key="token",
  293. value=jwt_token,
  294. httponly=True, # Ensures the cookie is not accessible via JavaScript
  295. samesite=WEBUI_AUTH_COOKIE_SAME_SITE,
  296. secure=WEBUI_AUTH_COOKIE_SECURE,
  297. )
  298. if ENABLE_OAUTH_SIGNUP.value:
  299. oauth_id_token = token.get("id_token")
  300. response.set_cookie(
  301. key="oauth_id_token",
  302. value=oauth_id_token,
  303. httponly=True,
  304. samesite=WEBUI_AUTH_COOKIE_SAME_SITE,
  305. secure=WEBUI_AUTH_COOKIE_SECURE,
  306. )
  307. # Redirect back to the frontend with the JWT token
  308. redirect_url = f"{request.base_url}auth#token={jwt_token}"
  309. return RedirectResponse(url=redirect_url, headers=response.headers)
  310. oauth_manager = OAuthManager()