auths.py 31 KB

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