auths.py 27 KB

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