auths.py 29 KB

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