auths.py 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081
  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. password_bytes = form_data.password.encode("utf-8")
  431. if len(password_bytes) > 72:
  432. # TODO: Implement other hashing algorithms that support longer passwords
  433. log.info("Password too long, truncating to 72 bytes for bcrypt")
  434. password_bytes = password_bytes[:72]
  435. # decode safely — ignore incomplete UTF-8 sequences
  436. form_data.password = password_bytes.decode("utf-8", errors="ignore")
  437. user = Auths.authenticate_user(form_data.email.lower(), form_data.password)
  438. if user:
  439. expires_delta = parse_duration(request.app.state.config.JWT_EXPIRES_IN)
  440. expires_at = None
  441. if expires_delta:
  442. expires_at = int(time.time()) + int(expires_delta.total_seconds())
  443. token = create_token(
  444. data={"id": user.id},
  445. expires_delta=expires_delta,
  446. )
  447. datetime_expires_at = (
  448. datetime.datetime.fromtimestamp(expires_at, datetime.timezone.utc)
  449. if expires_at
  450. else None
  451. )
  452. # Set the cookie token
  453. response.set_cookie(
  454. key="token",
  455. value=token,
  456. expires=datetime_expires_at,
  457. httponly=True, # Ensures the cookie is not accessible via JavaScript
  458. samesite=WEBUI_AUTH_COOKIE_SAME_SITE,
  459. secure=WEBUI_AUTH_COOKIE_SECURE,
  460. )
  461. user_permissions = get_permissions(
  462. user.id, request.app.state.config.USER_PERMISSIONS
  463. )
  464. return {
  465. "token": token,
  466. "token_type": "Bearer",
  467. "expires_at": expires_at,
  468. "id": user.id,
  469. "email": user.email,
  470. "name": user.name,
  471. "role": user.role,
  472. "profile_image_url": user.profile_image_url,
  473. "permissions": user_permissions,
  474. }
  475. else:
  476. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  477. ############################
  478. # SignUp
  479. ############################
  480. @router.post("/signup", response_model=SessionUserResponse)
  481. async def signup(request: Request, response: Response, form_data: SignupForm):
  482. has_users = Users.has_users()
  483. if WEBUI_AUTH:
  484. if (
  485. not request.app.state.config.ENABLE_SIGNUP
  486. or not request.app.state.config.ENABLE_LOGIN_FORM
  487. ):
  488. if has_users or not ENABLE_INITIAL_ADMIN_SIGNUP:
  489. raise HTTPException(
  490. status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.ACCESS_PROHIBITED
  491. )
  492. else:
  493. if has_users:
  494. raise HTTPException(
  495. status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.ACCESS_PROHIBITED
  496. )
  497. if not validate_email_format(form_data.email.lower()):
  498. raise HTTPException(
  499. status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.INVALID_EMAIL_FORMAT
  500. )
  501. if Users.get_user_by_email(form_data.email.lower()):
  502. raise HTTPException(400, detail=ERROR_MESSAGES.EMAIL_TAKEN)
  503. try:
  504. role = "admin" if not has_users else request.app.state.config.DEFAULT_USER_ROLE
  505. # The password passed to bcrypt must be 72 bytes or fewer. If it is longer, it will be truncated before hashing.
  506. if len(form_data.password.encode("utf-8")) > 72:
  507. raise HTTPException(
  508. status.HTTP_400_BAD_REQUEST,
  509. detail=ERROR_MESSAGES.PASSWORD_TOO_LONG,
  510. )
  511. hashed = get_password_hash(form_data.password)
  512. user = Auths.insert_new_auth(
  513. form_data.email.lower(),
  514. hashed,
  515. form_data.name,
  516. form_data.profile_image_url,
  517. role,
  518. )
  519. if user:
  520. expires_delta = parse_duration(request.app.state.config.JWT_EXPIRES_IN)
  521. expires_at = None
  522. if expires_delta:
  523. expires_at = int(time.time()) + int(expires_delta.total_seconds())
  524. token = create_token(
  525. data={"id": user.id},
  526. expires_delta=expires_delta,
  527. )
  528. datetime_expires_at = (
  529. datetime.datetime.fromtimestamp(expires_at, datetime.timezone.utc)
  530. if expires_at
  531. else None
  532. )
  533. # Set the cookie token
  534. response.set_cookie(
  535. key="token",
  536. value=token,
  537. expires=datetime_expires_at,
  538. httponly=True, # Ensures the cookie is not accessible via JavaScript
  539. samesite=WEBUI_AUTH_COOKIE_SAME_SITE,
  540. secure=WEBUI_AUTH_COOKIE_SECURE,
  541. )
  542. if request.app.state.config.WEBHOOK_URL:
  543. await post_webhook(
  544. request.app.state.WEBUI_NAME,
  545. request.app.state.config.WEBHOOK_URL,
  546. WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  547. {
  548. "action": "signup",
  549. "message": WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  550. "user": user.model_dump_json(exclude_none=True),
  551. },
  552. )
  553. user_permissions = get_permissions(
  554. user.id, request.app.state.config.USER_PERMISSIONS
  555. )
  556. if not has_users:
  557. # Disable signup after the first user is created
  558. request.app.state.config.ENABLE_SIGNUP = False
  559. return {
  560. "token": token,
  561. "token_type": "Bearer",
  562. "expires_at": expires_at,
  563. "id": user.id,
  564. "email": user.email,
  565. "name": user.name,
  566. "role": user.role,
  567. "profile_image_url": user.profile_image_url,
  568. "permissions": user_permissions,
  569. }
  570. else:
  571. raise HTTPException(500, detail=ERROR_MESSAGES.CREATE_USER_ERROR)
  572. except Exception as err:
  573. log.error(f"Signup error: {str(err)}")
  574. raise HTTPException(500, detail="An internal error occurred during signup.")
  575. @router.get("/signout")
  576. async def signout(request: Request, response: Response):
  577. response.delete_cookie("token")
  578. response.delete_cookie("oui-session")
  579. response.delete_cookie("oauth_id_token")
  580. oauth_session_id = request.cookies.get("oauth_session_id")
  581. if oauth_session_id:
  582. response.delete_cookie("oauth_session_id")
  583. session = OAuthSessions.get_session_by_id(oauth_session_id)
  584. oauth_server_metadata_url = (
  585. request.app.state.oauth_manager.get_server_metadata_url(session.provider)
  586. if session
  587. else None
  588. ) or OPENID_PROVIDER_URL.value
  589. if session and oauth_server_metadata_url:
  590. oauth_id_token = session.token.get("id_token")
  591. try:
  592. async with ClientSession(trust_env=True) as session:
  593. async with session.get(oauth_server_metadata_url) as r:
  594. if r.status == 200:
  595. openid_data = await r.json()
  596. logout_url = openid_data.get("end_session_endpoint")
  597. if logout_url:
  598. return JSONResponse(
  599. status_code=200,
  600. content={
  601. "status": True,
  602. "redirect_url": f"{logout_url}?id_token_hint={oauth_id_token}"
  603. + (
  604. f"&post_logout_redirect_uri={WEBUI_AUTH_SIGNOUT_REDIRECT_URL}"
  605. if WEBUI_AUTH_SIGNOUT_REDIRECT_URL
  606. else ""
  607. ),
  608. },
  609. headers=response.headers,
  610. )
  611. else:
  612. raise Exception("Failed to fetch OpenID configuration")
  613. except Exception as e:
  614. log.error(f"OpenID signout error: {str(e)}")
  615. raise HTTPException(
  616. status_code=500,
  617. detail="Failed to sign out from the OpenID provider.",
  618. headers=response.headers,
  619. )
  620. if WEBUI_AUTH_SIGNOUT_REDIRECT_URL:
  621. return JSONResponse(
  622. status_code=200,
  623. content={
  624. "status": True,
  625. "redirect_url": WEBUI_AUTH_SIGNOUT_REDIRECT_URL,
  626. },
  627. headers=response.headers,
  628. )
  629. return JSONResponse(
  630. status_code=200, content={"status": True}, headers=response.headers
  631. )
  632. ############################
  633. # AddUser
  634. ############################
  635. @router.post("/add", response_model=SigninResponse)
  636. async def add_user(form_data: AddUserForm, user=Depends(get_admin_user)):
  637. if not validate_email_format(form_data.email.lower()):
  638. raise HTTPException(
  639. status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.INVALID_EMAIL_FORMAT
  640. )
  641. if Users.get_user_by_email(form_data.email.lower()):
  642. raise HTTPException(400, detail=ERROR_MESSAGES.EMAIL_TAKEN)
  643. try:
  644. hashed = get_password_hash(form_data.password)
  645. user = Auths.insert_new_auth(
  646. form_data.email.lower(),
  647. hashed,
  648. form_data.name,
  649. form_data.profile_image_url,
  650. form_data.role,
  651. )
  652. if user:
  653. token = create_token(data={"id": user.id})
  654. return {
  655. "token": token,
  656. "token_type": "Bearer",
  657. "id": user.id,
  658. "email": user.email,
  659. "name": user.name,
  660. "role": user.role,
  661. "profile_image_url": user.profile_image_url,
  662. }
  663. else:
  664. raise HTTPException(500, detail=ERROR_MESSAGES.CREATE_USER_ERROR)
  665. except Exception as err:
  666. log.error(f"Add user error: {str(err)}")
  667. raise HTTPException(
  668. 500, detail="An internal error occurred while adding the user."
  669. )
  670. ############################
  671. # GetAdminDetails
  672. ############################
  673. @router.get("/admin/details")
  674. async def get_admin_details(request: Request, user=Depends(get_current_user)):
  675. if request.app.state.config.SHOW_ADMIN_DETAILS:
  676. admin_email = request.app.state.config.ADMIN_EMAIL
  677. admin_name = None
  678. log.info(f"Admin details - Email: {admin_email}, Name: {admin_name}")
  679. if admin_email:
  680. admin = Users.get_user_by_email(admin_email)
  681. if admin:
  682. admin_name = admin.name
  683. else:
  684. admin = Users.get_first_user()
  685. if admin:
  686. admin_email = admin.email
  687. admin_name = admin.name
  688. return {
  689. "name": admin_name,
  690. "email": admin_email,
  691. }
  692. else:
  693. raise HTTPException(400, detail=ERROR_MESSAGES.ACTION_PROHIBITED)
  694. ############################
  695. # ToggleSignUp
  696. ############################
  697. @router.get("/admin/config")
  698. async def get_admin_config(request: Request, user=Depends(get_admin_user)):
  699. return {
  700. "SHOW_ADMIN_DETAILS": request.app.state.config.SHOW_ADMIN_DETAILS,
  701. "WEBUI_URL": request.app.state.config.WEBUI_URL,
  702. "ENABLE_SIGNUP": request.app.state.config.ENABLE_SIGNUP,
  703. "ENABLE_API_KEY": request.app.state.config.ENABLE_API_KEY,
  704. "ENABLE_API_KEY_ENDPOINT_RESTRICTIONS": request.app.state.config.ENABLE_API_KEY_ENDPOINT_RESTRICTIONS,
  705. "API_KEY_ALLOWED_ENDPOINTS": request.app.state.config.API_KEY_ALLOWED_ENDPOINTS,
  706. "DEFAULT_USER_ROLE": request.app.state.config.DEFAULT_USER_ROLE,
  707. "JWT_EXPIRES_IN": request.app.state.config.JWT_EXPIRES_IN,
  708. "ENABLE_COMMUNITY_SHARING": request.app.state.config.ENABLE_COMMUNITY_SHARING,
  709. "ENABLE_MESSAGE_RATING": request.app.state.config.ENABLE_MESSAGE_RATING,
  710. "ENABLE_CHANNELS": request.app.state.config.ENABLE_CHANNELS,
  711. "ENABLE_NOTES": request.app.state.config.ENABLE_NOTES,
  712. "ENABLE_USER_WEBHOOKS": request.app.state.config.ENABLE_USER_WEBHOOKS,
  713. "PENDING_USER_OVERLAY_TITLE": request.app.state.config.PENDING_USER_OVERLAY_TITLE,
  714. "PENDING_USER_OVERLAY_CONTENT": request.app.state.config.PENDING_USER_OVERLAY_CONTENT,
  715. "RESPONSE_WATERMARK": request.app.state.config.RESPONSE_WATERMARK,
  716. }
  717. class AdminConfig(BaseModel):
  718. SHOW_ADMIN_DETAILS: bool
  719. WEBUI_URL: str
  720. ENABLE_SIGNUP: bool
  721. ENABLE_API_KEY: bool
  722. ENABLE_API_KEY_ENDPOINT_RESTRICTIONS: bool
  723. API_KEY_ALLOWED_ENDPOINTS: str
  724. DEFAULT_USER_ROLE: str
  725. JWT_EXPIRES_IN: str
  726. ENABLE_COMMUNITY_SHARING: bool
  727. ENABLE_MESSAGE_RATING: bool
  728. ENABLE_CHANNELS: bool
  729. ENABLE_NOTES: bool
  730. ENABLE_USER_WEBHOOKS: bool
  731. PENDING_USER_OVERLAY_TITLE: Optional[str] = None
  732. PENDING_USER_OVERLAY_CONTENT: Optional[str] = None
  733. RESPONSE_WATERMARK: Optional[str] = None
  734. @router.post("/admin/config")
  735. async def update_admin_config(
  736. request: Request, form_data: AdminConfig, user=Depends(get_admin_user)
  737. ):
  738. request.app.state.config.SHOW_ADMIN_DETAILS = form_data.SHOW_ADMIN_DETAILS
  739. request.app.state.config.WEBUI_URL = form_data.WEBUI_URL
  740. request.app.state.config.ENABLE_SIGNUP = form_data.ENABLE_SIGNUP
  741. request.app.state.config.ENABLE_API_KEY = form_data.ENABLE_API_KEY
  742. request.app.state.config.ENABLE_API_KEY_ENDPOINT_RESTRICTIONS = (
  743. form_data.ENABLE_API_KEY_ENDPOINT_RESTRICTIONS
  744. )
  745. request.app.state.config.API_KEY_ALLOWED_ENDPOINTS = (
  746. form_data.API_KEY_ALLOWED_ENDPOINTS
  747. )
  748. request.app.state.config.ENABLE_CHANNELS = form_data.ENABLE_CHANNELS
  749. request.app.state.config.ENABLE_NOTES = form_data.ENABLE_NOTES
  750. if form_data.DEFAULT_USER_ROLE in ["pending", "user", "admin"]:
  751. request.app.state.config.DEFAULT_USER_ROLE = form_data.DEFAULT_USER_ROLE
  752. pattern = r"^(-1|0|(-?\d+(\.\d+)?)(ms|s|m|h|d|w))$"
  753. # Check if the input string matches the pattern
  754. if re.match(pattern, form_data.JWT_EXPIRES_IN):
  755. request.app.state.config.JWT_EXPIRES_IN = form_data.JWT_EXPIRES_IN
  756. request.app.state.config.ENABLE_COMMUNITY_SHARING = (
  757. form_data.ENABLE_COMMUNITY_SHARING
  758. )
  759. request.app.state.config.ENABLE_MESSAGE_RATING = form_data.ENABLE_MESSAGE_RATING
  760. request.app.state.config.ENABLE_USER_WEBHOOKS = form_data.ENABLE_USER_WEBHOOKS
  761. request.app.state.config.PENDING_USER_OVERLAY_TITLE = (
  762. form_data.PENDING_USER_OVERLAY_TITLE
  763. )
  764. request.app.state.config.PENDING_USER_OVERLAY_CONTENT = (
  765. form_data.PENDING_USER_OVERLAY_CONTENT
  766. )
  767. request.app.state.config.RESPONSE_WATERMARK = form_data.RESPONSE_WATERMARK
  768. return {
  769. "SHOW_ADMIN_DETAILS": request.app.state.config.SHOW_ADMIN_DETAILS,
  770. "WEBUI_URL": request.app.state.config.WEBUI_URL,
  771. "ENABLE_SIGNUP": request.app.state.config.ENABLE_SIGNUP,
  772. "ENABLE_API_KEY": request.app.state.config.ENABLE_API_KEY,
  773. "ENABLE_API_KEY_ENDPOINT_RESTRICTIONS": request.app.state.config.ENABLE_API_KEY_ENDPOINT_RESTRICTIONS,
  774. "API_KEY_ALLOWED_ENDPOINTS": request.app.state.config.API_KEY_ALLOWED_ENDPOINTS,
  775. "DEFAULT_USER_ROLE": request.app.state.config.DEFAULT_USER_ROLE,
  776. "JWT_EXPIRES_IN": request.app.state.config.JWT_EXPIRES_IN,
  777. "ENABLE_COMMUNITY_SHARING": request.app.state.config.ENABLE_COMMUNITY_SHARING,
  778. "ENABLE_MESSAGE_RATING": request.app.state.config.ENABLE_MESSAGE_RATING,
  779. "ENABLE_CHANNELS": request.app.state.config.ENABLE_CHANNELS,
  780. "ENABLE_NOTES": request.app.state.config.ENABLE_NOTES,
  781. "ENABLE_USER_WEBHOOKS": request.app.state.config.ENABLE_USER_WEBHOOKS,
  782. "PENDING_USER_OVERLAY_TITLE": request.app.state.config.PENDING_USER_OVERLAY_TITLE,
  783. "PENDING_USER_OVERLAY_CONTENT": request.app.state.config.PENDING_USER_OVERLAY_CONTENT,
  784. "RESPONSE_WATERMARK": request.app.state.config.RESPONSE_WATERMARK,
  785. }
  786. class LdapServerConfig(BaseModel):
  787. label: str
  788. host: str
  789. port: Optional[int] = None
  790. attribute_for_mail: str = "mail"
  791. attribute_for_username: str = "uid"
  792. app_dn: str
  793. app_dn_password: str
  794. search_base: str
  795. search_filters: str = ""
  796. use_tls: bool = True
  797. certificate_path: Optional[str] = None
  798. validate_cert: bool = True
  799. ciphers: Optional[str] = "ALL"
  800. @router.get("/admin/config/ldap/server", response_model=LdapServerConfig)
  801. async def get_ldap_server(request: Request, user=Depends(get_admin_user)):
  802. return {
  803. "label": request.app.state.config.LDAP_SERVER_LABEL,
  804. "host": request.app.state.config.LDAP_SERVER_HOST,
  805. "port": request.app.state.config.LDAP_SERVER_PORT,
  806. "attribute_for_mail": request.app.state.config.LDAP_ATTRIBUTE_FOR_MAIL,
  807. "attribute_for_username": request.app.state.config.LDAP_ATTRIBUTE_FOR_USERNAME,
  808. "app_dn": request.app.state.config.LDAP_APP_DN,
  809. "app_dn_password": request.app.state.config.LDAP_APP_PASSWORD,
  810. "search_base": request.app.state.config.LDAP_SEARCH_BASE,
  811. "search_filters": request.app.state.config.LDAP_SEARCH_FILTERS,
  812. "use_tls": request.app.state.config.LDAP_USE_TLS,
  813. "certificate_path": request.app.state.config.LDAP_CA_CERT_FILE,
  814. "validate_cert": request.app.state.config.LDAP_VALIDATE_CERT,
  815. "ciphers": request.app.state.config.LDAP_CIPHERS,
  816. }
  817. @router.post("/admin/config/ldap/server")
  818. async def update_ldap_server(
  819. request: Request, form_data: LdapServerConfig, user=Depends(get_admin_user)
  820. ):
  821. required_fields = [
  822. "label",
  823. "host",
  824. "attribute_for_mail",
  825. "attribute_for_username",
  826. "app_dn",
  827. "app_dn_password",
  828. "search_base",
  829. ]
  830. for key in required_fields:
  831. value = getattr(form_data, key)
  832. if not value:
  833. raise HTTPException(400, detail=f"Required field {key} is empty")
  834. request.app.state.config.LDAP_SERVER_LABEL = form_data.label
  835. request.app.state.config.LDAP_SERVER_HOST = form_data.host
  836. request.app.state.config.LDAP_SERVER_PORT = form_data.port
  837. request.app.state.config.LDAP_ATTRIBUTE_FOR_MAIL = form_data.attribute_for_mail
  838. request.app.state.config.LDAP_ATTRIBUTE_FOR_USERNAME = (
  839. form_data.attribute_for_username
  840. )
  841. request.app.state.config.LDAP_APP_DN = form_data.app_dn
  842. request.app.state.config.LDAP_APP_PASSWORD = form_data.app_dn_password
  843. request.app.state.config.LDAP_SEARCH_BASE = form_data.search_base
  844. request.app.state.config.LDAP_SEARCH_FILTERS = form_data.search_filters
  845. request.app.state.config.LDAP_USE_TLS = form_data.use_tls
  846. request.app.state.config.LDAP_CA_CERT_FILE = form_data.certificate_path
  847. request.app.state.config.LDAP_VALIDATE_CERT = form_data.validate_cert
  848. request.app.state.config.LDAP_CIPHERS = form_data.ciphers
  849. return {
  850. "label": request.app.state.config.LDAP_SERVER_LABEL,
  851. "host": request.app.state.config.LDAP_SERVER_HOST,
  852. "port": request.app.state.config.LDAP_SERVER_PORT,
  853. "attribute_for_mail": request.app.state.config.LDAP_ATTRIBUTE_FOR_MAIL,
  854. "attribute_for_username": request.app.state.config.LDAP_ATTRIBUTE_FOR_USERNAME,
  855. "app_dn": request.app.state.config.LDAP_APP_DN,
  856. "app_dn_password": request.app.state.config.LDAP_APP_PASSWORD,
  857. "search_base": request.app.state.config.LDAP_SEARCH_BASE,
  858. "search_filters": request.app.state.config.LDAP_SEARCH_FILTERS,
  859. "use_tls": request.app.state.config.LDAP_USE_TLS,
  860. "certificate_path": request.app.state.config.LDAP_CA_CERT_FILE,
  861. "validate_cert": request.app.state.config.LDAP_VALIDATE_CERT,
  862. "ciphers": request.app.state.config.LDAP_CIPHERS,
  863. }
  864. @router.get("/admin/config/ldap")
  865. async def get_ldap_config(request: Request, user=Depends(get_admin_user)):
  866. return {"ENABLE_LDAP": request.app.state.config.ENABLE_LDAP}
  867. class LdapConfigForm(BaseModel):
  868. enable_ldap: Optional[bool] = None
  869. @router.post("/admin/config/ldap")
  870. async def update_ldap_config(
  871. request: Request, form_data: LdapConfigForm, user=Depends(get_admin_user)
  872. ):
  873. request.app.state.config.ENABLE_LDAP = form_data.enable_ldap
  874. return {"ENABLE_LDAP": request.app.state.config.ENABLE_LDAP}
  875. ############################
  876. # API Key
  877. ############################
  878. # create api key
  879. @router.post("/api_key", response_model=ApiKey)
  880. async def generate_api_key(request: Request, user=Depends(get_current_user)):
  881. if not request.app.state.config.ENABLE_API_KEY:
  882. raise HTTPException(
  883. status.HTTP_403_FORBIDDEN,
  884. detail=ERROR_MESSAGES.API_KEY_CREATION_NOT_ALLOWED,
  885. )
  886. api_key = create_api_key()
  887. success = Users.update_user_api_key_by_id(user.id, api_key)
  888. if success:
  889. return {
  890. "api_key": api_key,
  891. }
  892. else:
  893. raise HTTPException(500, detail=ERROR_MESSAGES.CREATE_API_KEY_ERROR)
  894. # delete api key
  895. @router.delete("/api_key", response_model=bool)
  896. async def delete_api_key(user=Depends(get_current_user)):
  897. success = Users.update_user_api_key_by_id(user.id, None)
  898. return success
  899. # get api key
  900. @router.get("/api_key", response_model=ApiKey)
  901. async def get_api_key(user=Depends(get_current_user)):
  902. api_key = Users.get_user_api_key_by_id(user.id)
  903. if api_key:
  904. return {
  905. "api_key": api_key,
  906. }
  907. else:
  908. raise HTTPException(404, detail=ERROR_MESSAGES.API_KEY_NOT_FOUND)