auths.py 25 KB

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