auths.py 29 KB

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