auths.py 24 KB

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