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. email=mail,
  214. password=str(uuid.uuid4()),
  215. name=cn,
  216. role=role
  217. )
  218. if not user:
  219. raise HTTPException(
  220. 500, detail=ERROR_MESSAGES.CREATE_USER_ERROR
  221. )
  222. except HTTPException:
  223. raise
  224. except Exception as err:
  225. raise HTTPException(500, detail=ERROR_MESSAGES.DEFAULT(err))
  226. user = Auths.authenticate_user_by_trusted_header(mail)
  227. if user:
  228. token = create_token(
  229. data={"id": user.id},
  230. expires_delta=parse_duration(
  231. request.app.state.config.JWT_EXPIRES_IN
  232. ),
  233. )
  234. # Set the cookie token
  235. response.set_cookie(
  236. key="token",
  237. value=token,
  238. httponly=True, # Ensures the cookie is not accessible via JavaScript
  239. )
  240. return {
  241. "token": token,
  242. "token_type": "Bearer",
  243. "id": user.id,
  244. "email": user.email,
  245. "name": user.name,
  246. "role": user.role,
  247. "profile_image_url": user.profile_image_url,
  248. }
  249. else:
  250. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  251. else:
  252. raise HTTPException(
  253. 400,
  254. f"User {form_data.user} does not match the record. Search result: {str(entry[f'{LDAP_ATTRIBUTE_FOR_USERNAME}'])}",
  255. )
  256. except Exception as e:
  257. raise HTTPException(400, detail=str(e))
  258. ############################
  259. # SignIn
  260. ############################
  261. @router.post("/signin", response_model=SessionUserResponse)
  262. async def signin(request: Request, response: Response, form_data: SigninForm):
  263. if WEBUI_AUTH_TRUSTED_EMAIL_HEADER:
  264. if WEBUI_AUTH_TRUSTED_EMAIL_HEADER not in request.headers:
  265. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_TRUSTED_HEADER)
  266. trusted_email = request.headers[WEBUI_AUTH_TRUSTED_EMAIL_HEADER].lower()
  267. trusted_name = trusted_email
  268. if WEBUI_AUTH_TRUSTED_NAME_HEADER:
  269. trusted_name = request.headers.get(
  270. WEBUI_AUTH_TRUSTED_NAME_HEADER, trusted_email
  271. )
  272. if not Users.get_user_by_email(trusted_email.lower()):
  273. await signup(
  274. request,
  275. response,
  276. SignupForm(
  277. email=trusted_email, password=str(uuid.uuid4()), name=trusted_name
  278. ),
  279. )
  280. user = Auths.authenticate_user_by_trusted_header(trusted_email)
  281. elif WEBUI_AUTH == False:
  282. admin_email = "admin@localhost"
  283. admin_password = "admin"
  284. if Users.get_user_by_email(admin_email.lower()):
  285. user = Auths.authenticate_user(admin_email.lower(), admin_password)
  286. else:
  287. if Users.get_num_users() != 0:
  288. raise HTTPException(400, detail=ERROR_MESSAGES.EXISTING_USERS)
  289. await signup(
  290. request,
  291. response,
  292. SignupForm(email=admin_email, password=admin_password, name="User"),
  293. )
  294. user = Auths.authenticate_user(admin_email.lower(), admin_password)
  295. else:
  296. user = Auths.authenticate_user(form_data.email.lower(), form_data.password)
  297. if user:
  298. expires_delta = parse_duration(request.app.state.config.JWT_EXPIRES_IN)
  299. expires_at = None
  300. if expires_delta:
  301. expires_at = int(time.time()) + int(expires_delta.total_seconds())
  302. token = create_token(
  303. data={"id": user.id},
  304. expires_delta=expires_delta,
  305. )
  306. datetime_expires_at = (
  307. datetime.datetime.fromtimestamp(expires_at, datetime.timezone.utc)
  308. if expires_at
  309. else None
  310. )
  311. # Set the cookie token
  312. response.set_cookie(
  313. key="token",
  314. value=token,
  315. expires=datetime_expires_at,
  316. httponly=True, # Ensures the cookie is not accessible via JavaScript
  317. samesite=WEBUI_SESSION_COOKIE_SAME_SITE,
  318. secure=WEBUI_SESSION_COOKIE_SECURE,
  319. )
  320. user_permissions = get_permissions(
  321. user.id, request.app.state.config.USER_PERMISSIONS
  322. )
  323. return {
  324. "token": token,
  325. "token_type": "Bearer",
  326. "expires_at": expires_at,
  327. "id": user.id,
  328. "email": user.email,
  329. "name": user.name,
  330. "role": user.role,
  331. "profile_image_url": user.profile_image_url,
  332. "permissions": user_permissions,
  333. }
  334. else:
  335. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  336. ############################
  337. # SignUp
  338. ############################
  339. @router.post("/signup", response_model=SessionUserResponse)
  340. async def signup(request: Request, response: Response, form_data: SignupForm):
  341. if WEBUI_AUTH:
  342. if (
  343. not request.app.state.config.ENABLE_SIGNUP
  344. or not request.app.state.config.ENABLE_LOGIN_FORM
  345. ):
  346. raise HTTPException(
  347. status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.ACCESS_PROHIBITED
  348. )
  349. else:
  350. if Users.get_num_users() != 0:
  351. raise HTTPException(
  352. status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.ACCESS_PROHIBITED
  353. )
  354. if not validate_email_format(form_data.email.lower()):
  355. raise HTTPException(
  356. status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.INVALID_EMAIL_FORMAT
  357. )
  358. if Users.get_user_by_email(form_data.email.lower()):
  359. raise HTTPException(400, detail=ERROR_MESSAGES.EMAIL_TAKEN)
  360. try:
  361. role = (
  362. "admin"
  363. if Users.get_num_users() == 0
  364. else request.app.state.config.DEFAULT_USER_ROLE
  365. )
  366. if Users.get_num_users() == 0:
  367. # Disable signup after the first user is created
  368. request.app.state.config.ENABLE_SIGNUP = False
  369. hashed = get_password_hash(form_data.password)
  370. user = Auths.insert_new_auth(
  371. form_data.email.lower(),
  372. hashed,
  373. form_data.name,
  374. form_data.profile_image_url,
  375. role,
  376. )
  377. if user:
  378. expires_delta = parse_duration(request.app.state.config.JWT_EXPIRES_IN)
  379. expires_at = None
  380. if expires_delta:
  381. expires_at = int(time.time()) + int(expires_delta.total_seconds())
  382. token = create_token(
  383. data={"id": user.id},
  384. expires_delta=expires_delta,
  385. )
  386. datetime_expires_at = (
  387. datetime.datetime.fromtimestamp(expires_at, datetime.timezone.utc)
  388. if expires_at
  389. else None
  390. )
  391. # Set the cookie token
  392. response.set_cookie(
  393. key="token",
  394. value=token,
  395. expires=datetime_expires_at,
  396. httponly=True, # Ensures the cookie is not accessible via JavaScript
  397. samesite=WEBUI_SESSION_COOKIE_SAME_SITE,
  398. secure=WEBUI_SESSION_COOKIE_SECURE,
  399. )
  400. if request.app.state.config.WEBHOOK_URL:
  401. post_webhook(
  402. request.app.state.config.WEBHOOK_URL,
  403. WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  404. {
  405. "action": "signup",
  406. "message": WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  407. "user": user.model_dump_json(exclude_none=True),
  408. },
  409. )
  410. user_permissions = get_permissions(
  411. user.id, request.app.state.config.USER_PERMISSIONS
  412. )
  413. return {
  414. "token": token,
  415. "token_type": "Bearer",
  416. "expires_at": expires_at,
  417. "id": user.id,
  418. "email": user.email,
  419. "name": user.name,
  420. "role": user.role,
  421. "profile_image_url": user.profile_image_url,
  422. "permissions": user_permissions,
  423. }
  424. else:
  425. raise HTTPException(500, detail=ERROR_MESSAGES.CREATE_USER_ERROR)
  426. except Exception as err:
  427. raise HTTPException(500, detail=ERROR_MESSAGES.DEFAULT(err))
  428. @router.get("/signout")
  429. async def signout(response: Response):
  430. response.delete_cookie("token")
  431. return {"status": True}
  432. ############################
  433. # AddUser
  434. ############################
  435. @router.post("/add", response_model=SigninResponse)
  436. async def add_user(form_data: AddUserForm, user=Depends(get_admin_user)):
  437. if not validate_email_format(form_data.email.lower()):
  438. raise HTTPException(
  439. status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.INVALID_EMAIL_FORMAT
  440. )
  441. if Users.get_user_by_email(form_data.email.lower()):
  442. raise HTTPException(400, detail=ERROR_MESSAGES.EMAIL_TAKEN)
  443. try:
  444. print(form_data)
  445. hashed = get_password_hash(form_data.password)
  446. user = Auths.insert_new_auth(
  447. form_data.email.lower(),
  448. hashed,
  449. form_data.name,
  450. form_data.profile_image_url,
  451. form_data.role,
  452. )
  453. if user:
  454. token = create_token(data={"id": user.id})
  455. return {
  456. "token": token,
  457. "token_type": "Bearer",
  458. "id": user.id,
  459. "email": user.email,
  460. "name": user.name,
  461. "role": user.role,
  462. "profile_image_url": user.profile_image_url,
  463. }
  464. else:
  465. raise HTTPException(500, detail=ERROR_MESSAGES.CREATE_USER_ERROR)
  466. except Exception as err:
  467. raise HTTPException(500, detail=ERROR_MESSAGES.DEFAULT(err))
  468. ############################
  469. # GetAdminDetails
  470. ############################
  471. @router.get("/admin/details")
  472. async def get_admin_details(request: Request, user=Depends(get_current_user)):
  473. if request.app.state.config.SHOW_ADMIN_DETAILS:
  474. admin_email = request.app.state.config.ADMIN_EMAIL
  475. admin_name = None
  476. print(admin_email, admin_name)
  477. if admin_email:
  478. admin = Users.get_user_by_email(admin_email)
  479. if admin:
  480. admin_name = admin.name
  481. else:
  482. admin = Users.get_first_user()
  483. if admin:
  484. admin_email = admin.email
  485. admin_name = admin.name
  486. return {
  487. "name": admin_name,
  488. "email": admin_email,
  489. }
  490. else:
  491. raise HTTPException(400, detail=ERROR_MESSAGES.ACTION_PROHIBITED)
  492. ############################
  493. # ToggleSignUp
  494. ############################
  495. @router.get("/admin/config")
  496. async def get_admin_config(request: Request, user=Depends(get_admin_user)):
  497. return {
  498. "SHOW_ADMIN_DETAILS": request.app.state.config.SHOW_ADMIN_DETAILS,
  499. "ENABLE_SIGNUP": request.app.state.config.ENABLE_SIGNUP,
  500. "ENABLE_API_KEY": request.app.state.config.ENABLE_API_KEY,
  501. "DEFAULT_USER_ROLE": request.app.state.config.DEFAULT_USER_ROLE,
  502. "JWT_EXPIRES_IN": request.app.state.config.JWT_EXPIRES_IN,
  503. "ENABLE_COMMUNITY_SHARING": request.app.state.config.ENABLE_COMMUNITY_SHARING,
  504. "ENABLE_MESSAGE_RATING": request.app.state.config.ENABLE_MESSAGE_RATING,
  505. }
  506. class AdminConfig(BaseModel):
  507. SHOW_ADMIN_DETAILS: bool
  508. ENABLE_SIGNUP: bool
  509. ENABLE_API_KEY: bool
  510. DEFAULT_USER_ROLE: str
  511. JWT_EXPIRES_IN: str
  512. ENABLE_COMMUNITY_SHARING: bool
  513. ENABLE_MESSAGE_RATING: bool
  514. @router.post("/admin/config")
  515. async def update_admin_config(
  516. request: Request, form_data: AdminConfig, user=Depends(get_admin_user)
  517. ):
  518. request.app.state.config.SHOW_ADMIN_DETAILS = form_data.SHOW_ADMIN_DETAILS
  519. request.app.state.config.ENABLE_SIGNUP = form_data.ENABLE_SIGNUP
  520. request.app.state.config.ENABLE_API_KEY = form_data.ENABLE_API_KEY
  521. if form_data.DEFAULT_USER_ROLE in ["pending", "user", "admin"]:
  522. request.app.state.config.DEFAULT_USER_ROLE = form_data.DEFAULT_USER_ROLE
  523. pattern = r"^(-1|0|(-?\d+(\.\d+)?)(ms|s|m|h|d|w))$"
  524. # Check if the input string matches the pattern
  525. if re.match(pattern, form_data.JWT_EXPIRES_IN):
  526. request.app.state.config.JWT_EXPIRES_IN = form_data.JWT_EXPIRES_IN
  527. request.app.state.config.ENABLE_COMMUNITY_SHARING = (
  528. form_data.ENABLE_COMMUNITY_SHARING
  529. )
  530. request.app.state.config.ENABLE_MESSAGE_RATING = form_data.ENABLE_MESSAGE_RATING
  531. return {
  532. "SHOW_ADMIN_DETAILS": request.app.state.config.SHOW_ADMIN_DETAILS,
  533. "ENABLE_SIGNUP": request.app.state.config.ENABLE_SIGNUP,
  534. "ENABLE_API_KEY": request.app.state.config.ENABLE_API_KEY,
  535. "DEFAULT_USER_ROLE": request.app.state.config.DEFAULT_USER_ROLE,
  536. "JWT_EXPIRES_IN": request.app.state.config.JWT_EXPIRES_IN,
  537. "ENABLE_COMMUNITY_SHARING": request.app.state.config.ENABLE_COMMUNITY_SHARING,
  538. "ENABLE_MESSAGE_RATING": request.app.state.config.ENABLE_MESSAGE_RATING,
  539. }
  540. class LdapServerConfig(BaseModel):
  541. label: str
  542. host: str
  543. port: Optional[int] = None
  544. attribute_for_username: str = "uid"
  545. app_dn: str
  546. app_dn_password: str
  547. search_base: str
  548. search_filters: str = ""
  549. use_tls: bool = True
  550. certificate_path: Optional[str] = None
  551. ciphers: Optional[str] = "ALL"
  552. @router.get("/admin/config/ldap/server", response_model=LdapServerConfig)
  553. async def get_ldap_server(request: Request, user=Depends(get_admin_user)):
  554. return {
  555. "label": request.app.state.config.LDAP_SERVER_LABEL,
  556. "host": request.app.state.config.LDAP_SERVER_HOST,
  557. "port": request.app.state.config.LDAP_SERVER_PORT,
  558. "attribute_for_username": request.app.state.config.LDAP_ATTRIBUTE_FOR_USERNAME,
  559. "app_dn": request.app.state.config.LDAP_APP_DN,
  560. "app_dn_password": request.app.state.config.LDAP_APP_PASSWORD,
  561. "search_base": request.app.state.config.LDAP_SEARCH_BASE,
  562. "search_filters": request.app.state.config.LDAP_SEARCH_FILTERS,
  563. "use_tls": request.app.state.config.LDAP_USE_TLS,
  564. "certificate_path": request.app.state.config.LDAP_CA_CERT_FILE,
  565. "ciphers": request.app.state.config.LDAP_CIPHERS,
  566. }
  567. @router.post("/admin/config/ldap/server")
  568. async def update_ldap_server(
  569. request: Request, form_data: LdapServerConfig, user=Depends(get_admin_user)
  570. ):
  571. required_fields = [
  572. "label",
  573. "host",
  574. "attribute_for_username",
  575. "app_dn",
  576. "app_dn_password",
  577. "search_base",
  578. ]
  579. for key in required_fields:
  580. value = getattr(form_data, key)
  581. if not value:
  582. raise HTTPException(400, detail=f"Required field {key} is empty")
  583. if form_data.use_tls and not form_data.certificate_path:
  584. raise HTTPException(
  585. 400, detail="TLS is enabled but certificate file path is missing"
  586. )
  587. request.app.state.config.LDAP_SERVER_LABEL = form_data.label
  588. request.app.state.config.LDAP_SERVER_HOST = form_data.host
  589. request.app.state.config.LDAP_SERVER_PORT = form_data.port
  590. request.app.state.config.LDAP_ATTRIBUTE_FOR_USERNAME = (
  591. form_data.attribute_for_username
  592. )
  593. request.app.state.config.LDAP_APP_DN = form_data.app_dn
  594. request.app.state.config.LDAP_APP_PASSWORD = form_data.app_dn_password
  595. request.app.state.config.LDAP_SEARCH_BASE = form_data.search_base
  596. request.app.state.config.LDAP_SEARCH_FILTERS = form_data.search_filters
  597. request.app.state.config.LDAP_USE_TLS = form_data.use_tls
  598. request.app.state.config.LDAP_CA_CERT_FILE = form_data.certificate_path
  599. request.app.state.config.LDAP_CIPHERS = form_data.ciphers
  600. return {
  601. "label": request.app.state.config.LDAP_SERVER_LABEL,
  602. "host": request.app.state.config.LDAP_SERVER_HOST,
  603. "port": request.app.state.config.LDAP_SERVER_PORT,
  604. "attribute_for_username": request.app.state.config.LDAP_ATTRIBUTE_FOR_USERNAME,
  605. "app_dn": request.app.state.config.LDAP_APP_DN,
  606. "app_dn_password": request.app.state.config.LDAP_APP_PASSWORD,
  607. "search_base": request.app.state.config.LDAP_SEARCH_BASE,
  608. "search_filters": request.app.state.config.LDAP_SEARCH_FILTERS,
  609. "use_tls": request.app.state.config.LDAP_USE_TLS,
  610. "certificate_path": request.app.state.config.LDAP_CA_CERT_FILE,
  611. "ciphers": request.app.state.config.LDAP_CIPHERS,
  612. }
  613. @router.get("/admin/config/ldap")
  614. async def get_ldap_config(request: Request, user=Depends(get_admin_user)):
  615. return {"ENABLE_LDAP": request.app.state.config.ENABLE_LDAP}
  616. class LdapConfigForm(BaseModel):
  617. enable_ldap: Optional[bool] = None
  618. @router.post("/admin/config/ldap")
  619. async def update_ldap_config(
  620. request: Request, form_data: LdapConfigForm, user=Depends(get_admin_user)
  621. ):
  622. request.app.state.config.ENABLE_LDAP = form_data.enable_ldap
  623. return {"ENABLE_LDAP": request.app.state.config.ENABLE_LDAP}
  624. ############################
  625. # API Key
  626. ############################
  627. # create api key
  628. @router.post("/api_key", response_model=ApiKey)
  629. async def generate_api_key(request: Request, user=Depends(get_current_user)):
  630. if not request.app.state.config.ENABLE_API_KEY:
  631. raise HTTPException(
  632. status.HTTP_403_FORBIDDEN,
  633. detail=ERROR_MESSAGES.API_KEY_CREATION_NOT_ALLOWED,
  634. )
  635. api_key = create_api_key()
  636. success = Users.update_user_api_key_by_id(user.id, api_key)
  637. if success:
  638. return {
  639. "api_key": api_key,
  640. }
  641. else:
  642. raise HTTPException(500, detail=ERROR_MESSAGES.CREATE_API_KEY_ERROR)
  643. # delete api key
  644. @router.delete("/api_key", response_model=bool)
  645. async def delete_api_key(user=Depends(get_current_user)):
  646. success = Users.update_user_api_key_by_id(user.id, None)
  647. return success
  648. # get api key
  649. @router.get("/api_key", response_model=ApiKey)
  650. async def get_api_key(user=Depends(get_current_user)):
  651. api_key = Users.get_user_api_key_by_id(user.id)
  652. if api_key:
  653. return {
  654. "api_key": api_key,
  655. }
  656. else:
  657. raise HTTPException(404, detail=ERROR_MESSAGES.API_KEY_NOT_FOUND)