auths.py 37 KB

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