auths.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  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. )
  36. from pydantic import BaseModel
  37. from open_webui.utils.misc import parse_duration, validate_email_format
  38. from open_webui.utils.auth import (
  39. create_api_key,
  40. create_token,
  41. get_admin_user,
  42. get_verified_user,
  43. get_current_user,
  44. get_password_hash,
  45. )
  46. from open_webui.utils.webhook import post_webhook
  47. from open_webui.utils.access_control import get_permissions
  48. from typing import Optional, List
  49. from ssl import CERT_REQUIRED, PROTOCOL_TLS
  50. from ldap3 import Server, Connection, NONE, Tls
  51. from ldap3.utils.conv import escape_filter_chars
  52. router = APIRouter()
  53. log = logging.getLogger(__name__)
  54. log.setLevel(SRC_LOG_LEVELS["MAIN"])
  55. ############################
  56. # GetSessionUser
  57. ############################
  58. class SessionUserResponse(Token, UserResponse):
  59. expires_at: Optional[int] = None
  60. permissions: Optional[dict] = None
  61. @router.get("/", response_model=SessionUserResponse)
  62. async def get_session_user(
  63. request: Request, response: Response, user=Depends(get_current_user)
  64. ):
  65. expires_delta = parse_duration(request.app.state.config.JWT_EXPIRES_IN)
  66. expires_at = None
  67. if expires_delta:
  68. expires_at = int(time.time()) + int(expires_delta.total_seconds())
  69. token = create_token(
  70. data={"id": user.id},
  71. expires_delta=expires_delta,
  72. )
  73. datetime_expires_at = (
  74. datetime.datetime.fromtimestamp(expires_at, datetime.timezone.utc)
  75. if expires_at
  76. else None
  77. )
  78. # Set the cookie token
  79. response.set_cookie(
  80. key="token",
  81. value=token,
  82. expires=datetime_expires_at,
  83. httponly=True, # Ensures the cookie is not accessible via JavaScript
  84. samesite=WEBUI_AUTH_COOKIE_SAME_SITE,
  85. secure=WEBUI_AUTH_COOKIE_SECURE,
  86. )
  87. user_permissions = get_permissions(
  88. user.id, request.app.state.config.USER_PERMISSIONS
  89. )
  90. return {
  91. "token": token,
  92. "token_type": "Bearer",
  93. "expires_at": expires_at,
  94. "id": user.id,
  95. "email": user.email,
  96. "name": user.name,
  97. "role": user.role,
  98. "profile_image_url": user.profile_image_url,
  99. "permissions": user_permissions,
  100. }
  101. ############################
  102. # Update Profile
  103. ############################
  104. @router.post("/update/profile", response_model=UserResponse)
  105. async def update_profile(
  106. form_data: UpdateProfileForm, session_user=Depends(get_verified_user)
  107. ):
  108. if session_user:
  109. user = Users.update_user_by_id(
  110. session_user.id,
  111. {"profile_image_url": form_data.profile_image_url, "name": form_data.name},
  112. )
  113. if user:
  114. return user
  115. else:
  116. raise HTTPException(400, detail=ERROR_MESSAGES.DEFAULT())
  117. else:
  118. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  119. ############################
  120. # Update Password
  121. ############################
  122. @router.post("/update/password", response_model=bool)
  123. async def update_password(
  124. form_data: UpdatePasswordForm, session_user=Depends(get_current_user)
  125. ):
  126. if WEBUI_AUTH_TRUSTED_EMAIL_HEADER:
  127. raise HTTPException(400, detail=ERROR_MESSAGES.ACTION_PROHIBITED)
  128. if session_user:
  129. user = Auths.authenticate_user(session_user.email, form_data.password)
  130. if user:
  131. hashed = get_password_hash(form_data.new_password)
  132. return Auths.update_user_password_by_id(user.id, hashed)
  133. else:
  134. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_PASSWORD)
  135. else:
  136. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  137. ############################
  138. # LDAP Authentication
  139. ############################
  140. @router.post("/ldap", response_model=SessionUserResponse)
  141. async def ldap_auth(request: Request, response: Response, form_data: LdapForm):
  142. ENABLE_LDAP = request.app.state.config.ENABLE_LDAP
  143. LDAP_SERVER_LABEL = request.app.state.config.LDAP_SERVER_LABEL
  144. LDAP_SERVER_HOST = request.app.state.config.LDAP_SERVER_HOST
  145. LDAP_SERVER_PORT = request.app.state.config.LDAP_SERVER_PORT
  146. LDAP_ATTRIBUTE_FOR_MAIL = request.app.state.config.LDAP_ATTRIBUTE_FOR_MAIL
  147. LDAP_ATTRIBUTE_FOR_USERNAME = request.app.state.config.LDAP_ATTRIBUTE_FOR_USERNAME
  148. LDAP_SEARCH_BASE = request.app.state.config.LDAP_SEARCH_BASE
  149. LDAP_SEARCH_FILTERS = request.app.state.config.LDAP_SEARCH_FILTERS
  150. LDAP_APP_DN = request.app.state.config.LDAP_APP_DN
  151. LDAP_APP_PASSWORD = request.app.state.config.LDAP_APP_PASSWORD
  152. LDAP_USE_TLS = request.app.state.config.LDAP_USE_TLS
  153. LDAP_CA_CERT_FILE = request.app.state.config.LDAP_CA_CERT_FILE
  154. LDAP_CIPHERS = (
  155. request.app.state.config.LDAP_CIPHERS
  156. if request.app.state.config.LDAP_CIPHERS
  157. else "ALL"
  158. )
  159. if not ENABLE_LDAP:
  160. raise HTTPException(400, detail="LDAP authentication is not enabled")
  161. try:
  162. tls = Tls(
  163. validate=CERT_REQUIRED,
  164. version=PROTOCOL_TLS,
  165. ca_certs_file=LDAP_CA_CERT_FILE,
  166. ciphers=LDAP_CIPHERS,
  167. )
  168. except Exception as e:
  169. log.error(f"An error occurred on TLS: {str(e)}")
  170. raise HTTPException(400, detail=str(e))
  171. try:
  172. server = Server(
  173. host=LDAP_SERVER_HOST,
  174. port=LDAP_SERVER_PORT,
  175. get_info=NONE,
  176. use_ssl=LDAP_USE_TLS,
  177. tls=tls,
  178. )
  179. connection_app = Connection(
  180. server,
  181. LDAP_APP_DN,
  182. LDAP_APP_PASSWORD,
  183. auto_bind="NONE",
  184. authentication="SIMPLE",
  185. )
  186. if not connection_app.bind():
  187. raise HTTPException(400, detail="Application account bind failed")
  188. search_success = connection_app.search(
  189. search_base=LDAP_SEARCH_BASE,
  190. search_filter=f"(&({LDAP_ATTRIBUTE_FOR_USERNAME}={escape_filter_chars(form_data.user.lower())}){LDAP_SEARCH_FILTERS})",
  191. attributes=[
  192. f"{LDAP_ATTRIBUTE_FOR_USERNAME}",
  193. f"{LDAP_ATTRIBUTE_FOR_MAIL}",
  194. "cn",
  195. ],
  196. )
  197. if not search_success:
  198. raise HTTPException(400, detail="User not found in the LDAP server")
  199. entry = connection_app.entries[0]
  200. username = str(entry[f"{LDAP_ATTRIBUTE_FOR_USERNAME}"]).lower()
  201. mail = str(entry[f"{LDAP_ATTRIBUTE_FOR_MAIL}"])
  202. if not mail or mail == "" or mail == "[]":
  203. raise HTTPException(400, f"User {form_data.user} does not have mail.")
  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, f"Authentication failed for {form_data.user}")
  216. user = Users.get_user_by_email(mail)
  217. if not user:
  218. try:
  219. role = (
  220. "admin"
  221. if Users.get_num_users() == 0
  222. else request.app.state.config.DEFAULT_USER_ROLE
  223. )
  224. user = Auths.insert_new_auth(
  225. email=mail, password=str(uuid.uuid4()), name=cn, role=role
  226. )
  227. if not user:
  228. raise HTTPException(
  229. 500, detail=ERROR_MESSAGES.CREATE_USER_ERROR
  230. )
  231. except HTTPException:
  232. raise
  233. except Exception as err:
  234. raise HTTPException(500, detail=ERROR_MESSAGES.DEFAULT(err))
  235. user = Auths.authenticate_user_by_trusted_header(mail)
  236. if user:
  237. token = create_token(
  238. data={"id": user.id},
  239. expires_delta=parse_duration(
  240. request.app.state.config.JWT_EXPIRES_IN
  241. ),
  242. )
  243. # Set the cookie token
  244. response.set_cookie(
  245. key="token",
  246. value=token,
  247. httponly=True, # Ensures the cookie is not accessible via JavaScript
  248. )
  249. user_permissions = get_permissions(
  250. user.id, request.app.state.config.USER_PERMISSIONS
  251. )
  252. return {
  253. "token": token,
  254. "token_type": "Bearer",
  255. "id": user.id,
  256. "email": user.email,
  257. "name": user.name,
  258. "role": user.role,
  259. "profile_image_url": user.profile_image_url,
  260. "permissions": user_permissions,
  261. }
  262. else:
  263. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  264. else:
  265. raise HTTPException(
  266. 400,
  267. f"User {form_data.user} does not match the record. Search result: {str(entry[f'{LDAP_ATTRIBUTE_FOR_USERNAME}'])}",
  268. )
  269. except Exception as e:
  270. raise HTTPException(400, detail=str(e))
  271. ############################
  272. # SignIn
  273. ############################
  274. @router.post("/signin", response_model=SessionUserResponse)
  275. async def signin(request: Request, response: Response, form_data: SigninForm):
  276. if WEBUI_AUTH_TRUSTED_EMAIL_HEADER:
  277. if WEBUI_AUTH_TRUSTED_EMAIL_HEADER not in request.headers:
  278. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_TRUSTED_HEADER)
  279. trusted_email = request.headers[WEBUI_AUTH_TRUSTED_EMAIL_HEADER].lower()
  280. trusted_name = trusted_email
  281. if WEBUI_AUTH_TRUSTED_NAME_HEADER:
  282. trusted_name = request.headers.get(
  283. WEBUI_AUTH_TRUSTED_NAME_HEADER, trusted_email
  284. )
  285. if not Users.get_user_by_email(trusted_email.lower()):
  286. await signup(
  287. request,
  288. response,
  289. SignupForm(
  290. email=trusted_email, password=str(uuid.uuid4()), name=trusted_name
  291. ),
  292. )
  293. user = Auths.authenticate_user_by_trusted_header(trusted_email)
  294. elif WEBUI_AUTH == False:
  295. admin_email = "admin@localhost"
  296. admin_password = "admin"
  297. if Users.get_user_by_email(admin_email.lower()):
  298. user = Auths.authenticate_user(admin_email.lower(), admin_password)
  299. else:
  300. if Users.get_num_users() != 0:
  301. raise HTTPException(400, detail=ERROR_MESSAGES.EXISTING_USERS)
  302. await signup(
  303. request,
  304. response,
  305. SignupForm(email=admin_email, password=admin_password, name="User"),
  306. )
  307. user = Auths.authenticate_user(admin_email.lower(), admin_password)
  308. else:
  309. user = Auths.authenticate_user(form_data.email.lower(), form_data.password)
  310. if user:
  311. expires_delta = parse_duration(request.app.state.config.JWT_EXPIRES_IN)
  312. expires_at = None
  313. if expires_delta:
  314. expires_at = int(time.time()) + int(expires_delta.total_seconds())
  315. token = create_token(
  316. data={"id": user.id},
  317. expires_delta=expires_delta,
  318. )
  319. datetime_expires_at = (
  320. datetime.datetime.fromtimestamp(expires_at, datetime.timezone.utc)
  321. if expires_at
  322. else None
  323. )
  324. # Set the cookie token
  325. response.set_cookie(
  326. key="token",
  327. value=token,
  328. expires=datetime_expires_at,
  329. httponly=True, # Ensures the cookie is not accessible via JavaScript
  330. samesite=WEBUI_AUTH_COOKIE_SAME_SITE,
  331. secure=WEBUI_AUTH_COOKIE_SECURE,
  332. )
  333. user_permissions = get_permissions(
  334. user.id, request.app.state.config.USER_PERMISSIONS
  335. )
  336. return {
  337. "token": token,
  338. "token_type": "Bearer",
  339. "expires_at": expires_at,
  340. "id": user.id,
  341. "email": user.email,
  342. "name": user.name,
  343. "role": user.role,
  344. "profile_image_url": user.profile_image_url,
  345. "permissions": user_permissions,
  346. }
  347. else:
  348. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  349. ############################
  350. # SignUp
  351. ############################
  352. @router.post("/signup", response_model=SessionUserResponse)
  353. async def signup(request: Request, response: Response, form_data: SignupForm):
  354. if WEBUI_AUTH:
  355. if (
  356. not request.app.state.config.ENABLE_SIGNUP
  357. or not request.app.state.config.ENABLE_LOGIN_FORM
  358. ):
  359. raise HTTPException(
  360. status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.ACCESS_PROHIBITED
  361. )
  362. else:
  363. if Users.get_num_users() != 0:
  364. raise HTTPException(
  365. status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.ACCESS_PROHIBITED
  366. )
  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"
  376. if Users.get_num_users() == 0
  377. else request.app.state.config.DEFAULT_USER_ROLE
  378. )
  379. if Users.get_num_users() == 0:
  380. # Disable signup after the first user is created
  381. request.app.state.config.ENABLE_SIGNUP = False
  382. hashed = get_password_hash(form_data.password)
  383. user = Auths.insert_new_auth(
  384. form_data.email.lower(),
  385. hashed,
  386. form_data.name,
  387. form_data.profile_image_url,
  388. role,
  389. )
  390. if user:
  391. expires_delta = parse_duration(request.app.state.config.JWT_EXPIRES_IN)
  392. expires_at = None
  393. if expires_delta:
  394. expires_at = int(time.time()) + int(expires_delta.total_seconds())
  395. token = create_token(
  396. data={"id": user.id},
  397. expires_delta=expires_delta,
  398. )
  399. datetime_expires_at = (
  400. datetime.datetime.fromtimestamp(expires_at, datetime.timezone.utc)
  401. if expires_at
  402. else None
  403. )
  404. # Set the cookie token
  405. response.set_cookie(
  406. key="token",
  407. value=token,
  408. expires=datetime_expires_at,
  409. httponly=True, # Ensures the cookie is not accessible via JavaScript
  410. samesite=WEBUI_AUTH_COOKIE_SAME_SITE,
  411. secure=WEBUI_AUTH_COOKIE_SECURE,
  412. )
  413. if request.app.state.config.WEBHOOK_URL:
  414. post_webhook(
  415. request.app.state.config.WEBHOOK_URL,
  416. WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  417. {
  418. "action": "signup",
  419. "message": WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  420. "user": user.model_dump_json(exclude_none=True),
  421. },
  422. )
  423. user_permissions = get_permissions(
  424. user.id, request.app.state.config.USER_PERMISSIONS
  425. )
  426. return {
  427. "token": token,
  428. "token_type": "Bearer",
  429. "expires_at": expires_at,
  430. "id": user.id,
  431. "email": user.email,
  432. "name": user.name,
  433. "role": user.role,
  434. "profile_image_url": user.profile_image_url,
  435. "permissions": user_permissions,
  436. }
  437. else:
  438. raise HTTPException(500, detail=ERROR_MESSAGES.CREATE_USER_ERROR)
  439. except Exception as err:
  440. raise HTTPException(500, detail=ERROR_MESSAGES.DEFAULT(err))
  441. @router.get("/signout")
  442. async def signout(request: Request, response: Response):
  443. response.delete_cookie("token")
  444. if ENABLE_OAUTH_SIGNUP.value:
  445. oauth_id_token = request.cookies.get("oauth_id_token")
  446. if oauth_id_token:
  447. try:
  448. async with ClientSession() as session:
  449. async with session.get(OPENID_PROVIDER_URL.value) as resp:
  450. if resp.status == 200:
  451. openid_data = await resp.json()
  452. logout_url = openid_data.get("end_session_endpoint")
  453. if logout_url:
  454. response.delete_cookie("oauth_id_token")
  455. return RedirectResponse(
  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. print(admin_email, 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)