auths.py 24 KB

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