auths.py 30 KB

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