auths.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785
  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 Response
  31. from pydantic import BaseModel
  32. from open_webui.utils.misc import parse_duration, validate_email_format
  33. from open_webui.utils.utils import (
  34. create_api_key,
  35. create_token,
  36. get_admin_user,
  37. get_verified_user,
  38. get_current_user,
  39. get_password_hash,
  40. )
  41. from open_webui.utils.webhook import post_webhook
  42. from open_webui.utils.access_control import get_permissions
  43. from typing import Optional, List
  44. from ssl import CERT_REQUIRED, PROTOCOL_TLS
  45. from ldap3 import Server, Connection, ALL, Tls
  46. from ldap3.utils.conv import escape_filter_chars
  47. router = APIRouter()
  48. log = logging.getLogger(__name__)
  49. log.setLevel(SRC_LOG_LEVELS["MAIN"])
  50. ############################
  51. # GetSessionUser
  52. ############################
  53. class SessionUserResponse(Token, UserResponse):
  54. expires_at: Optional[int] = None
  55. permissions: Optional[dict] = None
  56. @router.get("/", response_model=SessionUserResponse)
  57. async def get_session_user(
  58. request: Request, response: Response, user=Depends(get_current_user)
  59. ):
  60. expires_delta = parse_duration(request.app.state.config.JWT_EXPIRES_IN)
  61. expires_at = None
  62. if expires_delta:
  63. expires_at = int(time.time()) + int(expires_delta.total_seconds())
  64. token = create_token(
  65. data={"id": user.id},
  66. expires_delta=expires_delta,
  67. )
  68. datetime_expires_at = (
  69. datetime.datetime.fromtimestamp(expires_at, datetime.timezone.utc)
  70. if expires_at
  71. else None
  72. )
  73. # Set the cookie token
  74. response.set_cookie(
  75. key="token",
  76. value=token,
  77. expires=datetime_expires_at,
  78. httponly=True, # Ensures the cookie is not accessible via JavaScript
  79. samesite=WEBUI_SESSION_COOKIE_SAME_SITE,
  80. secure=WEBUI_SESSION_COOKIE_SECURE,
  81. )
  82. user_permissions = get_permissions(
  83. user.id, request.app.state.config.USER_PERMISSIONS
  84. )
  85. return {
  86. "token": token,
  87. "token_type": "Bearer",
  88. "expires_at": expires_at,
  89. "id": user.id,
  90. "email": user.email,
  91. "name": user.name,
  92. "role": user.role,
  93. "profile_image_url": user.profile_image_url,
  94. "permissions": user_permissions,
  95. }
  96. ############################
  97. # Update Profile
  98. ############################
  99. @router.post("/update/profile", response_model=UserResponse)
  100. async def update_profile(
  101. form_data: UpdateProfileForm, session_user=Depends(get_verified_user)
  102. ):
  103. if session_user:
  104. user = Users.update_user_by_id(
  105. session_user.id,
  106. {"profile_image_url": form_data.profile_image_url, "name": form_data.name},
  107. )
  108. if user:
  109. return user
  110. else:
  111. raise HTTPException(400, detail=ERROR_MESSAGES.DEFAULT())
  112. else:
  113. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  114. ############################
  115. # Update Password
  116. ############################
  117. @router.post("/update/password", response_model=bool)
  118. async def update_password(
  119. form_data: UpdatePasswordForm, session_user=Depends(get_current_user)
  120. ):
  121. if WEBUI_AUTH_TRUSTED_EMAIL_HEADER:
  122. raise HTTPException(400, detail=ERROR_MESSAGES.ACTION_PROHIBITED)
  123. if session_user:
  124. user = Auths.authenticate_user(session_user.email, form_data.password)
  125. if user:
  126. hashed = get_password_hash(form_data.new_password)
  127. return Auths.update_user_password_by_id(user.id, hashed)
  128. else:
  129. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_PASSWORD)
  130. else:
  131. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  132. ############################
  133. # LDAP Authentication
  134. ############################
  135. @router.post("/ldap", response_model=SigninResponse)
  136. async def ldap_auth(request: Request, response: Response, form_data: LdapForm):
  137. ENABLE_LDAP = request.app.state.config.ENABLE_LDAP
  138. LDAP_SERVER_LABEL = request.app.state.config.LDAP_SERVER_LABEL
  139. LDAP_SERVER_HOST = request.app.state.config.LDAP_SERVER_HOST
  140. LDAP_SERVER_PORT = request.app.state.config.LDAP_SERVER_PORT
  141. LDAP_ATTRIBUTE_FOR_USERNAME = request.app.state.config.LDAP_ATTRIBUTE_FOR_USERNAME
  142. LDAP_SEARCH_BASE = request.app.state.config.LDAP_SEARCH_BASE
  143. LDAP_SEARCH_FILTERS = request.app.state.config.LDAP_SEARCH_FILTERS
  144. LDAP_APP_DN = request.app.state.config.LDAP_APP_DN
  145. LDAP_APP_PASSWORD = request.app.state.config.LDAP_APP_PASSWORD
  146. LDAP_USE_TLS = request.app.state.config.LDAP_USE_TLS
  147. LDAP_CA_CERT_FILE = request.app.state.config.LDAP_CA_CERT_FILE
  148. LDAP_CIPHERS = (
  149. request.app.state.config.LDAP_CIPHERS
  150. if request.app.state.config.LDAP_CIPHERS
  151. else "ALL"
  152. )
  153. if not ENABLE_LDAP:
  154. raise HTTPException(400, detail="LDAP authentication is not enabled")
  155. try:
  156. tls = Tls(
  157. validate=CERT_REQUIRED,
  158. version=PROTOCOL_TLS,
  159. ca_certs_file=LDAP_CA_CERT_FILE,
  160. ciphers=LDAP_CIPHERS,
  161. )
  162. except Exception as e:
  163. log.error(f"An error occurred on TLS: {str(e)}")
  164. raise HTTPException(400, detail=str(e))
  165. try:
  166. server = Server(
  167. host=LDAP_SERVER_HOST,
  168. port=LDAP_SERVER_PORT,
  169. get_info=ALL,
  170. use_ssl=LDAP_USE_TLS,
  171. tls=tls,
  172. )
  173. connection_app = Connection(
  174. server,
  175. LDAP_APP_DN,
  176. LDAP_APP_PASSWORD,
  177. auto_bind="NONE",
  178. authentication="SIMPLE",
  179. )
  180. if not connection_app.bind():
  181. raise HTTPException(400, detail="Application account bind failed")
  182. search_success = connection_app.search(
  183. search_base=LDAP_SEARCH_BASE,
  184. search_filter=f"(&({LDAP_ATTRIBUTE_FOR_USERNAME}={escape_filter_chars(form_data.user.lower())}){LDAP_SEARCH_FILTERS})",
  185. attributes=[f"{LDAP_ATTRIBUTE_FOR_USERNAME}", "mail", "cn"],
  186. )
  187. if not search_success:
  188. raise HTTPException(400, detail="User not found in the LDAP server")
  189. entry = connection_app.entries[0]
  190. username = str(entry[f"{LDAP_ATTRIBUTE_FOR_USERNAME}"]).lower()
  191. mail = str(entry["mail"])
  192. cn = str(entry["cn"])
  193. user_dn = entry.entry_dn
  194. if username == form_data.user.lower():
  195. connection_user = Connection(
  196. server,
  197. user_dn,
  198. form_data.password,
  199. auto_bind="NONE",
  200. authentication="SIMPLE",
  201. )
  202. if not connection_user.bind():
  203. raise HTTPException(400, f"Authentication failed for {form_data.user}")
  204. user = Users.get_user_by_email(mail)
  205. if not user:
  206. try:
  207. role = (
  208. "admin"
  209. if Users.get_num_users() == 0
  210. else request.app.state.config.DEFAULT_USER_ROLE
  211. )
  212. user = Auths.insert_new_auth(
  213. mail,
  214. str(uuid.uuid4()),
  215. cn,
  216. None,
  217. 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(response: Response):
  431. response.delete_cookie("token")
  432. return {"status": True}
  433. ############################
  434. # AddUser
  435. ############################
  436. @router.post("/add", response_model=SigninResponse)
  437. async def add_user(form_data: AddUserForm, user=Depends(get_admin_user)):
  438. if not validate_email_format(form_data.email.lower()):
  439. raise HTTPException(
  440. status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.INVALID_EMAIL_FORMAT
  441. )
  442. if Users.get_user_by_email(form_data.email.lower()):
  443. raise HTTPException(400, detail=ERROR_MESSAGES.EMAIL_TAKEN)
  444. try:
  445. print(form_data)
  446. hashed = get_password_hash(form_data.password)
  447. user = Auths.insert_new_auth(
  448. form_data.email.lower(),
  449. hashed,
  450. form_data.name,
  451. form_data.profile_image_url,
  452. form_data.role,
  453. )
  454. if user:
  455. token = create_token(data={"id": user.id})
  456. return {
  457. "token": token,
  458. "token_type": "Bearer",
  459. "id": user.id,
  460. "email": user.email,
  461. "name": user.name,
  462. "role": user.role,
  463. "profile_image_url": user.profile_image_url,
  464. }
  465. else:
  466. raise HTTPException(500, detail=ERROR_MESSAGES.CREATE_USER_ERROR)
  467. except Exception as err:
  468. raise HTTPException(500, detail=ERROR_MESSAGES.DEFAULT(err))
  469. ############################
  470. # GetAdminDetails
  471. ############################
  472. @router.get("/admin/details")
  473. async def get_admin_details(request: Request, user=Depends(get_current_user)):
  474. if request.app.state.config.SHOW_ADMIN_DETAILS:
  475. admin_email = request.app.state.config.ADMIN_EMAIL
  476. admin_name = None
  477. print(admin_email, admin_name)
  478. if admin_email:
  479. admin = Users.get_user_by_email(admin_email)
  480. if admin:
  481. admin_name = admin.name
  482. else:
  483. admin = Users.get_first_user()
  484. if admin:
  485. admin_email = admin.email
  486. admin_name = admin.name
  487. return {
  488. "name": admin_name,
  489. "email": admin_email,
  490. }
  491. else:
  492. raise HTTPException(400, detail=ERROR_MESSAGES.ACTION_PROHIBITED)
  493. ############################
  494. # ToggleSignUp
  495. ############################
  496. @router.get("/admin/config")
  497. async def get_admin_config(request: Request, user=Depends(get_admin_user)):
  498. return {
  499. "SHOW_ADMIN_DETAILS": request.app.state.config.SHOW_ADMIN_DETAILS,
  500. "ENABLE_SIGNUP": request.app.state.config.ENABLE_SIGNUP,
  501. "ENABLE_API_KEY": request.app.state.config.ENABLE_API_KEY,
  502. "DEFAULT_USER_ROLE": request.app.state.config.DEFAULT_USER_ROLE,
  503. "JWT_EXPIRES_IN": request.app.state.config.JWT_EXPIRES_IN,
  504. "ENABLE_COMMUNITY_SHARING": request.app.state.config.ENABLE_COMMUNITY_SHARING,
  505. "ENABLE_MESSAGE_RATING": request.app.state.config.ENABLE_MESSAGE_RATING,
  506. }
  507. class AdminConfig(BaseModel):
  508. SHOW_ADMIN_DETAILS: bool
  509. ENABLE_SIGNUP: bool
  510. ENABLE_API_KEY: bool
  511. DEFAULT_USER_ROLE: str
  512. JWT_EXPIRES_IN: str
  513. ENABLE_COMMUNITY_SHARING: bool
  514. ENABLE_MESSAGE_RATING: bool
  515. @router.post("/admin/config")
  516. async def update_admin_config(
  517. request: Request, form_data: AdminConfig, user=Depends(get_admin_user)
  518. ):
  519. request.app.state.config.SHOW_ADMIN_DETAILS = form_data.SHOW_ADMIN_DETAILS
  520. request.app.state.config.ENABLE_SIGNUP = form_data.ENABLE_SIGNUP
  521. request.app.state.config.ENABLE_API_KEY = form_data.ENABLE_API_KEY
  522. if form_data.DEFAULT_USER_ROLE in ["pending", "user", "admin"]:
  523. request.app.state.config.DEFAULT_USER_ROLE = form_data.DEFAULT_USER_ROLE
  524. pattern = r"^(-1|0|(-?\d+(\.\d+)?)(ms|s|m|h|d|w))$"
  525. # Check if the input string matches the pattern
  526. if re.match(pattern, form_data.JWT_EXPIRES_IN):
  527. request.app.state.config.JWT_EXPIRES_IN = form_data.JWT_EXPIRES_IN
  528. request.app.state.config.ENABLE_COMMUNITY_SHARING = (
  529. form_data.ENABLE_COMMUNITY_SHARING
  530. )
  531. request.app.state.config.ENABLE_MESSAGE_RATING = form_data.ENABLE_MESSAGE_RATING
  532. return {
  533. "SHOW_ADMIN_DETAILS": request.app.state.config.SHOW_ADMIN_DETAILS,
  534. "ENABLE_SIGNUP": request.app.state.config.ENABLE_SIGNUP,
  535. "ENABLE_API_KEY": request.app.state.config.ENABLE_API_KEY,
  536. "DEFAULT_USER_ROLE": request.app.state.config.DEFAULT_USER_ROLE,
  537. "JWT_EXPIRES_IN": request.app.state.config.JWT_EXPIRES_IN,
  538. "ENABLE_COMMUNITY_SHARING": request.app.state.config.ENABLE_COMMUNITY_SHARING,
  539. "ENABLE_MESSAGE_RATING": request.app.state.config.ENABLE_MESSAGE_RATING,
  540. }
  541. class LdapServerConfig(BaseModel):
  542. label: str
  543. host: str
  544. port: Optional[int] = None
  545. attribute_for_username: str = "uid"
  546. app_dn: str
  547. app_dn_password: str
  548. search_base: str
  549. search_filters: str = ""
  550. use_tls: bool = True
  551. certificate_path: Optional[str] = None
  552. ciphers: Optional[str] = "ALL"
  553. @router.get("/admin/config/ldap/server", response_model=LdapServerConfig)
  554. async def get_ldap_server(request: Request, user=Depends(get_admin_user)):
  555. return {
  556. "label": request.app.state.config.LDAP_SERVER_LABEL,
  557. "host": request.app.state.config.LDAP_SERVER_HOST,
  558. "port": request.app.state.config.LDAP_SERVER_PORT,
  559. "attribute_for_username": request.app.state.config.LDAP_ATTRIBUTE_FOR_USERNAME,
  560. "app_dn": request.app.state.config.LDAP_APP_DN,
  561. "app_dn_password": request.app.state.config.LDAP_APP_PASSWORD,
  562. "search_base": request.app.state.config.LDAP_SEARCH_BASE,
  563. "search_filters": request.app.state.config.LDAP_SEARCH_FILTERS,
  564. "use_tls": request.app.state.config.LDAP_USE_TLS,
  565. "certificate_path": request.app.state.config.LDAP_CA_CERT_FILE,
  566. "ciphers": request.app.state.config.LDAP_CIPHERS,
  567. }
  568. @router.post("/admin/config/ldap/server")
  569. async def update_ldap_server(
  570. request: Request, form_data: LdapServerConfig, user=Depends(get_admin_user)
  571. ):
  572. required_fields = [
  573. "label",
  574. "host",
  575. "attribute_for_username",
  576. "app_dn",
  577. "app_dn_password",
  578. "search_base",
  579. ]
  580. for key in required_fields:
  581. value = getattr(form_data, key)
  582. if not value:
  583. raise HTTPException(400, detail=f"Required field {key} is empty")
  584. if form_data.use_tls and not form_data.certificate_path:
  585. raise HTTPException(
  586. 400, detail="TLS is enabled but certificate file path is missing"
  587. )
  588. request.app.state.config.LDAP_SERVER_LABEL = form_data.label
  589. request.app.state.config.LDAP_SERVER_HOST = form_data.host
  590. request.app.state.config.LDAP_SERVER_PORT = form_data.port
  591. request.app.state.config.LDAP_ATTRIBUTE_FOR_USERNAME = (
  592. form_data.attribute_for_username
  593. )
  594. request.app.state.config.LDAP_APP_DN = form_data.app_dn
  595. request.app.state.config.LDAP_APP_PASSWORD = form_data.app_dn_password
  596. request.app.state.config.LDAP_SEARCH_BASE = form_data.search_base
  597. request.app.state.config.LDAP_SEARCH_FILTERS = form_data.search_filters
  598. request.app.state.config.LDAP_USE_TLS = form_data.use_tls
  599. request.app.state.config.LDAP_CA_CERT_FILE = form_data.certificate_path
  600. request.app.state.config.LDAP_CIPHERS = form_data.ciphers
  601. return {
  602. "label": request.app.state.config.LDAP_SERVER_LABEL,
  603. "host": request.app.state.config.LDAP_SERVER_HOST,
  604. "port": request.app.state.config.LDAP_SERVER_PORT,
  605. "attribute_for_username": request.app.state.config.LDAP_ATTRIBUTE_FOR_USERNAME,
  606. "app_dn": request.app.state.config.LDAP_APP_DN,
  607. "app_dn_password": request.app.state.config.LDAP_APP_PASSWORD,
  608. "search_base": request.app.state.config.LDAP_SEARCH_BASE,
  609. "search_filters": request.app.state.config.LDAP_SEARCH_FILTERS,
  610. "use_tls": request.app.state.config.LDAP_USE_TLS,
  611. "certificate_path": request.app.state.config.LDAP_CA_CERT_FILE,
  612. "ciphers": request.app.state.config.LDAP_CIPHERS,
  613. }
  614. @router.get("/admin/config/ldap")
  615. async def get_ldap_config(request: Request, user=Depends(get_admin_user)):
  616. return {"ENABLE_LDAP": request.app.state.config.ENABLE_LDAP}
  617. class LdapConfigForm(BaseModel):
  618. enable_ldap: Optional[bool] = None
  619. @router.post("/admin/config/ldap")
  620. async def update_ldap_config(
  621. request: Request, form_data: LdapConfigForm, user=Depends(get_admin_user)
  622. ):
  623. request.app.state.config.ENABLE_LDAP = form_data.enable_ldap
  624. return {"ENABLE_LDAP": request.app.state.config.ENABLE_LDAP}
  625. ############################
  626. # API Key
  627. ############################
  628. # create api key
  629. @router.post("/api_key", response_model=ApiKey)
  630. async def generate_api_key(request: Request, user=Depends(get_current_user)):
  631. if not request.app.state.config.ENABLE_API_KEY:
  632. raise HTTPException(
  633. status.HTTP_403_FORBIDDEN,
  634. detail=ERROR_MESSAGES.API_KEY_CREATION_NOT_ALLOWED,
  635. )
  636. api_key = create_api_key()
  637. success = Users.update_user_api_key_by_id(user.id, api_key)
  638. if success:
  639. return {
  640. "api_key": api_key,
  641. }
  642. else:
  643. raise HTTPException(500, detail=ERROR_MESSAGES.CREATE_API_KEY_ERROR)
  644. # delete api key
  645. @router.delete("/api_key", response_model=bool)
  646. async def delete_api_key(user=Depends(get_current_user)):
  647. success = Users.update_user_api_key_by_id(user.id, None)
  648. return success
  649. # get api key
  650. @router.get("/api_key", response_model=ApiKey)
  651. async def get_api_key(user=Depends(get_current_user)):
  652. api_key = Users.get_user_api_key_by_id(user.id)
  653. if api_key:
  654. return {
  655. "api_key": api_key,
  656. }
  657. else:
  658. raise HTTPException(404, detail=ERROR_MESSAGES.API_KEY_NOT_FOUND)