auths.py 31 KB

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