auths.py 30 KB

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