auths.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794
  1. import re
  2. import uuid
  3. import time
  4. import datetime
  5. import logging
  6. from open_webui.apps.webui.models.auths import (
  7. AddUserForm,
  8. ApiKey,
  9. Auths,
  10. Token,
  11. LdapForm,
  12. SigninForm,
  13. SigninResponse,
  14. SignupForm,
  15. UpdatePasswordForm,
  16. UpdateProfileForm,
  17. UserResponse,
  18. )
  19. from open_webui.apps.webui.models.users import Users
  20. from open_webui.constants import ERROR_MESSAGES, WEBHOOK_MESSAGES
  21. from open_webui.env import (
  22. WEBUI_AUTH,
  23. WEBUI_AUTH_TRUSTED_EMAIL_HEADER,
  24. WEBUI_AUTH_TRUSTED_NAME_HEADER,
  25. WEBUI_SESSION_COOKIE_SAME_SITE,
  26. WEBUI_SESSION_COOKIE_SECURE,
  27. SRC_LOG_LEVELS,
  28. )
  29. from fastapi import APIRouter, Depends, HTTPException, Request, status
  30. from fastapi.responses import RedirectResponse, Response
  31. from open_webui.config import (
  32. OAUTH_PROVIDER_NAME,
  33. OAUTH_LOGOUT_URL,
  34. )
  35. from pydantic import BaseModel
  36. from open_webui.utils.misc import parse_duration, validate_email_format
  37. from open_webui.utils.utils import (
  38. create_api_key,
  39. create_token,
  40. get_admin_user,
  41. get_verified_user,
  42. get_current_user,
  43. get_password_hash,
  44. )
  45. from open_webui.utils.webhook import post_webhook
  46. from open_webui.utils.access_control import get_permissions
  47. from typing import Optional, List
  48. from ssl import CERT_REQUIRED, PROTOCOL_TLS
  49. from ldap3 import Server, Connection, ALL, Tls
  50. from ldap3.utils.conv import escape_filter_chars
  51. router = APIRouter()
  52. log = logging.getLogger(__name__)
  53. log.setLevel(SRC_LOG_LEVELS["MAIN"])
  54. ############################
  55. # GetSessionUser
  56. ############################
  57. class SessionUserResponse(Token, UserResponse):
  58. expires_at: Optional[int] = None
  59. permissions: Optional[dict] = None
  60. @router.get("/", response_model=SessionUserResponse)
  61. async def get_session_user(
  62. request: Request, response: Response, user=Depends(get_current_user)
  63. ):
  64. expires_delta = parse_duration(request.app.state.config.JWT_EXPIRES_IN)
  65. expires_at = None
  66. if expires_delta:
  67. expires_at = int(time.time()) + int(expires_delta.total_seconds())
  68. token = create_token(
  69. data={"id": user.id},
  70. expires_delta=expires_delta,
  71. )
  72. datetime_expires_at = (
  73. datetime.datetime.fromtimestamp(expires_at, datetime.timezone.utc)
  74. if expires_at
  75. else None
  76. )
  77. # Set the cookie token
  78. response.set_cookie(
  79. key="token",
  80. value=token,
  81. expires=datetime_expires_at,
  82. httponly=True, # Ensures the cookie is not accessible via JavaScript
  83. samesite=WEBUI_SESSION_COOKIE_SAME_SITE,
  84. secure=WEBUI_SESSION_COOKIE_SECURE,
  85. )
  86. user_permissions = get_permissions(
  87. user.id, request.app.state.config.USER_PERMISSIONS
  88. )
  89. return {
  90. "token": token,
  91. "token_type": "Bearer",
  92. "expires_at": expires_at,
  93. "id": user.id,
  94. "email": user.email,
  95. "name": user.name,
  96. "role": user.role,
  97. "profile_image_url": user.profile_image_url,
  98. "permissions": user_permissions,
  99. }
  100. ############################
  101. # Update Profile
  102. ############################
  103. @router.post("/update/profile", response_model=UserResponse)
  104. async def update_profile(
  105. form_data: UpdateProfileForm, session_user=Depends(get_verified_user)
  106. ):
  107. if session_user:
  108. user = Users.update_user_by_id(
  109. session_user.id,
  110. {"profile_image_url": form_data.profile_image_url, "name": form_data.name},
  111. )
  112. if user:
  113. return user
  114. else:
  115. raise HTTPException(400, detail=ERROR_MESSAGES.DEFAULT())
  116. else:
  117. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  118. ############################
  119. # Update Password
  120. ############################
  121. @router.post("/update/password", response_model=bool)
  122. async def update_password(
  123. form_data: UpdatePasswordForm, session_user=Depends(get_current_user)
  124. ):
  125. if WEBUI_AUTH_TRUSTED_EMAIL_HEADER:
  126. raise HTTPException(400, detail=ERROR_MESSAGES.ACTION_PROHIBITED)
  127. if session_user:
  128. user = Auths.authenticate_user(session_user.email, form_data.password)
  129. if user:
  130. hashed = get_password_hash(form_data.new_password)
  131. return Auths.update_user_password_by_id(user.id, hashed)
  132. else:
  133. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_PASSWORD)
  134. else:
  135. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  136. ############################
  137. # LDAP Authentication
  138. ############################
  139. @router.post("/ldap", response_model=SigninResponse)
  140. async def ldap_auth(request: Request, response: Response, form_data: LdapForm):
  141. ENABLE_LDAP = request.app.state.config.ENABLE_LDAP
  142. LDAP_SERVER_LABEL = request.app.state.config.LDAP_SERVER_LABEL
  143. LDAP_SERVER_HOST = request.app.state.config.LDAP_SERVER_HOST
  144. LDAP_SERVER_PORT = request.app.state.config.LDAP_SERVER_PORT
  145. LDAP_ATTRIBUTE_FOR_USERNAME = request.app.state.config.LDAP_ATTRIBUTE_FOR_USERNAME
  146. LDAP_SEARCH_BASE = request.app.state.config.LDAP_SEARCH_BASE
  147. LDAP_SEARCH_FILTERS = request.app.state.config.LDAP_SEARCH_FILTERS
  148. LDAP_APP_DN = request.app.state.config.LDAP_APP_DN
  149. LDAP_APP_PASSWORD = request.app.state.config.LDAP_APP_PASSWORD
  150. LDAP_USE_TLS = request.app.state.config.LDAP_USE_TLS
  151. LDAP_CA_CERT_FILE = request.app.state.config.LDAP_CA_CERT_FILE
  152. LDAP_CIPHERS = (
  153. request.app.state.config.LDAP_CIPHERS
  154. if request.app.state.config.LDAP_CIPHERS
  155. else "ALL"
  156. )
  157. if not ENABLE_LDAP:
  158. raise HTTPException(400, detail="LDAP authentication is not enabled")
  159. try:
  160. tls = Tls(
  161. validate=CERT_REQUIRED,
  162. version=PROTOCOL_TLS,
  163. ca_certs_file=LDAP_CA_CERT_FILE,
  164. ciphers=LDAP_CIPHERS,
  165. )
  166. except Exception as e:
  167. log.error(f"An error occurred on TLS: {str(e)}")
  168. raise HTTPException(400, detail=str(e))
  169. try:
  170. server = Server(
  171. host=LDAP_SERVER_HOST,
  172. port=LDAP_SERVER_PORT,
  173. get_info=ALL,
  174. use_ssl=LDAP_USE_TLS,
  175. tls=tls,
  176. )
  177. connection_app = Connection(
  178. server,
  179. LDAP_APP_DN,
  180. LDAP_APP_PASSWORD,
  181. auto_bind="NONE",
  182. authentication="SIMPLE",
  183. )
  184. if not connection_app.bind():
  185. raise HTTPException(400, detail="Application account bind failed")
  186. search_success = connection_app.search(
  187. search_base=LDAP_SEARCH_BASE,
  188. search_filter=f"(&({LDAP_ATTRIBUTE_FOR_USERNAME}={escape_filter_chars(form_data.user.lower())}){LDAP_SEARCH_FILTERS})",
  189. attributes=[f"{LDAP_ATTRIBUTE_FOR_USERNAME}", "mail", "cn"],
  190. )
  191. if not search_success:
  192. raise HTTPException(400, detail="User not found in the LDAP server")
  193. entry = connection_app.entries[0]
  194. username = str(entry[f"{LDAP_ATTRIBUTE_FOR_USERNAME}"]).lower()
  195. mail = str(entry["mail"])
  196. cn = str(entry["cn"])
  197. user_dn = entry.entry_dn
  198. if username == form_data.user.lower():
  199. connection_user = Connection(
  200. server,
  201. user_dn,
  202. form_data.password,
  203. auto_bind="NONE",
  204. authentication="SIMPLE",
  205. )
  206. if not connection_user.bind():
  207. raise HTTPException(400, f"Authentication failed for {form_data.user}")
  208. user = Users.get_user_by_email(mail)
  209. if not user:
  210. try:
  211. role = (
  212. "admin"
  213. if Users.get_num_users() == 0
  214. else request.app.state.config.DEFAULT_USER_ROLE
  215. )
  216. user = Auths.insert_new_auth(
  217. email=mail, password=str(uuid.uuid4()), name=cn, role=role
  218. )
  219. if not user:
  220. raise HTTPException(
  221. 500, detail=ERROR_MESSAGES.CREATE_USER_ERROR
  222. )
  223. except HTTPException:
  224. raise
  225. except Exception as err:
  226. raise HTTPException(500, detail=ERROR_MESSAGES.DEFAULT(err))
  227. user = Auths.authenticate_user_by_trusted_header(mail)
  228. if user:
  229. token = create_token(
  230. data={"id": user.id},
  231. expires_delta=parse_duration(
  232. request.app.state.config.JWT_EXPIRES_IN
  233. ),
  234. )
  235. # Set the cookie token
  236. response.set_cookie(
  237. key="token",
  238. value=token,
  239. httponly=True, # Ensures the cookie is not accessible via JavaScript
  240. )
  241. return {
  242. "token": token,
  243. "token_type": "Bearer",
  244. "id": user.id,
  245. "email": user.email,
  246. "name": user.name,
  247. "role": user.role,
  248. "profile_image_url": user.profile_image_url,
  249. }
  250. else:
  251. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  252. else:
  253. raise HTTPException(
  254. 400,
  255. f"User {form_data.user} does not match the record. Search result: {str(entry[f'{LDAP_ATTRIBUTE_FOR_USERNAME}'])}",
  256. )
  257. except Exception as e:
  258. raise HTTPException(400, detail=str(e))
  259. ############################
  260. # SignIn
  261. ############################
  262. @router.post("/signin", response_model=SessionUserResponse)
  263. async def signin(request: Request, response: Response, form_data: SigninForm):
  264. if WEBUI_AUTH_TRUSTED_EMAIL_HEADER:
  265. if WEBUI_AUTH_TRUSTED_EMAIL_HEADER not in request.headers:
  266. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_TRUSTED_HEADER)
  267. trusted_email = request.headers[WEBUI_AUTH_TRUSTED_EMAIL_HEADER].lower()
  268. trusted_name = trusted_email
  269. if WEBUI_AUTH_TRUSTED_NAME_HEADER:
  270. trusted_name = request.headers.get(
  271. WEBUI_AUTH_TRUSTED_NAME_HEADER, trusted_email
  272. )
  273. if not Users.get_user_by_email(trusted_email.lower()):
  274. await signup(
  275. request,
  276. response,
  277. SignupForm(
  278. email=trusted_email, password=str(uuid.uuid4()), name=trusted_name
  279. ),
  280. )
  281. user = Auths.authenticate_user_by_trusted_header(trusted_email)
  282. elif WEBUI_AUTH == False:
  283. admin_email = "admin@localhost"
  284. admin_password = "admin"
  285. if Users.get_user_by_email(admin_email.lower()):
  286. user = Auths.authenticate_user(admin_email.lower(), admin_password)
  287. else:
  288. if Users.get_num_users() != 0:
  289. raise HTTPException(400, detail=ERROR_MESSAGES.EXISTING_USERS)
  290. await signup(
  291. request,
  292. response,
  293. SignupForm(email=admin_email, password=admin_password, name="User"),
  294. )
  295. user = Auths.authenticate_user(admin_email.lower(), admin_password)
  296. else:
  297. user = Auths.authenticate_user(form_data.email.lower(), form_data.password)
  298. if user:
  299. expires_delta = parse_duration(request.app.state.config.JWT_EXPIRES_IN)
  300. expires_at = None
  301. if expires_delta:
  302. expires_at = int(time.time()) + int(expires_delta.total_seconds())
  303. token = create_token(
  304. data={"id": user.id},
  305. expires_delta=expires_delta,
  306. )
  307. datetime_expires_at = (
  308. datetime.datetime.fromtimestamp(expires_at, datetime.timezone.utc)
  309. if expires_at
  310. else None
  311. )
  312. # Set the cookie token
  313. response.set_cookie(
  314. key="token",
  315. value=token,
  316. expires=datetime_expires_at,
  317. httponly=True, # Ensures the cookie is not accessible via JavaScript
  318. samesite=WEBUI_SESSION_COOKIE_SAME_SITE,
  319. secure=WEBUI_SESSION_COOKIE_SECURE,
  320. )
  321. user_permissions = get_permissions(
  322. user.id, request.app.state.config.USER_PERMISSIONS
  323. )
  324. return {
  325. "token": token,
  326. "token_type": "Bearer",
  327. "expires_at": expires_at,
  328. "id": user.id,
  329. "email": user.email,
  330. "name": user.name,
  331. "role": user.role,
  332. "profile_image_url": user.profile_image_url,
  333. "permissions": user_permissions,
  334. }
  335. else:
  336. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  337. ############################
  338. # SignUp
  339. ############################
  340. @router.post("/signup", response_model=SessionUserResponse)
  341. async def signup(request: Request, response: Response, form_data: SignupForm):
  342. if WEBUI_AUTH:
  343. if (
  344. not request.app.state.config.ENABLE_SIGNUP
  345. or not request.app.state.config.ENABLE_LOGIN_FORM
  346. ):
  347. raise HTTPException(
  348. status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.ACCESS_PROHIBITED
  349. )
  350. else:
  351. if Users.get_num_users() != 0:
  352. raise HTTPException(
  353. status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.ACCESS_PROHIBITED
  354. )
  355. if not validate_email_format(form_data.email.lower()):
  356. raise HTTPException(
  357. status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.INVALID_EMAIL_FORMAT
  358. )
  359. if Users.get_user_by_email(form_data.email.lower()):
  360. raise HTTPException(400, detail=ERROR_MESSAGES.EMAIL_TAKEN)
  361. try:
  362. role = (
  363. "admin"
  364. if Users.get_num_users() == 0
  365. else request.app.state.config.DEFAULT_USER_ROLE
  366. )
  367. if Users.get_num_users() == 0:
  368. # Disable signup after the first user is created
  369. request.app.state.config.ENABLE_SIGNUP = False
  370. hashed = get_password_hash(form_data.password)
  371. user = Auths.insert_new_auth(
  372. form_data.email.lower(),
  373. hashed,
  374. form_data.name,
  375. form_data.profile_image_url,
  376. role,
  377. )
  378. if user:
  379. expires_delta = parse_duration(request.app.state.config.JWT_EXPIRES_IN)
  380. expires_at = None
  381. if expires_delta:
  382. expires_at = int(time.time()) + int(expires_delta.total_seconds())
  383. token = create_token(
  384. data={"id": user.id},
  385. expires_delta=expires_delta,
  386. )
  387. datetime_expires_at = (
  388. datetime.datetime.fromtimestamp(expires_at, datetime.timezone.utc)
  389. if expires_at
  390. else None
  391. )
  392. # Set the cookie token
  393. response.set_cookie(
  394. key="token",
  395. value=token,
  396. expires=datetime_expires_at,
  397. httponly=True, # Ensures the cookie is not accessible via JavaScript
  398. samesite=WEBUI_SESSION_COOKIE_SAME_SITE,
  399. secure=WEBUI_SESSION_COOKIE_SECURE,
  400. )
  401. if request.app.state.config.WEBHOOK_URL:
  402. post_webhook(
  403. request.app.state.config.WEBHOOK_URL,
  404. WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  405. {
  406. "action": "signup",
  407. "message": WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  408. "user": user.model_dump_json(exclude_none=True),
  409. },
  410. )
  411. user_permissions = get_permissions(
  412. user.id, request.app.state.config.USER_PERMISSIONS
  413. )
  414. return {
  415. "token": token,
  416. "token_type": "Bearer",
  417. "expires_at": expires_at,
  418. "id": user.id,
  419. "email": user.email,
  420. "name": user.name,
  421. "role": user.role,
  422. "profile_image_url": user.profile_image_url,
  423. "permissions": user_permissions,
  424. }
  425. else:
  426. raise HTTPException(500, detail=ERROR_MESSAGES.CREATE_USER_ERROR)
  427. except Exception as err:
  428. raise HTTPException(500, detail=ERROR_MESSAGES.DEFAULT(err))
  429. @router.get("/signout")
  430. async def signout(request: Request, response: Response):
  431. response.delete_cookie("token")
  432. if OAUTH_PROVIDER_NAME.value == "keycloak" and OAUTH_LOGOUT_URL:
  433. id_token = request.cookies.get("id_token", None)
  434. if id_token:
  435. logout_url = f"{OAUTH_LOGOUT_URL}?id_token_hint={id_token}"
  436. response.delete_cookie("id_token")
  437. return RedirectResponse(url=logout_url)
  438. # Fall back to the default signout
  439. return {"status": True}
  440. ############################
  441. # AddUser
  442. ############################
  443. @router.post("/add", response_model=SigninResponse)
  444. async def add_user(form_data: AddUserForm, user=Depends(get_admin_user)):
  445. if not validate_email_format(form_data.email.lower()):
  446. raise HTTPException(
  447. status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.INVALID_EMAIL_FORMAT
  448. )
  449. if Users.get_user_by_email(form_data.email.lower()):
  450. raise HTTPException(400, detail=ERROR_MESSAGES.EMAIL_TAKEN)
  451. try:
  452. print(form_data)
  453. hashed = get_password_hash(form_data.password)
  454. user = Auths.insert_new_auth(
  455. form_data.email.lower(),
  456. hashed,
  457. form_data.name,
  458. form_data.profile_image_url,
  459. form_data.role,
  460. )
  461. if user:
  462. token = create_token(data={"id": user.id})
  463. return {
  464. "token": token,
  465. "token_type": "Bearer",
  466. "id": user.id,
  467. "email": user.email,
  468. "name": user.name,
  469. "role": user.role,
  470. "profile_image_url": user.profile_image_url,
  471. }
  472. else:
  473. raise HTTPException(500, detail=ERROR_MESSAGES.CREATE_USER_ERROR)
  474. except Exception as err:
  475. raise HTTPException(500, detail=ERROR_MESSAGES.DEFAULT(err))
  476. ############################
  477. # GetAdminDetails
  478. ############################
  479. @router.get("/admin/details")
  480. async def get_admin_details(request: Request, user=Depends(get_current_user)):
  481. if request.app.state.config.SHOW_ADMIN_DETAILS:
  482. admin_email = request.app.state.config.ADMIN_EMAIL
  483. admin_name = None
  484. print(admin_email, admin_name)
  485. if admin_email:
  486. admin = Users.get_user_by_email(admin_email)
  487. if admin:
  488. admin_name = admin.name
  489. else:
  490. admin = Users.get_first_user()
  491. if admin:
  492. admin_email = admin.email
  493. admin_name = admin.name
  494. return {
  495. "name": admin_name,
  496. "email": admin_email,
  497. }
  498. else:
  499. raise HTTPException(400, detail=ERROR_MESSAGES.ACTION_PROHIBITED)
  500. ############################
  501. # ToggleSignUp
  502. ############################
  503. @router.get("/admin/config")
  504. async def get_admin_config(request: Request, user=Depends(get_admin_user)):
  505. return {
  506. "SHOW_ADMIN_DETAILS": request.app.state.config.SHOW_ADMIN_DETAILS,
  507. "ENABLE_SIGNUP": request.app.state.config.ENABLE_SIGNUP,
  508. "ENABLE_API_KEY": request.app.state.config.ENABLE_API_KEY,
  509. "DEFAULT_USER_ROLE": request.app.state.config.DEFAULT_USER_ROLE,
  510. "JWT_EXPIRES_IN": request.app.state.config.JWT_EXPIRES_IN,
  511. "ENABLE_COMMUNITY_SHARING": request.app.state.config.ENABLE_COMMUNITY_SHARING,
  512. "ENABLE_MESSAGE_RATING": request.app.state.config.ENABLE_MESSAGE_RATING,
  513. }
  514. class AdminConfig(BaseModel):
  515. SHOW_ADMIN_DETAILS: bool
  516. ENABLE_SIGNUP: bool
  517. ENABLE_API_KEY: bool
  518. DEFAULT_USER_ROLE: str
  519. JWT_EXPIRES_IN: str
  520. ENABLE_COMMUNITY_SHARING: bool
  521. ENABLE_MESSAGE_RATING: bool
  522. @router.post("/admin/config")
  523. async def update_admin_config(
  524. request: Request, form_data: AdminConfig, user=Depends(get_admin_user)
  525. ):
  526. request.app.state.config.SHOW_ADMIN_DETAILS = form_data.SHOW_ADMIN_DETAILS
  527. request.app.state.config.ENABLE_SIGNUP = form_data.ENABLE_SIGNUP
  528. request.app.state.config.ENABLE_API_KEY = form_data.ENABLE_API_KEY
  529. if form_data.DEFAULT_USER_ROLE in ["pending", "user", "admin"]:
  530. request.app.state.config.DEFAULT_USER_ROLE = form_data.DEFAULT_USER_ROLE
  531. pattern = r"^(-1|0|(-?\d+(\.\d+)?)(ms|s|m|h|d|w))$"
  532. # Check if the input string matches the pattern
  533. if re.match(pattern, form_data.JWT_EXPIRES_IN):
  534. request.app.state.config.JWT_EXPIRES_IN = form_data.JWT_EXPIRES_IN
  535. request.app.state.config.ENABLE_COMMUNITY_SHARING = (
  536. form_data.ENABLE_COMMUNITY_SHARING
  537. )
  538. request.app.state.config.ENABLE_MESSAGE_RATING = form_data.ENABLE_MESSAGE_RATING
  539. return {
  540. "SHOW_ADMIN_DETAILS": request.app.state.config.SHOW_ADMIN_DETAILS,
  541. "ENABLE_SIGNUP": request.app.state.config.ENABLE_SIGNUP,
  542. "ENABLE_API_KEY": request.app.state.config.ENABLE_API_KEY,
  543. "DEFAULT_USER_ROLE": request.app.state.config.DEFAULT_USER_ROLE,
  544. "JWT_EXPIRES_IN": request.app.state.config.JWT_EXPIRES_IN,
  545. "ENABLE_COMMUNITY_SHARING": request.app.state.config.ENABLE_COMMUNITY_SHARING,
  546. "ENABLE_MESSAGE_RATING": request.app.state.config.ENABLE_MESSAGE_RATING,
  547. }
  548. class LdapServerConfig(BaseModel):
  549. label: str
  550. host: str
  551. port: Optional[int] = None
  552. attribute_for_username: str = "uid"
  553. app_dn: str
  554. app_dn_password: str
  555. search_base: str
  556. search_filters: str = ""
  557. use_tls: bool = True
  558. certificate_path: Optional[str] = None
  559. ciphers: Optional[str] = "ALL"
  560. @router.get("/admin/config/ldap/server", response_model=LdapServerConfig)
  561. async def get_ldap_server(request: Request, user=Depends(get_admin_user)):
  562. return {
  563. "label": request.app.state.config.LDAP_SERVER_LABEL,
  564. "host": request.app.state.config.LDAP_SERVER_HOST,
  565. "port": request.app.state.config.LDAP_SERVER_PORT,
  566. "attribute_for_username": request.app.state.config.LDAP_ATTRIBUTE_FOR_USERNAME,
  567. "app_dn": request.app.state.config.LDAP_APP_DN,
  568. "app_dn_password": request.app.state.config.LDAP_APP_PASSWORD,
  569. "search_base": request.app.state.config.LDAP_SEARCH_BASE,
  570. "search_filters": request.app.state.config.LDAP_SEARCH_FILTERS,
  571. "use_tls": request.app.state.config.LDAP_USE_TLS,
  572. "certificate_path": request.app.state.config.LDAP_CA_CERT_FILE,
  573. "ciphers": request.app.state.config.LDAP_CIPHERS,
  574. }
  575. @router.post("/admin/config/ldap/server")
  576. async def update_ldap_server(
  577. request: Request, form_data: LdapServerConfig, user=Depends(get_admin_user)
  578. ):
  579. required_fields = [
  580. "label",
  581. "host",
  582. "attribute_for_username",
  583. "app_dn",
  584. "app_dn_password",
  585. "search_base",
  586. ]
  587. for key in required_fields:
  588. value = getattr(form_data, key)
  589. if not value:
  590. raise HTTPException(400, detail=f"Required field {key} is empty")
  591. if form_data.use_tls and not form_data.certificate_path:
  592. raise HTTPException(
  593. 400, detail="TLS is enabled but certificate file path is missing"
  594. )
  595. request.app.state.config.LDAP_SERVER_LABEL = form_data.label
  596. request.app.state.config.LDAP_SERVER_HOST = form_data.host
  597. request.app.state.config.LDAP_SERVER_PORT = form_data.port
  598. request.app.state.config.LDAP_ATTRIBUTE_FOR_USERNAME = (
  599. form_data.attribute_for_username
  600. )
  601. request.app.state.config.LDAP_APP_DN = form_data.app_dn
  602. request.app.state.config.LDAP_APP_PASSWORD = form_data.app_dn_password
  603. request.app.state.config.LDAP_SEARCH_BASE = form_data.search_base
  604. request.app.state.config.LDAP_SEARCH_FILTERS = form_data.search_filters
  605. request.app.state.config.LDAP_USE_TLS = form_data.use_tls
  606. request.app.state.config.LDAP_CA_CERT_FILE = form_data.certificate_path
  607. request.app.state.config.LDAP_CIPHERS = form_data.ciphers
  608. return {
  609. "label": request.app.state.config.LDAP_SERVER_LABEL,
  610. "host": request.app.state.config.LDAP_SERVER_HOST,
  611. "port": request.app.state.config.LDAP_SERVER_PORT,
  612. "attribute_for_username": request.app.state.config.LDAP_ATTRIBUTE_FOR_USERNAME,
  613. "app_dn": request.app.state.config.LDAP_APP_DN,
  614. "app_dn_password": request.app.state.config.LDAP_APP_PASSWORD,
  615. "search_base": request.app.state.config.LDAP_SEARCH_BASE,
  616. "search_filters": request.app.state.config.LDAP_SEARCH_FILTERS,
  617. "use_tls": request.app.state.config.LDAP_USE_TLS,
  618. "certificate_path": request.app.state.config.LDAP_CA_CERT_FILE,
  619. "ciphers": request.app.state.config.LDAP_CIPHERS,
  620. }
  621. @router.get("/admin/config/ldap")
  622. async def get_ldap_config(request: Request, user=Depends(get_admin_user)):
  623. return {"ENABLE_LDAP": request.app.state.config.ENABLE_LDAP}
  624. class LdapConfigForm(BaseModel):
  625. enable_ldap: Optional[bool] = None
  626. @router.post("/admin/config/ldap")
  627. async def update_ldap_config(
  628. request: Request, form_data: LdapConfigForm, user=Depends(get_admin_user)
  629. ):
  630. request.app.state.config.ENABLE_LDAP = form_data.enable_ldap
  631. return {"ENABLE_LDAP": request.app.state.config.ENABLE_LDAP}
  632. ############################
  633. # API Key
  634. ############################
  635. # create api key
  636. @router.post("/api_key", response_model=ApiKey)
  637. async def generate_api_key(request: Request, user=Depends(get_current_user)):
  638. if not request.app.state.config.ENABLE_API_KEY:
  639. raise HTTPException(
  640. status.HTTP_403_FORBIDDEN,
  641. detail=ERROR_MESSAGES.API_KEY_CREATION_NOT_ALLOWED,
  642. )
  643. api_key = create_api_key()
  644. success = Users.update_user_api_key_by_id(user.id, api_key)
  645. if success:
  646. return {
  647. "api_key": api_key,
  648. }
  649. else:
  650. raise HTTPException(500, detail=ERROR_MESSAGES.CREATE_API_KEY_ERROR)
  651. # delete api key
  652. @router.delete("/api_key", response_model=bool)
  653. async def delete_api_key(user=Depends(get_current_user)):
  654. success = Users.update_user_api_key_by_id(user.id, None)
  655. return success
  656. # get api key
  657. @router.get("/api_key", response_model=ApiKey)
  658. async def get_api_key(user=Depends(get_current_user)):
  659. api_key = Users.get_user_api_key_by_id(user.id)
  660. if api_key:
  661. return {
  662. "api_key": api_key,
  663. }
  664. else:
  665. raise HTTPException(404, detail=ERROR_MESSAGES.API_KEY_NOT_FOUND)