auths.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872
  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 = str(entry[f"{LDAP_ATTRIBUTE_FOR_MAIL}"])
  201. if not email or email == "" or email == "[]":
  202. raise HTTPException(400, "User does not have a valid email address.")
  203. else:
  204. email = email.lower()
  205. cn = str(entry["cn"])
  206. user_dn = entry.entry_dn
  207. if username == form_data.user.lower():
  208. connection_user = Connection(
  209. server,
  210. user_dn,
  211. form_data.password,
  212. auto_bind="NONE",
  213. authentication="SIMPLE",
  214. )
  215. if not connection_user.bind():
  216. raise HTTPException(400, "Authentication failed.")
  217. user = Users.get_user_by_email(email)
  218. if not user:
  219. try:
  220. user_count = Users.get_num_users()
  221. role = (
  222. "admin"
  223. if user_count == 0
  224. else request.app.state.config.DEFAULT_USER_ROLE
  225. )
  226. user = Auths.insert_new_auth(
  227. email=email,
  228. password=str(uuid.uuid4()),
  229. name=cn,
  230. role=role,
  231. )
  232. if not user:
  233. raise HTTPException(
  234. 500, detail=ERROR_MESSAGES.CREATE_USER_ERROR
  235. )
  236. except HTTPException:
  237. raise
  238. except Exception as err:
  239. log.error(f"LDAP user creation error: {str(err)}")
  240. raise HTTPException(
  241. 500, detail="Internal error occurred during LDAP user creation."
  242. )
  243. user = Auths.authenticate_user_by_trusted_header(email)
  244. if user:
  245. token = create_token(
  246. data={"id": user.id},
  247. expires_delta=parse_duration(
  248. request.app.state.config.JWT_EXPIRES_IN
  249. ),
  250. )
  251. # Set the cookie token
  252. response.set_cookie(
  253. key="token",
  254. value=token,
  255. httponly=True, # Ensures the cookie is not accessible via JavaScript
  256. )
  257. user_permissions = get_permissions(
  258. user.id, request.app.state.config.USER_PERMISSIONS
  259. )
  260. return {
  261. "token": token,
  262. "token_type": "Bearer",
  263. "id": user.id,
  264. "email": user.email,
  265. "name": user.name,
  266. "role": user.role,
  267. "profile_image_url": user.profile_image_url,
  268. "permissions": user_permissions,
  269. }
  270. else:
  271. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  272. else:
  273. raise HTTPException(400, "User record mismatch.")
  274. except Exception as e:
  275. log.error(f"LDAP authentication error: {str(e)}")
  276. raise HTTPException(400, detail="LDAP authentication failed.")
  277. ############################
  278. # SignIn
  279. ############################
  280. @router.post("/signin", response_model=SessionUserResponse)
  281. async def signin(request: Request, response: Response, form_data: SigninForm):
  282. if WEBUI_AUTH_TRUSTED_EMAIL_HEADER:
  283. if WEBUI_AUTH_TRUSTED_EMAIL_HEADER not in request.headers:
  284. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_TRUSTED_HEADER)
  285. trusted_email = request.headers[WEBUI_AUTH_TRUSTED_EMAIL_HEADER].lower()
  286. trusted_name = trusted_email
  287. if WEBUI_AUTH_TRUSTED_NAME_HEADER:
  288. trusted_name = request.headers.get(
  289. WEBUI_AUTH_TRUSTED_NAME_HEADER, trusted_email
  290. )
  291. if not Users.get_user_by_email(trusted_email.lower()):
  292. await signup(
  293. request,
  294. response,
  295. SignupForm(
  296. email=trusted_email, password=str(uuid.uuid4()), name=trusted_name
  297. ),
  298. )
  299. user = Auths.authenticate_user_by_trusted_header(trusted_email)
  300. elif WEBUI_AUTH == False:
  301. admin_email = "admin@localhost"
  302. admin_password = "admin"
  303. if Users.get_user_by_email(admin_email.lower()):
  304. user = Auths.authenticate_user(admin_email.lower(), admin_password)
  305. else:
  306. if Users.get_num_users() != 0:
  307. raise HTTPException(400, detail=ERROR_MESSAGES.EXISTING_USERS)
  308. await signup(
  309. request,
  310. response,
  311. SignupForm(email=admin_email, password=admin_password, name="User"),
  312. )
  313. user = Auths.authenticate_user(admin_email.lower(), admin_password)
  314. else:
  315. user = Auths.authenticate_user(form_data.email.lower(), form_data.password)
  316. if user:
  317. expires_delta = parse_duration(request.app.state.config.JWT_EXPIRES_IN)
  318. expires_at = None
  319. if expires_delta:
  320. expires_at = int(time.time()) + int(expires_delta.total_seconds())
  321. token = create_token(
  322. data={"id": user.id},
  323. expires_delta=expires_delta,
  324. )
  325. datetime_expires_at = (
  326. datetime.datetime.fromtimestamp(expires_at, datetime.timezone.utc)
  327. if expires_at
  328. else None
  329. )
  330. # Set the cookie token
  331. response.set_cookie(
  332. key="token",
  333. value=token,
  334. expires=datetime_expires_at,
  335. httponly=True, # Ensures the cookie is not accessible via JavaScript
  336. samesite=WEBUI_AUTH_COOKIE_SAME_SITE,
  337. secure=WEBUI_AUTH_COOKIE_SECURE,
  338. )
  339. user_permissions = get_permissions(
  340. user.id, request.app.state.config.USER_PERMISSIONS
  341. )
  342. return {
  343. "token": token,
  344. "token_type": "Bearer",
  345. "expires_at": expires_at,
  346. "id": user.id,
  347. "email": user.email,
  348. "name": user.name,
  349. "role": user.role,
  350. "profile_image_url": user.profile_image_url,
  351. "permissions": user_permissions,
  352. }
  353. else:
  354. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  355. ############################
  356. # SignUp
  357. ############################
  358. @router.post("/signup", response_model=SessionUserResponse)
  359. async def signup(request: Request, response: Response, form_data: SignupForm):
  360. if WEBUI_AUTH:
  361. if (
  362. not request.app.state.config.ENABLE_SIGNUP
  363. or not request.app.state.config.ENABLE_LOGIN_FORM
  364. ):
  365. raise HTTPException(
  366. status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.ACCESS_PROHIBITED
  367. )
  368. else:
  369. if Users.get_num_users() != 0:
  370. raise HTTPException(
  371. status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.ACCESS_PROHIBITED
  372. )
  373. user_count = Users.get_num_users()
  374. if not validate_email_format(form_data.email.lower()):
  375. raise HTTPException(
  376. status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.INVALID_EMAIL_FORMAT
  377. )
  378. if Users.get_user_by_email(form_data.email.lower()):
  379. raise HTTPException(400, detail=ERROR_MESSAGES.EMAIL_TAKEN)
  380. try:
  381. role = (
  382. "admin" if user_count == 0 else request.app.state.config.DEFAULT_USER_ROLE
  383. )
  384. if user_count == 0:
  385. # Disable signup after the first user is created
  386. request.app.state.config.ENABLE_SIGNUP = False
  387. hashed = get_password_hash(form_data.password)
  388. user = Auths.insert_new_auth(
  389. form_data.email.lower(),
  390. hashed,
  391. form_data.name,
  392. form_data.profile_image_url,
  393. role,
  394. )
  395. if user:
  396. expires_delta = parse_duration(request.app.state.config.JWT_EXPIRES_IN)
  397. expires_at = None
  398. if expires_delta:
  399. expires_at = int(time.time()) + int(expires_delta.total_seconds())
  400. token = create_token(
  401. data={"id": user.id},
  402. expires_delta=expires_delta,
  403. )
  404. datetime_expires_at = (
  405. datetime.datetime.fromtimestamp(expires_at, datetime.timezone.utc)
  406. if expires_at
  407. else None
  408. )
  409. # Set the cookie token
  410. response.set_cookie(
  411. key="token",
  412. value=token,
  413. expires=datetime_expires_at,
  414. httponly=True, # Ensures the cookie is not accessible via JavaScript
  415. samesite=WEBUI_AUTH_COOKIE_SAME_SITE,
  416. secure=WEBUI_AUTH_COOKIE_SECURE,
  417. )
  418. if request.app.state.config.WEBHOOK_URL:
  419. post_webhook(
  420. request.app.state.WEBUI_NAME,
  421. request.app.state.config.WEBHOOK_URL,
  422. WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  423. {
  424. "action": "signup",
  425. "message": WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  426. "user": user.model_dump_json(exclude_none=True),
  427. },
  428. )
  429. user_permissions = get_permissions(
  430. user.id, request.app.state.config.USER_PERMISSIONS
  431. )
  432. return {
  433. "token": token,
  434. "token_type": "Bearer",
  435. "expires_at": expires_at,
  436. "id": user.id,
  437. "email": user.email,
  438. "name": user.name,
  439. "role": user.role,
  440. "profile_image_url": user.profile_image_url,
  441. "permissions": user_permissions,
  442. }
  443. else:
  444. raise HTTPException(500, detail=ERROR_MESSAGES.CREATE_USER_ERROR)
  445. except Exception as err:
  446. log.error(f"Signup error: {str(err)}")
  447. raise HTTPException(500, detail="An internal error occurred during signup.")
  448. @router.get("/signout")
  449. async def signout(request: Request, response: Response):
  450. response.delete_cookie("token")
  451. if ENABLE_OAUTH_SIGNUP.value:
  452. oauth_id_token = request.cookies.get("oauth_id_token")
  453. if oauth_id_token:
  454. try:
  455. async with ClientSession() as session:
  456. async with session.get(OPENID_PROVIDER_URL.value) as resp:
  457. if resp.status == 200:
  458. openid_data = await resp.json()
  459. logout_url = openid_data.get("end_session_endpoint")
  460. if logout_url:
  461. response.delete_cookie("oauth_id_token")
  462. return RedirectResponse(
  463. headers=response.headers,
  464. url=f"{logout_url}?id_token_hint={oauth_id_token}",
  465. )
  466. else:
  467. raise HTTPException(
  468. status_code=resp.status,
  469. detail="Failed to fetch OpenID configuration",
  470. )
  471. except Exception as e:
  472. log.error(f"OpenID signout error: {str(e)}")
  473. raise HTTPException(
  474. status_code=500,
  475. detail="Failed to sign out from the OpenID provider.",
  476. )
  477. if SIGNOUT_REDIRECT_URI:
  478. return RedirectResponse(
  479. headers=response.headers,
  480. url=SIGNOUT_REDIRECT_URI,
  481. )
  482. return {"status": True}
  483. ############################
  484. # AddUser
  485. ############################
  486. @router.post("/add", response_model=SigninResponse)
  487. async def add_user(form_data: AddUserForm, user=Depends(get_admin_user)):
  488. if not validate_email_format(form_data.email.lower()):
  489. raise HTTPException(
  490. status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.INVALID_EMAIL_FORMAT
  491. )
  492. if Users.get_user_by_email(form_data.email.lower()):
  493. raise HTTPException(400, detail=ERROR_MESSAGES.EMAIL_TAKEN)
  494. try:
  495. hashed = get_password_hash(form_data.password)
  496. user = Auths.insert_new_auth(
  497. form_data.email.lower(),
  498. hashed,
  499. form_data.name,
  500. form_data.profile_image_url,
  501. form_data.role,
  502. )
  503. if user:
  504. token = create_token(data={"id": user.id})
  505. return {
  506. "token": token,
  507. "token_type": "Bearer",
  508. "id": user.id,
  509. "email": user.email,
  510. "name": user.name,
  511. "role": user.role,
  512. "profile_image_url": user.profile_image_url,
  513. }
  514. else:
  515. raise HTTPException(500, detail=ERROR_MESSAGES.CREATE_USER_ERROR)
  516. except Exception as err:
  517. log.error(f"Add user error: {str(err)}")
  518. raise HTTPException(
  519. 500, detail="An internal error occurred while adding the user."
  520. )
  521. ############################
  522. # GetAdminDetails
  523. ############################
  524. @router.get("/admin/details")
  525. async def get_admin_details(request: Request, user=Depends(get_current_user)):
  526. if request.app.state.config.SHOW_ADMIN_DETAILS:
  527. admin_email = request.app.state.config.ADMIN_EMAIL
  528. admin_name = None
  529. log.info(f"Admin details - Email: {admin_email}, Name: {admin_name}")
  530. if admin_email:
  531. admin = Users.get_user_by_email(admin_email)
  532. if admin:
  533. admin_name = admin.name
  534. else:
  535. admin = Users.get_first_user()
  536. if admin:
  537. admin_email = admin.email
  538. admin_name = admin.name
  539. return {
  540. "name": admin_name,
  541. "email": admin_email,
  542. }
  543. else:
  544. raise HTTPException(400, detail=ERROR_MESSAGES.ACTION_PROHIBITED)
  545. ############################
  546. # ToggleSignUp
  547. ############################
  548. @router.get("/admin/config")
  549. async def get_admin_config(request: Request, user=Depends(get_admin_user)):
  550. return {
  551. "SHOW_ADMIN_DETAILS": request.app.state.config.SHOW_ADMIN_DETAILS,
  552. "WEBUI_URL": request.app.state.config.WEBUI_URL,
  553. "ENABLE_SIGNUP": request.app.state.config.ENABLE_SIGNUP,
  554. "ENABLE_API_KEY": request.app.state.config.ENABLE_API_KEY,
  555. "ENABLE_API_KEY_ENDPOINT_RESTRICTIONS": request.app.state.config.ENABLE_API_KEY_ENDPOINT_RESTRICTIONS,
  556. "API_KEY_ALLOWED_ENDPOINTS": request.app.state.config.API_KEY_ALLOWED_ENDPOINTS,
  557. "DEFAULT_USER_ROLE": request.app.state.config.DEFAULT_USER_ROLE,
  558. "JWT_EXPIRES_IN": request.app.state.config.JWT_EXPIRES_IN,
  559. "ENABLE_COMMUNITY_SHARING": request.app.state.config.ENABLE_COMMUNITY_SHARING,
  560. "ENABLE_MESSAGE_RATING": request.app.state.config.ENABLE_MESSAGE_RATING,
  561. "ENABLE_CHANNELS": request.app.state.config.ENABLE_CHANNELS,
  562. "ENABLE_USER_WEBHOOKS": request.app.state.config.ENABLE_USER_WEBHOOKS,
  563. }
  564. class AdminConfig(BaseModel):
  565. SHOW_ADMIN_DETAILS: bool
  566. WEBUI_URL: str
  567. ENABLE_SIGNUP: bool
  568. ENABLE_API_KEY: bool
  569. ENABLE_API_KEY_ENDPOINT_RESTRICTIONS: bool
  570. API_KEY_ALLOWED_ENDPOINTS: str
  571. DEFAULT_USER_ROLE: str
  572. JWT_EXPIRES_IN: str
  573. ENABLE_COMMUNITY_SHARING: bool
  574. ENABLE_MESSAGE_RATING: bool
  575. ENABLE_CHANNELS: bool
  576. ENABLE_USER_WEBHOOKS: bool
  577. @router.post("/admin/config")
  578. async def update_admin_config(
  579. request: Request, form_data: AdminConfig, user=Depends(get_admin_user)
  580. ):
  581. request.app.state.config.SHOW_ADMIN_DETAILS = form_data.SHOW_ADMIN_DETAILS
  582. request.app.state.config.WEBUI_URL = form_data.WEBUI_URL
  583. request.app.state.config.ENABLE_SIGNUP = form_data.ENABLE_SIGNUP
  584. request.app.state.config.ENABLE_API_KEY = form_data.ENABLE_API_KEY
  585. request.app.state.config.ENABLE_API_KEY_ENDPOINT_RESTRICTIONS = (
  586. form_data.ENABLE_API_KEY_ENDPOINT_RESTRICTIONS
  587. )
  588. request.app.state.config.API_KEY_ALLOWED_ENDPOINTS = (
  589. form_data.API_KEY_ALLOWED_ENDPOINTS
  590. )
  591. request.app.state.config.ENABLE_CHANNELS = form_data.ENABLE_CHANNELS
  592. if form_data.DEFAULT_USER_ROLE in ["pending", "user", "admin"]:
  593. request.app.state.config.DEFAULT_USER_ROLE = form_data.DEFAULT_USER_ROLE
  594. pattern = r"^(-1|0|(-?\d+(\.\d+)?)(ms|s|m|h|d|w))$"
  595. # Check if the input string matches the pattern
  596. if re.match(pattern, form_data.JWT_EXPIRES_IN):
  597. request.app.state.config.JWT_EXPIRES_IN = form_data.JWT_EXPIRES_IN
  598. request.app.state.config.ENABLE_COMMUNITY_SHARING = (
  599. form_data.ENABLE_COMMUNITY_SHARING
  600. )
  601. request.app.state.config.ENABLE_MESSAGE_RATING = form_data.ENABLE_MESSAGE_RATING
  602. request.app.state.config.ENABLE_USER_WEBHOOKS = form_data.ENABLE_USER_WEBHOOKS
  603. return {
  604. "SHOW_ADMIN_DETAILS": request.app.state.config.SHOW_ADMIN_DETAILS,
  605. "WEBUI_URL": request.app.state.config.WEBUI_URL,
  606. "ENABLE_SIGNUP": request.app.state.config.ENABLE_SIGNUP,
  607. "ENABLE_API_KEY": request.app.state.config.ENABLE_API_KEY,
  608. "ENABLE_API_KEY_ENDPOINT_RESTRICTIONS": request.app.state.config.ENABLE_API_KEY_ENDPOINT_RESTRICTIONS,
  609. "API_KEY_ALLOWED_ENDPOINTS": request.app.state.config.API_KEY_ALLOWED_ENDPOINTS,
  610. "ENABLE_CHANNELS": request.app.state.config.ENABLE_CHANNELS,
  611. "DEFAULT_USER_ROLE": request.app.state.config.DEFAULT_USER_ROLE,
  612. "JWT_EXPIRES_IN": request.app.state.config.JWT_EXPIRES_IN,
  613. "ENABLE_COMMUNITY_SHARING": request.app.state.config.ENABLE_COMMUNITY_SHARING,
  614. "ENABLE_MESSAGE_RATING": request.app.state.config.ENABLE_MESSAGE_RATING,
  615. "ENABLE_USER_WEBHOOKS": request.app.state.config.ENABLE_USER_WEBHOOKS,
  616. }
  617. class LdapServerConfig(BaseModel):
  618. label: str
  619. host: str
  620. port: Optional[int] = None
  621. attribute_for_mail: str = "mail"
  622. attribute_for_username: str = "uid"
  623. app_dn: str
  624. app_dn_password: str
  625. search_base: str
  626. search_filters: str = ""
  627. use_tls: bool = True
  628. certificate_path: Optional[str] = None
  629. ciphers: Optional[str] = "ALL"
  630. @router.get("/admin/config/ldap/server", response_model=LdapServerConfig)
  631. async def get_ldap_server(request: Request, user=Depends(get_admin_user)):
  632. return {
  633. "label": request.app.state.config.LDAP_SERVER_LABEL,
  634. "host": request.app.state.config.LDAP_SERVER_HOST,
  635. "port": request.app.state.config.LDAP_SERVER_PORT,
  636. "attribute_for_mail": request.app.state.config.LDAP_ATTRIBUTE_FOR_MAIL,
  637. "attribute_for_username": request.app.state.config.LDAP_ATTRIBUTE_FOR_USERNAME,
  638. "app_dn": request.app.state.config.LDAP_APP_DN,
  639. "app_dn_password": request.app.state.config.LDAP_APP_PASSWORD,
  640. "search_base": request.app.state.config.LDAP_SEARCH_BASE,
  641. "search_filters": request.app.state.config.LDAP_SEARCH_FILTERS,
  642. "use_tls": request.app.state.config.LDAP_USE_TLS,
  643. "certificate_path": request.app.state.config.LDAP_CA_CERT_FILE,
  644. "ciphers": request.app.state.config.LDAP_CIPHERS,
  645. }
  646. @router.post("/admin/config/ldap/server")
  647. async def update_ldap_server(
  648. request: Request, form_data: LdapServerConfig, user=Depends(get_admin_user)
  649. ):
  650. required_fields = [
  651. "label",
  652. "host",
  653. "attribute_for_mail",
  654. "attribute_for_username",
  655. "app_dn",
  656. "app_dn_password",
  657. "search_base",
  658. ]
  659. for key in required_fields:
  660. value = getattr(form_data, key)
  661. if not value:
  662. raise HTTPException(400, detail=f"Required field {key} is empty")
  663. request.app.state.config.LDAP_SERVER_LABEL = form_data.label
  664. request.app.state.config.LDAP_SERVER_HOST = form_data.host
  665. request.app.state.config.LDAP_SERVER_PORT = form_data.port
  666. request.app.state.config.LDAP_ATTRIBUTE_FOR_MAIL = form_data.attribute_for_mail
  667. request.app.state.config.LDAP_ATTRIBUTE_FOR_USERNAME = (
  668. form_data.attribute_for_username
  669. )
  670. request.app.state.config.LDAP_APP_DN = form_data.app_dn
  671. request.app.state.config.LDAP_APP_PASSWORD = form_data.app_dn_password
  672. request.app.state.config.LDAP_SEARCH_BASE = form_data.search_base
  673. request.app.state.config.LDAP_SEARCH_FILTERS = form_data.search_filters
  674. request.app.state.config.LDAP_USE_TLS = form_data.use_tls
  675. request.app.state.config.LDAP_CA_CERT_FILE = form_data.certificate_path
  676. request.app.state.config.LDAP_CIPHERS = form_data.ciphers
  677. return {
  678. "label": request.app.state.config.LDAP_SERVER_LABEL,
  679. "host": request.app.state.config.LDAP_SERVER_HOST,
  680. "port": request.app.state.config.LDAP_SERVER_PORT,
  681. "attribute_for_mail": request.app.state.config.LDAP_ATTRIBUTE_FOR_MAIL,
  682. "attribute_for_username": request.app.state.config.LDAP_ATTRIBUTE_FOR_USERNAME,
  683. "app_dn": request.app.state.config.LDAP_APP_DN,
  684. "app_dn_password": request.app.state.config.LDAP_APP_PASSWORD,
  685. "search_base": request.app.state.config.LDAP_SEARCH_BASE,
  686. "search_filters": request.app.state.config.LDAP_SEARCH_FILTERS,
  687. "use_tls": request.app.state.config.LDAP_USE_TLS,
  688. "certificate_path": request.app.state.config.LDAP_CA_CERT_FILE,
  689. "ciphers": request.app.state.config.LDAP_CIPHERS,
  690. }
  691. @router.get("/admin/config/ldap")
  692. async def get_ldap_config(request: Request, user=Depends(get_admin_user)):
  693. return {"ENABLE_LDAP": request.app.state.config.ENABLE_LDAP}
  694. class LdapConfigForm(BaseModel):
  695. enable_ldap: Optional[bool] = None
  696. @router.post("/admin/config/ldap")
  697. async def update_ldap_config(
  698. request: Request, form_data: LdapConfigForm, user=Depends(get_admin_user)
  699. ):
  700. request.app.state.config.ENABLE_LDAP = form_data.enable_ldap
  701. return {"ENABLE_LDAP": request.app.state.config.ENABLE_LDAP}
  702. ############################
  703. # API Key
  704. ############################
  705. # create api key
  706. @router.post("/api_key", response_model=ApiKey)
  707. async def generate_api_key(request: Request, user=Depends(get_current_user)):
  708. if not request.app.state.config.ENABLE_API_KEY:
  709. raise HTTPException(
  710. status.HTTP_403_FORBIDDEN,
  711. detail=ERROR_MESSAGES.API_KEY_CREATION_NOT_ALLOWED,
  712. )
  713. api_key = create_api_key()
  714. success = Users.update_user_api_key_by_id(user.id, api_key)
  715. if success:
  716. return {
  717. "api_key": api_key,
  718. }
  719. else:
  720. raise HTTPException(500, detail=ERROR_MESSAGES.CREATE_API_KEY_ERROR)
  721. # delete api key
  722. @router.delete("/api_key", response_model=bool)
  723. async def delete_api_key(user=Depends(get_current_user)):
  724. success = Users.update_user_api_key_by_id(user.id, None)
  725. return success
  726. # get api key
  727. @router.get("/api_key", response_model=ApiKey)
  728. async def get_api_key(user=Depends(get_current_user)):
  729. api_key = Users.get_user_api_key_by_id(user.id)
  730. if api_key:
  731. return {
  732. "api_key": api_key,
  733. }
  734. else:
  735. raise HTTPException(404, detail=ERROR_MESSAGES.API_KEY_NOT_FOUND)