auths.py 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072
  1. import re
  2. import uuid
  3. import time
  4. import datetime
  5. import logging
  6. from aiohttp import ClientSession
  7. from open_webui.models.auths import (
  8. AddUserForm,
  9. ApiKey,
  10. Auths,
  11. Token,
  12. LdapForm,
  13. SigninForm,
  14. SigninResponse,
  15. SignupForm,
  16. UpdatePasswordForm,
  17. UserResponse,
  18. )
  19. from open_webui.models.users import Users, UpdateProfileForm
  20. from open_webui.models.groups import Groups
  21. from open_webui.models.oauth_sessions import OAuthSessions
  22. from open_webui.constants import ERROR_MESSAGES, WEBHOOK_MESSAGES
  23. from open_webui.env import (
  24. WEBUI_AUTH,
  25. WEBUI_AUTH_TRUSTED_EMAIL_HEADER,
  26. WEBUI_AUTH_TRUSTED_NAME_HEADER,
  27. WEBUI_AUTH_TRUSTED_GROUPS_HEADER,
  28. WEBUI_AUTH_COOKIE_SAME_SITE,
  29. WEBUI_AUTH_COOKIE_SECURE,
  30. WEBUI_AUTH_SIGNOUT_REDIRECT_URL,
  31. ENABLE_INITIAL_ADMIN_SIGNUP,
  32. SRC_LOG_LEVELS,
  33. )
  34. from fastapi import APIRouter, Depends, HTTPException, Request, status
  35. from fastapi.responses import RedirectResponse, Response, JSONResponse
  36. from open_webui.config import OPENID_PROVIDER_URL, ENABLE_OAUTH_SIGNUP, ENABLE_LDAP
  37. from pydantic import BaseModel
  38. from open_webui.utils.misc import parse_duration, validate_email_format
  39. from open_webui.utils.auth import (
  40. decode_token,
  41. create_api_key,
  42. create_token,
  43. get_admin_user,
  44. get_verified_user,
  45. get_current_user,
  46. get_password_hash,
  47. get_http_authorization_cred,
  48. )
  49. from open_webui.utils.webhook import post_webhook
  50. from open_webui.utils.access_control import get_permissions
  51. from typing import Optional, List
  52. from ssl import CERT_NONE, CERT_REQUIRED, PROTOCOL_TLS
  53. from ldap3 import Server, Connection, NONE, Tls
  54. from ldap3.utils.conv import escape_filter_chars
  55. router = APIRouter()
  56. log = logging.getLogger(__name__)
  57. log.setLevel(SRC_LOG_LEVELS["MAIN"])
  58. ############################
  59. # GetSessionUser
  60. ############################
  61. class SessionUserResponse(Token, UserResponse):
  62. expires_at: Optional[int] = None
  63. permissions: Optional[dict] = None
  64. class SessionUserInfoResponse(SessionUserResponse):
  65. bio: Optional[str] = None
  66. gender: Optional[str] = None
  67. date_of_birth: Optional[datetime.date] = None
  68. @router.get("/", response_model=SessionUserInfoResponse)
  69. async def get_session_user(
  70. request: Request, response: Response, user=Depends(get_current_user)
  71. ):
  72. auth_header = request.headers.get("Authorization")
  73. auth_token = get_http_authorization_cred(auth_header)
  74. token = auth_token.credentials
  75. data = decode_token(token)
  76. expires_at = None
  77. if data:
  78. expires_at = data.get("exp")
  79. if (expires_at is not None) and int(time.time()) > expires_at:
  80. raise HTTPException(
  81. status_code=status.HTTP_401_UNAUTHORIZED,
  82. detail=ERROR_MESSAGES.INVALID_TOKEN,
  83. )
  84. # Set the cookie token
  85. response.set_cookie(
  86. key="token",
  87. value=token,
  88. expires=(
  89. datetime.datetime.fromtimestamp(expires_at, datetime.timezone.utc)
  90. if expires_at
  91. else None
  92. ),
  93. httponly=True, # Ensures the cookie is not accessible via JavaScript
  94. samesite=WEBUI_AUTH_COOKIE_SAME_SITE,
  95. secure=WEBUI_AUTH_COOKIE_SECURE,
  96. )
  97. user_permissions = get_permissions(
  98. user.id, request.app.state.config.USER_PERMISSIONS
  99. )
  100. return {
  101. "token": token,
  102. "token_type": "Bearer",
  103. "expires_at": expires_at,
  104. "id": user.id,
  105. "email": user.email,
  106. "name": user.name,
  107. "role": user.role,
  108. "profile_image_url": user.profile_image_url,
  109. "bio": user.bio,
  110. "gender": user.gender,
  111. "date_of_birth": user.date_of_birth,
  112. "permissions": user_permissions,
  113. }
  114. ############################
  115. # Update Profile
  116. ############################
  117. @router.post("/update/profile", response_model=UserResponse)
  118. async def update_profile(
  119. form_data: UpdateProfileForm, session_user=Depends(get_verified_user)
  120. ):
  121. if session_user:
  122. user = Users.update_user_by_id(
  123. session_user.id,
  124. form_data.model_dump(),
  125. )
  126. if user:
  127. return user
  128. else:
  129. raise HTTPException(400, detail=ERROR_MESSAGES.DEFAULT())
  130. else:
  131. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  132. ############################
  133. # Update Password
  134. ############################
  135. @router.post("/update/password", response_model=bool)
  136. async def update_password(
  137. form_data: UpdatePasswordForm, session_user=Depends(get_current_user)
  138. ):
  139. if WEBUI_AUTH_TRUSTED_EMAIL_HEADER:
  140. raise HTTPException(400, detail=ERROR_MESSAGES.ACTION_PROHIBITED)
  141. if session_user:
  142. user = Auths.authenticate_user(session_user.email, form_data.password)
  143. if user:
  144. hashed = get_password_hash(form_data.new_password)
  145. return Auths.update_user_password_by_id(user.id, hashed)
  146. else:
  147. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_PASSWORD)
  148. else:
  149. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  150. ############################
  151. # LDAP Authentication
  152. ############################
  153. @router.post("/ldap", response_model=SessionUserResponse)
  154. async def ldap_auth(request: Request, response: Response, form_data: LdapForm):
  155. ENABLE_LDAP = request.app.state.config.ENABLE_LDAP
  156. LDAP_SERVER_LABEL = request.app.state.config.LDAP_SERVER_LABEL
  157. LDAP_SERVER_HOST = request.app.state.config.LDAP_SERVER_HOST
  158. LDAP_SERVER_PORT = request.app.state.config.LDAP_SERVER_PORT
  159. LDAP_ATTRIBUTE_FOR_MAIL = request.app.state.config.LDAP_ATTRIBUTE_FOR_MAIL
  160. LDAP_ATTRIBUTE_FOR_USERNAME = request.app.state.config.LDAP_ATTRIBUTE_FOR_USERNAME
  161. LDAP_SEARCH_BASE = request.app.state.config.LDAP_SEARCH_BASE
  162. LDAP_SEARCH_FILTERS = request.app.state.config.LDAP_SEARCH_FILTERS
  163. LDAP_APP_DN = request.app.state.config.LDAP_APP_DN
  164. LDAP_APP_PASSWORD = request.app.state.config.LDAP_APP_PASSWORD
  165. LDAP_USE_TLS = request.app.state.config.LDAP_USE_TLS
  166. LDAP_CA_CERT_FILE = request.app.state.config.LDAP_CA_CERT_FILE
  167. LDAP_VALIDATE_CERT = (
  168. CERT_REQUIRED if request.app.state.config.LDAP_VALIDATE_CERT else CERT_NONE
  169. )
  170. LDAP_CIPHERS = (
  171. request.app.state.config.LDAP_CIPHERS
  172. if request.app.state.config.LDAP_CIPHERS
  173. else "ALL"
  174. )
  175. if not ENABLE_LDAP:
  176. raise HTTPException(400, detail="LDAP authentication is not enabled")
  177. try:
  178. tls = Tls(
  179. validate=LDAP_VALIDATE_CERT,
  180. version=PROTOCOL_TLS,
  181. ca_certs_file=LDAP_CA_CERT_FILE,
  182. ciphers=LDAP_CIPHERS,
  183. )
  184. except Exception as e:
  185. log.error(f"TLS configuration error: {str(e)}")
  186. raise HTTPException(400, detail="Failed to configure TLS for LDAP connection.")
  187. try:
  188. server = Server(
  189. host=LDAP_SERVER_HOST,
  190. port=LDAP_SERVER_PORT,
  191. get_info=NONE,
  192. use_ssl=LDAP_USE_TLS,
  193. tls=tls,
  194. )
  195. connection_app = Connection(
  196. server,
  197. LDAP_APP_DN,
  198. LDAP_APP_PASSWORD,
  199. auto_bind="NONE",
  200. authentication="SIMPLE" if LDAP_APP_DN else "ANONYMOUS",
  201. )
  202. if not connection_app.bind():
  203. raise HTTPException(400, detail="Application account bind failed")
  204. ENABLE_LDAP_GROUP_MANAGEMENT = (
  205. request.app.state.config.ENABLE_LDAP_GROUP_MANAGEMENT
  206. )
  207. ENABLE_LDAP_GROUP_CREATION = request.app.state.config.ENABLE_LDAP_GROUP_CREATION
  208. LDAP_ATTRIBUTE_FOR_GROUPS = request.app.state.config.LDAP_ATTRIBUTE_FOR_GROUPS
  209. search_attributes = [
  210. f"{LDAP_ATTRIBUTE_FOR_USERNAME}",
  211. f"{LDAP_ATTRIBUTE_FOR_MAIL}",
  212. "cn",
  213. ]
  214. if ENABLE_LDAP_GROUP_MANAGEMENT:
  215. search_attributes.append(f"{LDAP_ATTRIBUTE_FOR_GROUPS}")
  216. log.info(
  217. f"LDAP Group Management enabled. Adding {LDAP_ATTRIBUTE_FOR_GROUPS} to search attributes"
  218. )
  219. log.info(f"LDAP search attributes: {search_attributes}")
  220. search_success = connection_app.search(
  221. search_base=LDAP_SEARCH_BASE,
  222. search_filter=f"(&({LDAP_ATTRIBUTE_FOR_USERNAME}={escape_filter_chars(form_data.user.lower())}){LDAP_SEARCH_FILTERS})",
  223. attributes=search_attributes,
  224. )
  225. if not search_success or not connection_app.entries:
  226. raise HTTPException(400, detail="User not found in the LDAP server")
  227. entry = connection_app.entries[0]
  228. username = str(entry[f"{LDAP_ATTRIBUTE_FOR_USERNAME}"]).lower()
  229. email = entry[
  230. f"{LDAP_ATTRIBUTE_FOR_MAIL}"
  231. ].value # retrieve the Attribute value
  232. if not email:
  233. raise HTTPException(400, "User does not have a valid email address.")
  234. elif isinstance(email, str):
  235. email = email.lower()
  236. elif isinstance(email, list):
  237. email = email[0].lower()
  238. else:
  239. email = str(email).lower()
  240. cn = str(entry["cn"])
  241. user_dn = entry.entry_dn
  242. user_groups = []
  243. if ENABLE_LDAP_GROUP_MANAGEMENT and LDAP_ATTRIBUTE_FOR_GROUPS in entry:
  244. group_dns = entry[LDAP_ATTRIBUTE_FOR_GROUPS]
  245. log.info(f"LDAP raw group DNs for user {username}: {group_dns}")
  246. if group_dns:
  247. log.info(f"LDAP group_dns original: {group_dns}")
  248. log.info(f"LDAP group_dns type: {type(group_dns)}")
  249. log.info(f"LDAP group_dns length: {len(group_dns)}")
  250. if hasattr(group_dns, "value"):
  251. group_dns = group_dns.value
  252. log.info(f"Extracted .value property: {group_dns}")
  253. elif hasattr(group_dns, "__iter__") and not isinstance(
  254. group_dns, (str, bytes)
  255. ):
  256. group_dns = list(group_dns)
  257. log.info(f"Converted to list: {group_dns}")
  258. if isinstance(group_dns, list):
  259. group_dns = [str(item) for item in group_dns]
  260. else:
  261. group_dns = [str(group_dns)]
  262. log.info(
  263. f"LDAP group_dns after processing - type: {type(group_dns)}, length: {len(group_dns)}"
  264. )
  265. for group_idx, group_dn in enumerate(group_dns):
  266. group_dn = str(group_dn)
  267. log.info(f"Processing group DN #{group_idx + 1}: {group_dn}")
  268. try:
  269. group_cn = None
  270. for item in group_dn.split(","):
  271. item = item.strip()
  272. if item.upper().startswith("CN="):
  273. group_cn = item[3:]
  274. break
  275. if group_cn:
  276. user_groups.append(group_cn)
  277. else:
  278. log.warning(
  279. f"Could not extract CN from group DN: {group_dn}"
  280. )
  281. except Exception as e:
  282. log.warning(
  283. f"Failed to extract group name from DN {group_dn}: {e}"
  284. )
  285. log.info(
  286. f"LDAP groups for user {username}: {user_groups} (total: {len(user_groups)})"
  287. )
  288. else:
  289. log.info(f"No groups found for user {username}")
  290. elif ENABLE_LDAP_GROUP_MANAGEMENT:
  291. log.warning(
  292. f"LDAP Group Management enabled but {LDAP_ATTRIBUTE_FOR_GROUPS} attribute not found in user entry"
  293. )
  294. if username == form_data.user.lower():
  295. connection_user = Connection(
  296. server,
  297. user_dn,
  298. form_data.password,
  299. auto_bind="NONE",
  300. authentication="SIMPLE",
  301. )
  302. if not connection_user.bind():
  303. raise HTTPException(400, "Authentication failed.")
  304. user = Users.get_user_by_email(email)
  305. if not user:
  306. try:
  307. role = (
  308. "admin"
  309. if not Users.has_users()
  310. else request.app.state.config.DEFAULT_USER_ROLE
  311. )
  312. user = Auths.insert_new_auth(
  313. email=email,
  314. password=str(uuid.uuid4()),
  315. name=cn,
  316. role=role,
  317. )
  318. if not user:
  319. raise HTTPException(
  320. 500, detail=ERROR_MESSAGES.CREATE_USER_ERROR
  321. )
  322. except HTTPException:
  323. raise
  324. except Exception as err:
  325. log.error(f"LDAP user creation error: {str(err)}")
  326. raise HTTPException(
  327. 500, detail="Internal error occurred during LDAP user creation."
  328. )
  329. user = Auths.authenticate_user_by_email(email)
  330. if user:
  331. expires_delta = parse_duration(request.app.state.config.JWT_EXPIRES_IN)
  332. expires_at = None
  333. if expires_delta:
  334. expires_at = int(time.time()) + int(expires_delta.total_seconds())
  335. token = create_token(
  336. data={"id": user.id},
  337. expires_delta=expires_delta,
  338. )
  339. # Set the cookie token
  340. response.set_cookie(
  341. key="token",
  342. value=token,
  343. expires=(
  344. datetime.datetime.fromtimestamp(
  345. expires_at, datetime.timezone.utc
  346. )
  347. if expires_at
  348. else None
  349. ),
  350. httponly=True, # Ensures the cookie is not accessible via JavaScript
  351. samesite=WEBUI_AUTH_COOKIE_SAME_SITE,
  352. secure=WEBUI_AUTH_COOKIE_SECURE,
  353. )
  354. user_permissions = get_permissions(
  355. user.id, request.app.state.config.USER_PERMISSIONS
  356. )
  357. if (
  358. user.role != "admin"
  359. and ENABLE_LDAP_GROUP_MANAGEMENT
  360. and user_groups
  361. ):
  362. if ENABLE_LDAP_GROUP_CREATION:
  363. Groups.create_groups_by_group_names(user.id, user_groups)
  364. try:
  365. Groups.sync_groups_by_group_names(user.id, user_groups)
  366. log.info(
  367. f"Successfully synced groups for user {user.id}: {user_groups}"
  368. )
  369. except Exception as e:
  370. log.error(f"Failed to sync groups for user {user.id}: {e}")
  371. return {
  372. "token": token,
  373. "token_type": "Bearer",
  374. "expires_at": expires_at,
  375. "id": user.id,
  376. "email": user.email,
  377. "name": user.name,
  378. "role": user.role,
  379. "profile_image_url": user.profile_image_url,
  380. "permissions": user_permissions,
  381. }
  382. else:
  383. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  384. else:
  385. raise HTTPException(400, "User record mismatch.")
  386. except Exception as e:
  387. log.error(f"LDAP authentication error: {str(e)}")
  388. raise HTTPException(400, detail="LDAP authentication failed.")
  389. ############################
  390. # SignIn
  391. ############################
  392. @router.post("/signin", response_model=SessionUserResponse)
  393. async def signin(request: Request, response: Response, form_data: SigninForm):
  394. if WEBUI_AUTH_TRUSTED_EMAIL_HEADER:
  395. if WEBUI_AUTH_TRUSTED_EMAIL_HEADER not in request.headers:
  396. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_TRUSTED_HEADER)
  397. email = request.headers[WEBUI_AUTH_TRUSTED_EMAIL_HEADER].lower()
  398. name = email
  399. if WEBUI_AUTH_TRUSTED_NAME_HEADER:
  400. name = request.headers.get(WEBUI_AUTH_TRUSTED_NAME_HEADER, email)
  401. if not Users.get_user_by_email(email.lower()):
  402. await signup(
  403. request,
  404. response,
  405. SignupForm(email=email, password=str(uuid.uuid4()), name=name),
  406. )
  407. user = Auths.authenticate_user_by_email(email)
  408. if WEBUI_AUTH_TRUSTED_GROUPS_HEADER and user and user.role != "admin":
  409. group_names = request.headers.get(
  410. WEBUI_AUTH_TRUSTED_GROUPS_HEADER, ""
  411. ).split(",")
  412. group_names = [name.strip() for name in group_names if name.strip()]
  413. if group_names:
  414. Groups.sync_groups_by_group_names(user.id, group_names)
  415. elif WEBUI_AUTH == False:
  416. admin_email = "admin@localhost"
  417. admin_password = "admin"
  418. if Users.get_user_by_email(admin_email.lower()):
  419. user = Auths.authenticate_user(admin_email.lower(), admin_password)
  420. else:
  421. if Users.has_users():
  422. raise HTTPException(400, detail=ERROR_MESSAGES.EXISTING_USERS)
  423. await signup(
  424. request,
  425. response,
  426. SignupForm(email=admin_email, password=admin_password, name="User"),
  427. )
  428. user = Auths.authenticate_user(admin_email.lower(), admin_password)
  429. else:
  430. user = Auths.authenticate_user(form_data.email.lower(), form_data.password)
  431. if user:
  432. expires_delta = parse_duration(request.app.state.config.JWT_EXPIRES_IN)
  433. expires_at = None
  434. if expires_delta:
  435. expires_at = int(time.time()) + int(expires_delta.total_seconds())
  436. token = create_token(
  437. data={"id": user.id},
  438. expires_delta=expires_delta,
  439. )
  440. datetime_expires_at = (
  441. datetime.datetime.fromtimestamp(expires_at, datetime.timezone.utc)
  442. if expires_at
  443. else None
  444. )
  445. # Set the cookie token
  446. response.set_cookie(
  447. key="token",
  448. value=token,
  449. expires=datetime_expires_at,
  450. httponly=True, # Ensures the cookie is not accessible via JavaScript
  451. samesite=WEBUI_AUTH_COOKIE_SAME_SITE,
  452. secure=WEBUI_AUTH_COOKIE_SECURE,
  453. )
  454. user_permissions = get_permissions(
  455. user.id, request.app.state.config.USER_PERMISSIONS
  456. )
  457. return {
  458. "token": token,
  459. "token_type": "Bearer",
  460. "expires_at": expires_at,
  461. "id": user.id,
  462. "email": user.email,
  463. "name": user.name,
  464. "role": user.role,
  465. "profile_image_url": user.profile_image_url,
  466. "permissions": user_permissions,
  467. }
  468. else:
  469. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  470. ############################
  471. # SignUp
  472. ############################
  473. @router.post("/signup", response_model=SessionUserResponse)
  474. async def signup(request: Request, response: Response, form_data: SignupForm):
  475. has_users = Users.has_users()
  476. if WEBUI_AUTH:
  477. if (
  478. not request.app.state.config.ENABLE_SIGNUP
  479. or not request.app.state.config.ENABLE_LOGIN_FORM
  480. ):
  481. if has_users or not ENABLE_INITIAL_ADMIN_SIGNUP:
  482. raise HTTPException(
  483. status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.ACCESS_PROHIBITED
  484. )
  485. else:
  486. if has_users:
  487. raise HTTPException(
  488. status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.ACCESS_PROHIBITED
  489. )
  490. if not validate_email_format(form_data.email.lower()):
  491. raise HTTPException(
  492. status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.INVALID_EMAIL_FORMAT
  493. )
  494. if Users.get_user_by_email(form_data.email.lower()):
  495. raise HTTPException(400, detail=ERROR_MESSAGES.EMAIL_TAKEN)
  496. try:
  497. role = "admin" if not has_users else request.app.state.config.DEFAULT_USER_ROLE
  498. # The password passed to bcrypt must be 72 bytes or fewer. If it is longer, it will be truncated before hashing.
  499. if len(form_data.password.encode("utf-8")) > 72:
  500. raise HTTPException(
  501. status.HTTP_400_BAD_REQUEST,
  502. detail=ERROR_MESSAGES.PASSWORD_TOO_LONG,
  503. )
  504. hashed = get_password_hash(form_data.password)
  505. user = Auths.insert_new_auth(
  506. form_data.email.lower(),
  507. hashed,
  508. form_data.name,
  509. form_data.profile_image_url,
  510. role,
  511. )
  512. if user:
  513. expires_delta = parse_duration(request.app.state.config.JWT_EXPIRES_IN)
  514. expires_at = None
  515. if expires_delta:
  516. expires_at = int(time.time()) + int(expires_delta.total_seconds())
  517. token = create_token(
  518. data={"id": user.id},
  519. expires_delta=expires_delta,
  520. )
  521. datetime_expires_at = (
  522. datetime.datetime.fromtimestamp(expires_at, datetime.timezone.utc)
  523. if expires_at
  524. else None
  525. )
  526. # Set the cookie token
  527. response.set_cookie(
  528. key="token",
  529. value=token,
  530. expires=datetime_expires_at,
  531. httponly=True, # Ensures the cookie is not accessible via JavaScript
  532. samesite=WEBUI_AUTH_COOKIE_SAME_SITE,
  533. secure=WEBUI_AUTH_COOKIE_SECURE,
  534. )
  535. if request.app.state.config.WEBHOOK_URL:
  536. await post_webhook(
  537. request.app.state.WEBUI_NAME,
  538. request.app.state.config.WEBHOOK_URL,
  539. WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  540. {
  541. "action": "signup",
  542. "message": WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  543. "user": user.model_dump_json(exclude_none=True),
  544. },
  545. )
  546. user_permissions = get_permissions(
  547. user.id, request.app.state.config.USER_PERMISSIONS
  548. )
  549. if not has_users:
  550. # Disable signup after the first user is created
  551. request.app.state.config.ENABLE_SIGNUP = False
  552. return {
  553. "token": token,
  554. "token_type": "Bearer",
  555. "expires_at": expires_at,
  556. "id": user.id,
  557. "email": user.email,
  558. "name": user.name,
  559. "role": user.role,
  560. "profile_image_url": user.profile_image_url,
  561. "permissions": user_permissions,
  562. }
  563. else:
  564. raise HTTPException(500, detail=ERROR_MESSAGES.CREATE_USER_ERROR)
  565. except Exception as err:
  566. log.error(f"Signup error: {str(err)}")
  567. raise HTTPException(500, detail="An internal error occurred during signup.")
  568. @router.get("/signout")
  569. async def signout(request: Request, response: Response):
  570. response.delete_cookie("token")
  571. response.delete_cookie("oui-session")
  572. response.delete_cookie("oauth_id_token")
  573. oauth_session_id = request.cookies.get("oauth_session_id")
  574. if oauth_session_id:
  575. response.delete_cookie("oauth_session_id")
  576. session = OAuthSessions.get_session_by_id(oauth_session_id)
  577. oauth_server_metadata_url = (
  578. request.app.state.oauth_manager.get_server_metadata_url(session.provider)
  579. if session
  580. else None
  581. ) or OPENID_PROVIDER_URL.value
  582. if session and oauth_server_metadata_url:
  583. oauth_id_token = session.token.get("id_token")
  584. try:
  585. async with ClientSession(trust_env=True) as session:
  586. async with session.get(oauth_server_metadata_url) as r:
  587. if r.status == 200:
  588. openid_data = await r.json()
  589. logout_url = openid_data.get("end_session_endpoint")
  590. if logout_url:
  591. return JSONResponse(
  592. status_code=200,
  593. content={
  594. "status": True,
  595. "redirect_url": f"{logout_url}?id_token_hint={oauth_id_token}"
  596. + (
  597. f"&post_logout_redirect_uri={WEBUI_AUTH_SIGNOUT_REDIRECT_URL}"
  598. if WEBUI_AUTH_SIGNOUT_REDIRECT_URL
  599. else ""
  600. ),
  601. },
  602. headers=response.headers,
  603. )
  604. else:
  605. raise Exception("Failed to fetch OpenID configuration")
  606. except Exception as e:
  607. log.error(f"OpenID signout error: {str(e)}")
  608. raise HTTPException(
  609. status_code=500,
  610. detail="Failed to sign out from the OpenID provider.",
  611. headers=response.headers,
  612. )
  613. if WEBUI_AUTH_SIGNOUT_REDIRECT_URL:
  614. return JSONResponse(
  615. status_code=200,
  616. content={
  617. "status": True,
  618. "redirect_url": WEBUI_AUTH_SIGNOUT_REDIRECT_URL,
  619. },
  620. headers=response.headers,
  621. )
  622. return JSONResponse(
  623. status_code=200, content={"status": True}, headers=response.headers
  624. )
  625. ############################
  626. # AddUser
  627. ############################
  628. @router.post("/add", response_model=SigninResponse)
  629. async def add_user(form_data: AddUserForm, user=Depends(get_admin_user)):
  630. if not validate_email_format(form_data.email.lower()):
  631. raise HTTPException(
  632. status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.INVALID_EMAIL_FORMAT
  633. )
  634. if Users.get_user_by_email(form_data.email.lower()):
  635. raise HTTPException(400, detail=ERROR_MESSAGES.EMAIL_TAKEN)
  636. try:
  637. hashed = get_password_hash(form_data.password)
  638. user = Auths.insert_new_auth(
  639. form_data.email.lower(),
  640. hashed,
  641. form_data.name,
  642. form_data.profile_image_url,
  643. form_data.role,
  644. )
  645. if user:
  646. token = create_token(data={"id": user.id})
  647. return {
  648. "token": token,
  649. "token_type": "Bearer",
  650. "id": user.id,
  651. "email": user.email,
  652. "name": user.name,
  653. "role": user.role,
  654. "profile_image_url": user.profile_image_url,
  655. }
  656. else:
  657. raise HTTPException(500, detail=ERROR_MESSAGES.CREATE_USER_ERROR)
  658. except Exception as err:
  659. log.error(f"Add user error: {str(err)}")
  660. raise HTTPException(
  661. 500, detail="An internal error occurred while adding the user."
  662. )
  663. ############################
  664. # GetAdminDetails
  665. ############################
  666. @router.get("/admin/details")
  667. async def get_admin_details(request: Request, user=Depends(get_current_user)):
  668. if request.app.state.config.SHOW_ADMIN_DETAILS:
  669. admin_email = request.app.state.config.ADMIN_EMAIL
  670. admin_name = None
  671. log.info(f"Admin details - Email: {admin_email}, Name: {admin_name}")
  672. if admin_email:
  673. admin = Users.get_user_by_email(admin_email)
  674. if admin:
  675. admin_name = admin.name
  676. else:
  677. admin = Users.get_first_user()
  678. if admin:
  679. admin_email = admin.email
  680. admin_name = admin.name
  681. return {
  682. "name": admin_name,
  683. "email": admin_email,
  684. }
  685. else:
  686. raise HTTPException(400, detail=ERROR_MESSAGES.ACTION_PROHIBITED)
  687. ############################
  688. # ToggleSignUp
  689. ############################
  690. @router.get("/admin/config")
  691. async def get_admin_config(request: Request, user=Depends(get_admin_user)):
  692. return {
  693. "SHOW_ADMIN_DETAILS": request.app.state.config.SHOW_ADMIN_DETAILS,
  694. "WEBUI_URL": request.app.state.config.WEBUI_URL,
  695. "ENABLE_SIGNUP": request.app.state.config.ENABLE_SIGNUP,
  696. "ENABLE_API_KEY": request.app.state.config.ENABLE_API_KEY,
  697. "ENABLE_API_KEY_ENDPOINT_RESTRICTIONS": request.app.state.config.ENABLE_API_KEY_ENDPOINT_RESTRICTIONS,
  698. "API_KEY_ALLOWED_ENDPOINTS": request.app.state.config.API_KEY_ALLOWED_ENDPOINTS,
  699. "DEFAULT_USER_ROLE": request.app.state.config.DEFAULT_USER_ROLE,
  700. "JWT_EXPIRES_IN": request.app.state.config.JWT_EXPIRES_IN,
  701. "ENABLE_COMMUNITY_SHARING": request.app.state.config.ENABLE_COMMUNITY_SHARING,
  702. "ENABLE_MESSAGE_RATING": request.app.state.config.ENABLE_MESSAGE_RATING,
  703. "ENABLE_CHANNELS": request.app.state.config.ENABLE_CHANNELS,
  704. "ENABLE_NOTES": request.app.state.config.ENABLE_NOTES,
  705. "ENABLE_USER_WEBHOOKS": request.app.state.config.ENABLE_USER_WEBHOOKS,
  706. "PENDING_USER_OVERLAY_TITLE": request.app.state.config.PENDING_USER_OVERLAY_TITLE,
  707. "PENDING_USER_OVERLAY_CONTENT": request.app.state.config.PENDING_USER_OVERLAY_CONTENT,
  708. "RESPONSE_WATERMARK": request.app.state.config.RESPONSE_WATERMARK,
  709. }
  710. class AdminConfig(BaseModel):
  711. SHOW_ADMIN_DETAILS: bool
  712. WEBUI_URL: str
  713. ENABLE_SIGNUP: bool
  714. ENABLE_API_KEY: bool
  715. ENABLE_API_KEY_ENDPOINT_RESTRICTIONS: bool
  716. API_KEY_ALLOWED_ENDPOINTS: str
  717. DEFAULT_USER_ROLE: str
  718. JWT_EXPIRES_IN: str
  719. ENABLE_COMMUNITY_SHARING: bool
  720. ENABLE_MESSAGE_RATING: bool
  721. ENABLE_CHANNELS: bool
  722. ENABLE_NOTES: bool
  723. ENABLE_USER_WEBHOOKS: bool
  724. PENDING_USER_OVERLAY_TITLE: Optional[str] = None
  725. PENDING_USER_OVERLAY_CONTENT: Optional[str] = None
  726. RESPONSE_WATERMARK: Optional[str] = None
  727. @router.post("/admin/config")
  728. async def update_admin_config(
  729. request: Request, form_data: AdminConfig, user=Depends(get_admin_user)
  730. ):
  731. request.app.state.config.SHOW_ADMIN_DETAILS = form_data.SHOW_ADMIN_DETAILS
  732. request.app.state.config.WEBUI_URL = form_data.WEBUI_URL
  733. request.app.state.config.ENABLE_SIGNUP = form_data.ENABLE_SIGNUP
  734. request.app.state.config.ENABLE_API_KEY = form_data.ENABLE_API_KEY
  735. request.app.state.config.ENABLE_API_KEY_ENDPOINT_RESTRICTIONS = (
  736. form_data.ENABLE_API_KEY_ENDPOINT_RESTRICTIONS
  737. )
  738. request.app.state.config.API_KEY_ALLOWED_ENDPOINTS = (
  739. form_data.API_KEY_ALLOWED_ENDPOINTS
  740. )
  741. request.app.state.config.ENABLE_CHANNELS = form_data.ENABLE_CHANNELS
  742. request.app.state.config.ENABLE_NOTES = form_data.ENABLE_NOTES
  743. if form_data.DEFAULT_USER_ROLE in ["pending", "user", "admin"]:
  744. request.app.state.config.DEFAULT_USER_ROLE = form_data.DEFAULT_USER_ROLE
  745. pattern = r"^(-1|0|(-?\d+(\.\d+)?)(ms|s|m|h|d|w))$"
  746. # Check if the input string matches the pattern
  747. if re.match(pattern, form_data.JWT_EXPIRES_IN):
  748. request.app.state.config.JWT_EXPIRES_IN = form_data.JWT_EXPIRES_IN
  749. request.app.state.config.ENABLE_COMMUNITY_SHARING = (
  750. form_data.ENABLE_COMMUNITY_SHARING
  751. )
  752. request.app.state.config.ENABLE_MESSAGE_RATING = form_data.ENABLE_MESSAGE_RATING
  753. request.app.state.config.ENABLE_USER_WEBHOOKS = form_data.ENABLE_USER_WEBHOOKS
  754. request.app.state.config.PENDING_USER_OVERLAY_TITLE = (
  755. form_data.PENDING_USER_OVERLAY_TITLE
  756. )
  757. request.app.state.config.PENDING_USER_OVERLAY_CONTENT = (
  758. form_data.PENDING_USER_OVERLAY_CONTENT
  759. )
  760. request.app.state.config.RESPONSE_WATERMARK = form_data.RESPONSE_WATERMARK
  761. return {
  762. "SHOW_ADMIN_DETAILS": request.app.state.config.SHOW_ADMIN_DETAILS,
  763. "WEBUI_URL": request.app.state.config.WEBUI_URL,
  764. "ENABLE_SIGNUP": request.app.state.config.ENABLE_SIGNUP,
  765. "ENABLE_API_KEY": request.app.state.config.ENABLE_API_KEY,
  766. "ENABLE_API_KEY_ENDPOINT_RESTRICTIONS": request.app.state.config.ENABLE_API_KEY_ENDPOINT_RESTRICTIONS,
  767. "API_KEY_ALLOWED_ENDPOINTS": request.app.state.config.API_KEY_ALLOWED_ENDPOINTS,
  768. "DEFAULT_USER_ROLE": request.app.state.config.DEFAULT_USER_ROLE,
  769. "JWT_EXPIRES_IN": request.app.state.config.JWT_EXPIRES_IN,
  770. "ENABLE_COMMUNITY_SHARING": request.app.state.config.ENABLE_COMMUNITY_SHARING,
  771. "ENABLE_MESSAGE_RATING": request.app.state.config.ENABLE_MESSAGE_RATING,
  772. "ENABLE_CHANNELS": request.app.state.config.ENABLE_CHANNELS,
  773. "ENABLE_NOTES": request.app.state.config.ENABLE_NOTES,
  774. "ENABLE_USER_WEBHOOKS": request.app.state.config.ENABLE_USER_WEBHOOKS,
  775. "PENDING_USER_OVERLAY_TITLE": request.app.state.config.PENDING_USER_OVERLAY_TITLE,
  776. "PENDING_USER_OVERLAY_CONTENT": request.app.state.config.PENDING_USER_OVERLAY_CONTENT,
  777. "RESPONSE_WATERMARK": request.app.state.config.RESPONSE_WATERMARK,
  778. }
  779. class LdapServerConfig(BaseModel):
  780. label: str
  781. host: str
  782. port: Optional[int] = None
  783. attribute_for_mail: str = "mail"
  784. attribute_for_username: str = "uid"
  785. app_dn: str
  786. app_dn_password: str
  787. search_base: str
  788. search_filters: str = ""
  789. use_tls: bool = True
  790. certificate_path: Optional[str] = None
  791. validate_cert: bool = True
  792. ciphers: Optional[str] = "ALL"
  793. @router.get("/admin/config/ldap/server", response_model=LdapServerConfig)
  794. async def get_ldap_server(request: Request, user=Depends(get_admin_user)):
  795. return {
  796. "label": request.app.state.config.LDAP_SERVER_LABEL,
  797. "host": request.app.state.config.LDAP_SERVER_HOST,
  798. "port": request.app.state.config.LDAP_SERVER_PORT,
  799. "attribute_for_mail": request.app.state.config.LDAP_ATTRIBUTE_FOR_MAIL,
  800. "attribute_for_username": request.app.state.config.LDAP_ATTRIBUTE_FOR_USERNAME,
  801. "app_dn": request.app.state.config.LDAP_APP_DN,
  802. "app_dn_password": request.app.state.config.LDAP_APP_PASSWORD,
  803. "search_base": request.app.state.config.LDAP_SEARCH_BASE,
  804. "search_filters": request.app.state.config.LDAP_SEARCH_FILTERS,
  805. "use_tls": request.app.state.config.LDAP_USE_TLS,
  806. "certificate_path": request.app.state.config.LDAP_CA_CERT_FILE,
  807. "validate_cert": request.app.state.config.LDAP_VALIDATE_CERT,
  808. "ciphers": request.app.state.config.LDAP_CIPHERS,
  809. }
  810. @router.post("/admin/config/ldap/server")
  811. async def update_ldap_server(
  812. request: Request, form_data: LdapServerConfig, user=Depends(get_admin_user)
  813. ):
  814. required_fields = [
  815. "label",
  816. "host",
  817. "attribute_for_mail",
  818. "attribute_for_username",
  819. "app_dn",
  820. "app_dn_password",
  821. "search_base",
  822. ]
  823. for key in required_fields:
  824. value = getattr(form_data, key)
  825. if not value:
  826. raise HTTPException(400, detail=f"Required field {key} is empty")
  827. request.app.state.config.LDAP_SERVER_LABEL = form_data.label
  828. request.app.state.config.LDAP_SERVER_HOST = form_data.host
  829. request.app.state.config.LDAP_SERVER_PORT = form_data.port
  830. request.app.state.config.LDAP_ATTRIBUTE_FOR_MAIL = form_data.attribute_for_mail
  831. request.app.state.config.LDAP_ATTRIBUTE_FOR_USERNAME = (
  832. form_data.attribute_for_username
  833. )
  834. request.app.state.config.LDAP_APP_DN = form_data.app_dn
  835. request.app.state.config.LDAP_APP_PASSWORD = form_data.app_dn_password
  836. request.app.state.config.LDAP_SEARCH_BASE = form_data.search_base
  837. request.app.state.config.LDAP_SEARCH_FILTERS = form_data.search_filters
  838. request.app.state.config.LDAP_USE_TLS = form_data.use_tls
  839. request.app.state.config.LDAP_CA_CERT_FILE = form_data.certificate_path
  840. request.app.state.config.LDAP_VALIDATE_CERT = form_data.validate_cert
  841. request.app.state.config.LDAP_CIPHERS = form_data.ciphers
  842. return {
  843. "label": request.app.state.config.LDAP_SERVER_LABEL,
  844. "host": request.app.state.config.LDAP_SERVER_HOST,
  845. "port": request.app.state.config.LDAP_SERVER_PORT,
  846. "attribute_for_mail": request.app.state.config.LDAP_ATTRIBUTE_FOR_MAIL,
  847. "attribute_for_username": request.app.state.config.LDAP_ATTRIBUTE_FOR_USERNAME,
  848. "app_dn": request.app.state.config.LDAP_APP_DN,
  849. "app_dn_password": request.app.state.config.LDAP_APP_PASSWORD,
  850. "search_base": request.app.state.config.LDAP_SEARCH_BASE,
  851. "search_filters": request.app.state.config.LDAP_SEARCH_FILTERS,
  852. "use_tls": request.app.state.config.LDAP_USE_TLS,
  853. "certificate_path": request.app.state.config.LDAP_CA_CERT_FILE,
  854. "validate_cert": request.app.state.config.LDAP_VALIDATE_CERT,
  855. "ciphers": request.app.state.config.LDAP_CIPHERS,
  856. }
  857. @router.get("/admin/config/ldap")
  858. async def get_ldap_config(request: Request, user=Depends(get_admin_user)):
  859. return {"ENABLE_LDAP": request.app.state.config.ENABLE_LDAP}
  860. class LdapConfigForm(BaseModel):
  861. enable_ldap: Optional[bool] = None
  862. @router.post("/admin/config/ldap")
  863. async def update_ldap_config(
  864. request: Request, form_data: LdapConfigForm, user=Depends(get_admin_user)
  865. ):
  866. request.app.state.config.ENABLE_LDAP = form_data.enable_ldap
  867. return {"ENABLE_LDAP": request.app.state.config.ENABLE_LDAP}
  868. ############################
  869. # API Key
  870. ############################
  871. # create api key
  872. @router.post("/api_key", response_model=ApiKey)
  873. async def generate_api_key(request: Request, user=Depends(get_current_user)):
  874. if not request.app.state.config.ENABLE_API_KEY:
  875. raise HTTPException(
  876. status.HTTP_403_FORBIDDEN,
  877. detail=ERROR_MESSAGES.API_KEY_CREATION_NOT_ALLOWED,
  878. )
  879. api_key = create_api_key()
  880. success = Users.update_user_api_key_by_id(user.id, api_key)
  881. if success:
  882. return {
  883. "api_key": api_key,
  884. }
  885. else:
  886. raise HTTPException(500, detail=ERROR_MESSAGES.CREATE_API_KEY_ERROR)
  887. # delete api key
  888. @router.delete("/api_key", response_model=bool)
  889. async def delete_api_key(user=Depends(get_current_user)):
  890. success = Users.update_user_api_key_by_id(user.id, None)
  891. return success
  892. # get api key
  893. @router.get("/api_key", response_model=ApiKey)
  894. async def get_api_key(user=Depends(get_current_user)):
  895. api_key = Users.get_user_api_key_by_id(user.id)
  896. if api_key:
  897. return {
  898. "api_key": api_key,
  899. }
  900. else:
  901. raise HTTPException(404, detail=ERROR_MESSAGES.API_KEY_NOT_FOUND)