auths.py 29 KB

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