oauth.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656
  1. import base64
  2. import logging
  3. import mimetypes
  4. import sys
  5. import uuid
  6. import json
  7. import re
  8. import fnmatch
  9. import aiohttp
  10. from authlib.integrations.starlette_client import OAuth
  11. from authlib.oidc.core import UserInfo
  12. from fastapi import (
  13. HTTPException,
  14. status,
  15. )
  16. from starlette.responses import RedirectResponse
  17. from open_webui.models.auths import Auths
  18. from open_webui.models.users import Users
  19. from open_webui.models.groups import Groups, GroupModel, GroupUpdateForm, GroupForm
  20. from open_webui.config import (
  21. DEFAULT_USER_ROLE,
  22. ENABLE_OAUTH_SIGNUP,
  23. OAUTH_MERGE_ACCOUNTS_BY_EMAIL,
  24. OAUTH_PROVIDERS,
  25. ENABLE_OAUTH_ROLE_MANAGEMENT,
  26. ENABLE_OAUTH_GROUP_MANAGEMENT,
  27. ENABLE_OAUTH_GROUP_CREATION,
  28. OAUTH_BLOCKED_GROUPS,
  29. OAUTH_ROLES_CLAIM,
  30. OAUTH_SUB_CLAIM,
  31. OAUTH_GROUPS_CLAIM,
  32. OAUTH_EMAIL_CLAIM,
  33. OAUTH_PICTURE_CLAIM,
  34. OAUTH_USERNAME_CLAIM,
  35. OAUTH_ALLOWED_ROLES,
  36. OAUTH_ADMIN_ROLES,
  37. OAUTH_ALLOWED_DOMAINS,
  38. OAUTH_UPDATE_PICTURE_ON_LOGIN,
  39. WEBHOOK_URL,
  40. JWT_EXPIRES_IN,
  41. AppConfig,
  42. )
  43. from open_webui.constants import ERROR_MESSAGES, WEBHOOK_MESSAGES
  44. from open_webui.env import (
  45. AIOHTTP_CLIENT_SESSION_SSL,
  46. WEBUI_NAME,
  47. WEBUI_AUTH_COOKIE_SAME_SITE,
  48. WEBUI_AUTH_COOKIE_SECURE,
  49. ENABLE_OAUTH_SESSION_TOKENS_COOKIES,
  50. )
  51. from open_webui.utils.misc import parse_duration
  52. from open_webui.utils.auth import get_password_hash, create_token
  53. from open_webui.utils.webhook import post_webhook
  54. from open_webui.env import SRC_LOG_LEVELS, GLOBAL_LOG_LEVEL
  55. logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
  56. log = logging.getLogger(__name__)
  57. log.setLevel(SRC_LOG_LEVELS["OAUTH"])
  58. auth_manager_config = AppConfig()
  59. auth_manager_config.DEFAULT_USER_ROLE = DEFAULT_USER_ROLE
  60. auth_manager_config.ENABLE_OAUTH_SIGNUP = ENABLE_OAUTH_SIGNUP
  61. auth_manager_config.OAUTH_MERGE_ACCOUNTS_BY_EMAIL = OAUTH_MERGE_ACCOUNTS_BY_EMAIL
  62. auth_manager_config.ENABLE_OAUTH_ROLE_MANAGEMENT = ENABLE_OAUTH_ROLE_MANAGEMENT
  63. auth_manager_config.ENABLE_OAUTH_GROUP_MANAGEMENT = ENABLE_OAUTH_GROUP_MANAGEMENT
  64. auth_manager_config.ENABLE_OAUTH_GROUP_CREATION = ENABLE_OAUTH_GROUP_CREATION
  65. auth_manager_config.OAUTH_BLOCKED_GROUPS = OAUTH_BLOCKED_GROUPS
  66. auth_manager_config.OAUTH_ROLES_CLAIM = OAUTH_ROLES_CLAIM
  67. auth_manager_config.OAUTH_SUB_CLAIM = OAUTH_SUB_CLAIM
  68. auth_manager_config.OAUTH_GROUPS_CLAIM = OAUTH_GROUPS_CLAIM
  69. auth_manager_config.OAUTH_EMAIL_CLAIM = OAUTH_EMAIL_CLAIM
  70. auth_manager_config.OAUTH_PICTURE_CLAIM = OAUTH_PICTURE_CLAIM
  71. auth_manager_config.OAUTH_USERNAME_CLAIM = OAUTH_USERNAME_CLAIM
  72. auth_manager_config.OAUTH_ALLOWED_ROLES = OAUTH_ALLOWED_ROLES
  73. auth_manager_config.OAUTH_ADMIN_ROLES = OAUTH_ADMIN_ROLES
  74. auth_manager_config.OAUTH_ALLOWED_DOMAINS = OAUTH_ALLOWED_DOMAINS
  75. auth_manager_config.WEBHOOK_URL = WEBHOOK_URL
  76. auth_manager_config.JWT_EXPIRES_IN = JWT_EXPIRES_IN
  77. auth_manager_config.OAUTH_UPDATE_PICTURE_ON_LOGIN = OAUTH_UPDATE_PICTURE_ON_LOGIN
  78. def is_in_blocked_groups(group_name: str, groups: list) -> bool:
  79. """
  80. Check if a group name matches any blocked pattern.
  81. Supports exact matches, shell-style wildcards (*, ?), and regex patterns.
  82. Args:
  83. group_name: The group name to check
  84. groups: List of patterns to match against
  85. Returns:
  86. True if the group is blocked, False otherwise
  87. """
  88. if not groups:
  89. return False
  90. for group_pattern in groups:
  91. if not group_pattern: # Skip empty patterns
  92. continue
  93. # Exact match
  94. if group_name == group_pattern:
  95. return True
  96. # Try as regex pattern first if it contains regex-specific characters
  97. if any(
  98. char in group_pattern
  99. for char in ["^", "$", "[", "]", "(", ")", "{", "}", "+", "\\", "|"]
  100. ):
  101. try:
  102. # Use the original pattern as-is for regex matching
  103. if re.search(group_pattern, group_name):
  104. return True
  105. except re.error:
  106. # If regex is invalid, fall through to wildcard check
  107. pass
  108. # Shell-style wildcard match (supports * and ?)
  109. if "*" in group_pattern or "?" in group_pattern:
  110. if fnmatch.fnmatch(group_name, group_pattern):
  111. return True
  112. return False
  113. class OAuthManager:
  114. def __init__(self, app):
  115. self.oauth = OAuth()
  116. self.app = app
  117. for _, provider_config in OAUTH_PROVIDERS.items():
  118. provider_config["register"](self.oauth)
  119. def get_client(self, provider_name):
  120. return self.oauth.create_client(provider_name)
  121. def get_user_role(self, user, user_data):
  122. user_count = Users.get_num_users()
  123. if user and user_count == 1:
  124. # If the user is the only user, assign the role "admin" - actually repairs role for single user on login
  125. log.debug("Assigning the only user the admin role")
  126. return "admin"
  127. if not user and user_count == 0:
  128. # If there are no users, assign the role "admin", as the first user will be an admin
  129. log.debug("Assigning the first user the admin role")
  130. return "admin"
  131. if auth_manager_config.ENABLE_OAUTH_ROLE_MANAGEMENT:
  132. log.debug("Running OAUTH Role management")
  133. oauth_claim = auth_manager_config.OAUTH_ROLES_CLAIM
  134. oauth_allowed_roles = auth_manager_config.OAUTH_ALLOWED_ROLES
  135. oauth_admin_roles = auth_manager_config.OAUTH_ADMIN_ROLES
  136. oauth_roles = []
  137. # Default/fallback role if no matching roles are found
  138. role = auth_manager_config.DEFAULT_USER_ROLE
  139. # Next block extracts the roles from the user data, accepting nested claims of any depth
  140. if oauth_claim and oauth_allowed_roles and oauth_admin_roles:
  141. claim_data = user_data
  142. nested_claims = oauth_claim.split(".")
  143. for nested_claim in nested_claims:
  144. claim_data = claim_data.get(nested_claim, {})
  145. oauth_roles = []
  146. if isinstance(claim_data, list):
  147. oauth_roles = claim_data
  148. if isinstance(claim_data, str) or isinstance(claim_data, int):
  149. oauth_roles = [str(claim_data)]
  150. log.debug(f"Oauth Roles claim: {oauth_claim}")
  151. log.debug(f"User roles from oauth: {oauth_roles}")
  152. log.debug(f"Accepted user roles: {oauth_allowed_roles}")
  153. log.debug(f"Accepted admin roles: {oauth_admin_roles}")
  154. # If any roles are found, check if they match the allowed or admin roles
  155. if oauth_roles:
  156. # If role management is enabled, and matching roles are provided, use the roles
  157. for allowed_role in oauth_allowed_roles:
  158. # If the user has any of the allowed roles, assign the role "user"
  159. if allowed_role in oauth_roles:
  160. log.debug("Assigned user the user role")
  161. role = "user"
  162. break
  163. for admin_role in oauth_admin_roles:
  164. # If the user has any of the admin roles, assign the role "admin"
  165. if admin_role in oauth_roles:
  166. log.debug("Assigned user the admin role")
  167. role = "admin"
  168. break
  169. else:
  170. if not user:
  171. # If role management is disabled, use the default role for new users
  172. role = auth_manager_config.DEFAULT_USER_ROLE
  173. else:
  174. # If role management is disabled, use the existing role for existing users
  175. role = user.role
  176. return role
  177. def update_user_groups(self, user, user_data, default_permissions):
  178. log.debug("Running OAUTH Group management")
  179. oauth_claim = auth_manager_config.OAUTH_GROUPS_CLAIM
  180. try:
  181. blocked_groups = json.loads(auth_manager_config.OAUTH_BLOCKED_GROUPS)
  182. except Exception as e:
  183. log.exception(f"Error loading OAUTH_BLOCKED_GROUPS: {e}")
  184. blocked_groups = []
  185. user_oauth_groups = []
  186. # Nested claim search for groups claim
  187. if oauth_claim:
  188. claim_data = user_data
  189. nested_claims = oauth_claim.split(".")
  190. for nested_claim in nested_claims:
  191. claim_data = claim_data.get(nested_claim, {})
  192. if isinstance(claim_data, list):
  193. user_oauth_groups = claim_data
  194. elif isinstance(claim_data, str):
  195. user_oauth_groups = [claim_data]
  196. else:
  197. user_oauth_groups = []
  198. user_current_groups: list[GroupModel] = Groups.get_groups_by_member_id(user.id)
  199. all_available_groups: list[GroupModel] = Groups.get_groups()
  200. # Create groups if they don't exist and creation is enabled
  201. if auth_manager_config.ENABLE_OAUTH_GROUP_CREATION:
  202. log.debug("Checking for missing groups to create...")
  203. all_group_names = {g.name for g in all_available_groups}
  204. groups_created = False
  205. # Determine creator ID: Prefer admin, fallback to current user if no admin exists
  206. admin_user = Users.get_super_admin_user()
  207. creator_id = admin_user.id if admin_user else user.id
  208. log.debug(f"Using creator ID {creator_id} for potential group creation.")
  209. for group_name in user_oauth_groups:
  210. if group_name not in all_group_names:
  211. log.info(
  212. f"Group '{group_name}' not found via OAuth claim. Creating group..."
  213. )
  214. try:
  215. new_group_form = GroupForm(
  216. name=group_name,
  217. description=f"Group '{group_name}' created automatically via OAuth.",
  218. permissions=default_permissions, # Use default permissions from function args
  219. user_ids=[], # Start with no users, user will be added later by subsequent logic
  220. )
  221. # Use determined creator ID (admin or fallback to current user)
  222. created_group = Groups.insert_new_group(
  223. creator_id, new_group_form
  224. )
  225. if created_group:
  226. log.info(
  227. f"Successfully created group '{group_name}' with ID {created_group.id} using creator ID {creator_id}"
  228. )
  229. groups_created = True
  230. # Add to local set to prevent duplicate creation attempts in this run
  231. all_group_names.add(group_name)
  232. else:
  233. log.error(
  234. f"Failed to create group '{group_name}' via OAuth."
  235. )
  236. except Exception as e:
  237. log.error(f"Error creating group '{group_name}' via OAuth: {e}")
  238. # Refresh the list of all available groups if any were created
  239. if groups_created:
  240. all_available_groups = Groups.get_groups()
  241. log.debug("Refreshed list of all available groups after creation.")
  242. log.debug(f"Oauth Groups claim: {oauth_claim}")
  243. log.debug(f"User oauth groups: {user_oauth_groups}")
  244. log.debug(f"User's current groups: {[g.name for g in user_current_groups]}")
  245. log.debug(
  246. f"All groups available in OpenWebUI: {[g.name for g in all_available_groups]}"
  247. )
  248. # Remove groups that user is no longer a part of
  249. for group_model in user_current_groups:
  250. if (
  251. user_oauth_groups
  252. and group_model.name not in user_oauth_groups
  253. and not is_in_blocked_groups(group_model.name, blocked_groups)
  254. ):
  255. # Remove group from user
  256. log.debug(
  257. f"Removing user from group {group_model.name} as it is no longer in their oauth groups"
  258. )
  259. user_ids = group_model.user_ids
  260. user_ids = [i for i in user_ids if i != user.id]
  261. # In case a group is created, but perms are never assigned to the group by hitting "save"
  262. group_permissions = group_model.permissions
  263. if not group_permissions:
  264. group_permissions = default_permissions
  265. update_form = GroupUpdateForm(
  266. name=group_model.name,
  267. description=group_model.description,
  268. permissions=group_permissions,
  269. user_ids=user_ids,
  270. )
  271. Groups.update_group_by_id(
  272. id=group_model.id, form_data=update_form, overwrite=False
  273. )
  274. # Add user to new groups
  275. for group_model in all_available_groups:
  276. if (
  277. user_oauth_groups
  278. and group_model.name in user_oauth_groups
  279. and not any(gm.name == group_model.name for gm in user_current_groups)
  280. and not is_in_blocked_groups(group_model.name, blocked_groups)
  281. ):
  282. # Add user to group
  283. log.debug(
  284. f"Adding user to group {group_model.name} as it was found in their oauth groups"
  285. )
  286. user_ids = group_model.user_ids
  287. user_ids.append(user.id)
  288. # In case a group is created, but perms are never assigned to the group by hitting "save"
  289. group_permissions = group_model.permissions
  290. if not group_permissions:
  291. group_permissions = default_permissions
  292. update_form = GroupUpdateForm(
  293. name=group_model.name,
  294. description=group_model.description,
  295. permissions=group_permissions,
  296. user_ids=user_ids,
  297. )
  298. Groups.update_group_by_id(
  299. id=group_model.id, form_data=update_form, overwrite=False
  300. )
  301. async def _process_picture_url(
  302. self, picture_url: str, access_token: str = None
  303. ) -> str:
  304. """Process a picture URL and return a base64 encoded data URL.
  305. Args:
  306. picture_url: The URL of the picture to process
  307. access_token: Optional OAuth access token for authenticated requests
  308. Returns:
  309. A data URL containing the base64 encoded picture, or "/user.png" if processing fails
  310. """
  311. if not picture_url:
  312. return "/user.png"
  313. try:
  314. get_kwargs = {}
  315. if access_token:
  316. get_kwargs["headers"] = {
  317. "Authorization": f"Bearer {access_token}",
  318. }
  319. async with aiohttp.ClientSession(trust_env=True) as session:
  320. async with session.get(
  321. picture_url, **get_kwargs, ssl=AIOHTTP_CLIENT_SESSION_SSL
  322. ) as resp:
  323. if resp.ok:
  324. picture = await resp.read()
  325. base64_encoded_picture = base64.b64encode(picture).decode(
  326. "utf-8"
  327. )
  328. guessed_mime_type = mimetypes.guess_type(picture_url)[0]
  329. if guessed_mime_type is None:
  330. guessed_mime_type = "image/jpeg"
  331. return (
  332. f"data:{guessed_mime_type};base64,{base64_encoded_picture}"
  333. )
  334. else:
  335. log.warning(
  336. f"Failed to fetch profile picture from {picture_url}"
  337. )
  338. return "/user.png"
  339. except Exception as e:
  340. log.error(f"Error processing profile picture '{picture_url}': {e}")
  341. return "/user.png"
  342. async def handle_login(self, request, provider):
  343. if provider not in OAUTH_PROVIDERS:
  344. raise HTTPException(404)
  345. # If the provider has a custom redirect URL, use that, otherwise automatically generate one
  346. redirect_uri = OAUTH_PROVIDERS[provider].get("redirect_uri") or request.url_for(
  347. "oauth_callback", provider=provider
  348. )
  349. client = self.get_client(provider)
  350. if client is None:
  351. raise HTTPException(404)
  352. return await client.authorize_redirect(request, redirect_uri)
  353. async def handle_callback(self, request, provider, response):
  354. if provider not in OAUTH_PROVIDERS:
  355. raise HTTPException(404)
  356. error_message = None
  357. try:
  358. client = self.get_client(provider)
  359. try:
  360. token = await client.authorize_access_token(request)
  361. except Exception as e:
  362. log.warning(f"OAuth callback error: {e}")
  363. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  364. # Try to get userinfo from the token first, some providers include it there
  365. user_data: UserInfo = token.get("userinfo")
  366. if (
  367. (not user_data)
  368. or (auth_manager_config.OAUTH_EMAIL_CLAIM not in user_data)
  369. or (auth_manager_config.OAUTH_USERNAME_CLAIM not in user_data)
  370. ):
  371. user_data: UserInfo = await client.userinfo(token=token)
  372. if not user_data:
  373. log.warning(f"OAuth callback failed, user data is missing: {token}")
  374. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  375. # Extract the "sub" claim, using custom claim if configured
  376. if auth_manager_config.OAUTH_SUB_CLAIM:
  377. sub = user_data.get(auth_manager_config.OAUTH_SUB_CLAIM)
  378. else:
  379. # Fallback to the default sub claim if not configured
  380. sub = user_data.get(OAUTH_PROVIDERS[provider].get("sub_claim", "sub"))
  381. if not sub:
  382. log.warning(f"OAuth callback failed, sub is missing: {user_data}")
  383. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  384. provider_sub = f"{provider}@{sub}"
  385. # Email extraction
  386. email_claim = auth_manager_config.OAUTH_EMAIL_CLAIM
  387. email = user_data.get(email_claim, "")
  388. # We currently mandate that email addresses are provided
  389. if not email:
  390. # If the provider is GitHub,and public email is not provided, we can use the access token to fetch the user's email
  391. if provider == "github":
  392. try:
  393. access_token = token.get("access_token")
  394. headers = {"Authorization": f"Bearer {access_token}"}
  395. async with aiohttp.ClientSession(trust_env=True) as session:
  396. async with session.get(
  397. "https://api.github.com/user/emails",
  398. headers=headers,
  399. ssl=AIOHTTP_CLIENT_SESSION_SSL,
  400. ) as resp:
  401. if resp.ok:
  402. emails = await resp.json()
  403. # use the primary email as the user's email
  404. primary_email = next(
  405. (
  406. e["email"]
  407. for e in emails
  408. if e.get("primary")
  409. ),
  410. None,
  411. )
  412. if primary_email:
  413. email = primary_email
  414. else:
  415. log.warning(
  416. "No primary email found in GitHub response"
  417. )
  418. raise HTTPException(
  419. 400, detail=ERROR_MESSAGES.INVALID_CRED
  420. )
  421. else:
  422. log.warning("Failed to fetch GitHub email")
  423. raise HTTPException(
  424. 400, detail=ERROR_MESSAGES.INVALID_CRED
  425. )
  426. except Exception as e:
  427. log.warning(f"Error fetching GitHub email: {e}")
  428. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  429. else:
  430. log.warning(f"OAuth callback failed, email is missing: {user_data}")
  431. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  432. email = email.lower()
  433. # If allowed domains are configured, check if the email domain is in the list
  434. if (
  435. "*" not in auth_manager_config.OAUTH_ALLOWED_DOMAINS
  436. and email.split("@")[-1]
  437. not in auth_manager_config.OAUTH_ALLOWED_DOMAINS
  438. ):
  439. log.warning(
  440. f"OAuth callback failed, e-mail domain is not in the list of allowed domains: {user_data}"
  441. )
  442. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  443. # Check if the user exists
  444. user = Users.get_user_by_oauth_sub(provider_sub)
  445. if not user:
  446. # If the user does not exist, check if merging is enabled
  447. if auth_manager_config.OAUTH_MERGE_ACCOUNTS_BY_EMAIL:
  448. # Check if the user exists by email
  449. user = Users.get_user_by_email(email)
  450. if user:
  451. # Update the user with the new oauth sub
  452. Users.update_user_oauth_sub_by_id(user.id, provider_sub)
  453. if user:
  454. determined_role = self.get_user_role(user, user_data)
  455. if user.role != determined_role:
  456. Users.update_user_role_by_id(user.id, determined_role)
  457. # Update profile picture if enabled and different from current
  458. if auth_manager_config.OAUTH_UPDATE_PICTURE_ON_LOGIN:
  459. picture_claim = auth_manager_config.OAUTH_PICTURE_CLAIM
  460. if picture_claim:
  461. new_picture_url = user_data.get(
  462. picture_claim,
  463. OAUTH_PROVIDERS[provider].get("picture_url", ""),
  464. )
  465. processed_picture_url = await self._process_picture_url(
  466. new_picture_url, token.get("access_token")
  467. )
  468. if processed_picture_url != user.profile_image_url:
  469. Users.update_user_profile_image_url_by_id(
  470. user.id, processed_picture_url
  471. )
  472. log.debug(f"Updated profile picture for user {user.email}")
  473. else:
  474. # If the user does not exist, check if signups are enabled
  475. if auth_manager_config.ENABLE_OAUTH_SIGNUP:
  476. # Check if an existing user with the same email already exists
  477. existing_user = Users.get_user_by_email(email)
  478. if existing_user:
  479. raise HTTPException(400, detail=ERROR_MESSAGES.EMAIL_TAKEN)
  480. picture_claim = auth_manager_config.OAUTH_PICTURE_CLAIM
  481. if picture_claim:
  482. picture_url = user_data.get(
  483. picture_claim,
  484. OAUTH_PROVIDERS[provider].get("picture_url", ""),
  485. )
  486. picture_url = await self._process_picture_url(
  487. picture_url, token.get("access_token")
  488. )
  489. else:
  490. picture_url = "/user.png"
  491. username_claim = auth_manager_config.OAUTH_USERNAME_CLAIM
  492. name = user_data.get(username_claim)
  493. if not name:
  494. log.warning("Username claim is missing, using email as name")
  495. name = email
  496. user = Auths.insert_new_auth(
  497. email=email,
  498. password=get_password_hash(
  499. str(uuid.uuid4())
  500. ), # Random password, not used
  501. name=name,
  502. profile_image_url=picture_url,
  503. role=self.get_user_role(None, user_data),
  504. oauth_sub=provider_sub,
  505. )
  506. if auth_manager_config.WEBHOOK_URL:
  507. await post_webhook(
  508. WEBUI_NAME,
  509. auth_manager_config.WEBHOOK_URL,
  510. WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  511. {
  512. "action": "signup",
  513. "message": WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  514. "user": user.model_dump_json(exclude_none=True),
  515. },
  516. )
  517. else:
  518. raise HTTPException(
  519. status.HTTP_403_FORBIDDEN,
  520. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  521. )
  522. jwt_token = create_token(
  523. data={"id": user.id},
  524. expires_delta=parse_duration(auth_manager_config.JWT_EXPIRES_IN),
  525. )
  526. if (
  527. auth_manager_config.ENABLE_OAUTH_GROUP_MANAGEMENT
  528. and user.role != "admin"
  529. ):
  530. self.update_user_groups(
  531. user=user,
  532. user_data=user_data,
  533. default_permissions=request.app.state.config.USER_PERMISSIONS,
  534. )
  535. except Exception as e:
  536. log.error(f"Error during OAuth process: {e}")
  537. error_message = (
  538. e.detail
  539. if isinstance(e, HTTPException) and e.detail
  540. else ERROR_MESSAGES.DEFAULT("Error during OAuth process")
  541. )
  542. redirect_base_url = str(request.app.state.config.WEBUI_URL or request.base_url)
  543. if redirect_base_url.endswith("/"):
  544. redirect_base_url = redirect_base_url[:-1]
  545. redirect_url = f"{redirect_base_url}/auth"
  546. if error_message:
  547. redirect_url = f"{redirect_url}?error={error_message}"
  548. return RedirectResponse(url=redirect_url, headers=response.headers)
  549. response = RedirectResponse(url=redirect_url, headers=response.headers)
  550. # Set the cookie token
  551. # Redirect back to the frontend with the JWT token
  552. response.set_cookie(
  553. key="token",
  554. value=jwt_token,
  555. httponly=False, # Required for frontend access
  556. samesite=WEBUI_AUTH_COOKIE_SAME_SITE,
  557. secure=WEBUI_AUTH_COOKIE_SECURE,
  558. )
  559. if ENABLE_OAUTH_SIGNUP.value:
  560. if ENABLE_OAUTH_SESSION_TOKENS_COOKIES:
  561. oauth_id_token = token.get("id_token")
  562. response.set_cookie(
  563. key="oauth_id_token",
  564. value=oauth_id_token,
  565. httponly=True,
  566. samesite=WEBUI_AUTH_COOKIE_SAME_SITE,
  567. secure=WEBUI_AUTH_COOKIE_SECURE,
  568. )
  569. oauth_access_token = token.get("access_token")
  570. response.set_cookie(
  571. key="oauth_access_token",
  572. value=oauth_access_token,
  573. httponly=True,
  574. samesite=WEBUI_AUTH_COOKIE_SAME_SITE,
  575. secure=WEBUI_AUTH_COOKIE_SECURE,
  576. )
  577. oauth_refresh_token = token.get("refresh_token")
  578. response.set_cookie(
  579. key="oauth_refresh_token",
  580. value=oauth_refresh_token,
  581. httponly=True,
  582. samesite=WEBUI_AUTH_COOKIE_SAME_SITE,
  583. secure=WEBUI_AUTH_COOKIE_SECURE,
  584. )
  585. return response