auths.py 25 KB

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