auths.py 33 KB

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