auths.py 26 KB

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