auths.py 30 KB

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