auths.py 29 KB

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