auths.py 32 KB

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