oauth.py 26 KB

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