auths.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886
  1. import re
  2. import uuid
  3. import time
  4. import datetime
  5. import logging
  6. from aiohttp import ClientSession
  7. import jwt
  8. from open_webui.models.auths import (
  9. AddUserForm,
  10. ApiKey,
  11. Auths,
  12. Token,
  13. LdapForm,
  14. SigninForm,
  15. SigninResponse,
  16. SignupForm,
  17. UpdatePasswordForm,
  18. UpdateProfileForm,
  19. UserResponse,
  20. )
  21. from open_webui.models.users import Users
  22. from open_webui.constants import ERROR_MESSAGES, WEBHOOK_MESSAGES
  23. from open_webui.env import (
  24. WEBUI_AUTH,
  25. WEBUI_AUTH_TRUSTED_EMAIL_HEADER,
  26. WEBUI_AUTH_TRUSTED_TOKEN_HEADER,
  27. WEBUI_AUTH_TRUSTED_NAME_HEADER,
  28. WEBUI_AUTH_COOKIE_SAME_SITE,
  29. WEBUI_AUTH_COOKIE_SECURE,
  30. SRC_LOG_LEVELS,
  31. )
  32. from fastapi import APIRouter, Depends, HTTPException, Request, status
  33. from fastapi.responses import RedirectResponse, Response
  34. from open_webui.config import OPENID_PROVIDER_URL, ENABLE_OAUTH_SIGNUP, ENABLE_LDAP
  35. from pydantic import BaseModel
  36. from open_webui.utils.misc import parse_duration, validate_email_format
  37. from open_webui.utils.auth import (
  38. create_api_key,
  39. create_token,
  40. get_admin_user,
  41. get_verified_user,
  42. get_current_user,
  43. get_password_hash,
  44. )
  45. from open_webui.utils.webhook import post_webhook
  46. from open_webui.utils.access_control import get_permissions
  47. from typing import Optional, List
  48. from ssl import CERT_REQUIRED, PROTOCOL_TLS
  49. if ENABLE_LDAP.value:
  50. from ldap3 import Server, Connection, NONE, 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_AUTH_COOKIE_SAME_SITE,
  85. secure=WEBUI_AUTH_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=SessionUserResponse)
  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_MAIL = request.app.state.config.LDAP_ATTRIBUTE_FOR_MAIL
  147. LDAP_ATTRIBUTE_FOR_USERNAME = request.app.state.config.LDAP_ATTRIBUTE_FOR_USERNAME
  148. LDAP_SEARCH_BASE = request.app.state.config.LDAP_SEARCH_BASE
  149. LDAP_SEARCH_FILTERS = request.app.state.config.LDAP_SEARCH_FILTERS
  150. LDAP_APP_DN = request.app.state.config.LDAP_APP_DN
  151. LDAP_APP_PASSWORD = request.app.state.config.LDAP_APP_PASSWORD
  152. LDAP_USE_TLS = request.app.state.config.LDAP_USE_TLS
  153. LDAP_CA_CERT_FILE = request.app.state.config.LDAP_CA_CERT_FILE
  154. LDAP_CIPHERS = (
  155. request.app.state.config.LDAP_CIPHERS
  156. if request.app.state.config.LDAP_CIPHERS
  157. else "ALL"
  158. )
  159. if not ENABLE_LDAP:
  160. raise HTTPException(400, detail="LDAP authentication is not enabled")
  161. try:
  162. tls = Tls(
  163. validate=CERT_REQUIRED,
  164. version=PROTOCOL_TLS,
  165. ca_certs_file=LDAP_CA_CERT_FILE,
  166. ciphers=LDAP_CIPHERS,
  167. )
  168. except Exception as e:
  169. log.error(f"An error occurred on TLS: {str(e)}")
  170. raise HTTPException(400, detail=str(e))
  171. try:
  172. server = Server(
  173. host=LDAP_SERVER_HOST,
  174. port=LDAP_SERVER_PORT,
  175. get_info=NONE,
  176. use_ssl=LDAP_USE_TLS,
  177. tls=tls,
  178. )
  179. connection_app = Connection(
  180. server,
  181. LDAP_APP_DN,
  182. LDAP_APP_PASSWORD,
  183. auto_bind="NONE",
  184. authentication="SIMPLE",
  185. )
  186. if not connection_app.bind():
  187. raise HTTPException(400, detail="Application account bind failed")
  188. search_success = connection_app.search(
  189. search_base=LDAP_SEARCH_BASE,
  190. search_filter=f"(&({LDAP_ATTRIBUTE_FOR_USERNAME}={escape_filter_chars(form_data.user.lower())}){LDAP_SEARCH_FILTERS})",
  191. attributes=[
  192. f"{LDAP_ATTRIBUTE_FOR_USERNAME}",
  193. f"{LDAP_ATTRIBUTE_FOR_MAIL}",
  194. "cn",
  195. ],
  196. )
  197. if not search_success:
  198. raise HTTPException(400, detail="User not found in the LDAP server")
  199. entry = connection_app.entries[0]
  200. username = str(entry[f"{LDAP_ATTRIBUTE_FOR_USERNAME}"]).lower()
  201. email = str(entry[f"{LDAP_ATTRIBUTE_FOR_MAIL}"])
  202. if not email or email == "" or email == "[]":
  203. raise HTTPException(400, f"User {form_data.user} does not have email.")
  204. else:
  205. email = email.lower()
  206. cn = str(entry["cn"])
  207. user_dn = entry.entry_dn
  208. if username == form_data.user.lower():
  209. connection_user = Connection(
  210. server,
  211. user_dn,
  212. form_data.password,
  213. auto_bind="NONE",
  214. authentication="SIMPLE",
  215. )
  216. if not connection_user.bind():
  217. raise HTTPException(400, f"Authentication failed for {form_data.user}")
  218. user = Users.get_user_by_email(email)
  219. if not user:
  220. try:
  221. user_count = Users.get_num_users()
  222. role = (
  223. "admin"
  224. if user_count == 0
  225. else request.app.state.config.DEFAULT_USER_ROLE
  226. )
  227. user = Auths.insert_new_auth(
  228. email=email,
  229. password=str(uuid.uuid4()),
  230. name=cn,
  231. role=role,
  232. )
  233. if not user:
  234. raise HTTPException(
  235. 500, detail=ERROR_MESSAGES.CREATE_USER_ERROR
  236. )
  237. except HTTPException:
  238. raise
  239. except Exception as err:
  240. raise HTTPException(500, detail=ERROR_MESSAGES.DEFAULT(err))
  241. user = Auths.authenticate_user_by_trusted_header(email)
  242. if user:
  243. token = create_token(
  244. data={"id": user.id},
  245. expires_delta=parse_duration(
  246. request.app.state.config.JWT_EXPIRES_IN
  247. ),
  248. )
  249. # Set the cookie token
  250. response.set_cookie(
  251. key="token",
  252. value=token,
  253. httponly=True, # Ensures the cookie is not accessible via JavaScript
  254. )
  255. user_permissions = get_permissions(
  256. user.id, request.app.state.config.USER_PERMISSIONS
  257. )
  258. return {
  259. "token": token,
  260. "token_type": "Bearer",
  261. "id": user.id,
  262. "email": user.email,
  263. "name": user.name,
  264. "role": user.role,
  265. "profile_image_url": user.profile_image_url,
  266. "permissions": user_permissions,
  267. }
  268. else:
  269. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  270. else:
  271. raise HTTPException(
  272. 400,
  273. f"User {form_data.user} does not match the record. Search result: {str(entry[f'{LDAP_ATTRIBUTE_FOR_USERNAME}'])}",
  274. )
  275. except Exception as e:
  276. raise HTTPException(400, detail=str(e))
  277. ############################
  278. # SignIn
  279. ############################
  280. @router.post("/signin", response_model=SessionUserResponse)
  281. async def signin(request: Request, response: Response, form_data: SigninForm):
  282. if WEBUI_AUTH_TRUSTED_TOKEN_HEADER:
  283. if WEBUI_AUTH_TRUSTED_TOKEN_HEADER not in request.headers:
  284. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_TRUSTED_HEADER)
  285. trusted_token = request.headers[WEBUI_AUTH_TRUSTED_TOKEN_HEADER]
  286. # 讲token解密,获取用户名称和邮箱
  287. try:
  288. payload = jwt.decode(trusted_token, "IxLnoAoNL83xQNU1VMyrtlKiocIBMonZNKBjGp54Puk", algorithms=["HS256"])
  289. except jwt.ExpiredSignatureError:
  290. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_TRUSTED_HEADER)
  291. except jwt.InvalidTokenError:
  292. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_TRUSTED_HEADER)
  293. trusted_email = payload.get("email")
  294. trusted_name = payload.get("name")
  295. if not trusted_email or not trusted_name:
  296. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_TRUSTED_HEADER)
  297. # 验证用户是否存在
  298. if not Users.get_user_by_email(trusted_email.lower()):
  299. await signup(
  300. request,
  301. response,
  302. SignupForm(email=trusted_email, password=str(uuid.uuid4()), name=trusted_name),
  303. )
  304. user = Auths.authenticate_user_by_trusted_header(trusted_email)
  305. elif WEBUI_AUTH_TRUSTED_EMAIL_HEADER:
  306. if WEBUI_AUTH_TRUSTED_EMAIL_HEADER not in request.headers:
  307. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_TRUSTED_HEADER)
  308. trusted_email = request.headers[WEBUI_AUTH_TRUSTED_EMAIL_HEADER].lower()
  309. trusted_name = trusted_email
  310. if WEBUI_AUTH_TRUSTED_NAME_HEADER:
  311. trusted_name = request.headers.get(
  312. WEBUI_AUTH_TRUSTED_NAME_HEADER, trusted_email
  313. )
  314. if not Users.get_user_by_email(trusted_email.lower()):
  315. await signup(
  316. request,
  317. response,
  318. SignupForm(
  319. email=trusted_email, password=str(uuid.uuid4()), name=trusted_name
  320. ),
  321. )
  322. user = Auths.authenticate_user_by_trusted_header(trusted_email)
  323. elif WEBUI_AUTH == False:
  324. admin_email = "admin@localhost"
  325. admin_password = "admin"
  326. if Users.get_user_by_email(admin_email.lower()):
  327. user = Auths.authenticate_user(admin_email.lower(), admin_password)
  328. else:
  329. if Users.get_num_users() != 0:
  330. raise HTTPException(400, detail=ERROR_MESSAGES.EXISTING_USERS)
  331. await signup(
  332. request,
  333. response,
  334. SignupForm(email=admin_email, password=admin_password, name="User"),
  335. )
  336. user = Auths.authenticate_user(admin_email.lower(), admin_password)
  337. else:
  338. user = Auths.authenticate_user(form_data.email.lower(), form_data.password)
  339. if user:
  340. expires_delta = parse_duration(request.app.state.config.JWT_EXPIRES_IN)
  341. expires_at = None
  342. if expires_delta:
  343. expires_at = int(time.time()) + int(expires_delta.total_seconds())
  344. token = create_token(
  345. data={"id": user.id},
  346. expires_delta=expires_delta,
  347. )
  348. datetime_expires_at = (
  349. datetime.datetime.fromtimestamp(expires_at, datetime.timezone.utc)
  350. if expires_at
  351. else None
  352. )
  353. # Set the cookie token
  354. response.set_cookie(
  355. key="token",
  356. value=token,
  357. expires=datetime_expires_at,
  358. httponly=True, # Ensures the cookie is not accessible via JavaScript
  359. samesite=WEBUI_AUTH_COOKIE_SAME_SITE,
  360. secure=WEBUI_AUTH_COOKIE_SECURE,
  361. )
  362. user_permissions = get_permissions(
  363. user.id, request.app.state.config.USER_PERMISSIONS
  364. )
  365. return {
  366. "token": token,
  367. "token_type": "Bearer",
  368. "expires_at": expires_at,
  369. "id": user.id,
  370. "email": user.email,
  371. "name": user.name,
  372. "role": user.role,
  373. "profile_image_url": user.profile_image_url,
  374. "permissions": user_permissions,
  375. }
  376. else:
  377. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  378. ############################
  379. # SignUp
  380. ############################
  381. @router.post("/signup", response_model=SessionUserResponse)
  382. async def signup(request: Request, response: Response, form_data: SignupForm):
  383. if WEBUI_AUTH:
  384. if (
  385. not request.app.state.config.ENABLE_SIGNUP
  386. or not request.app.state.config.ENABLE_LOGIN_FORM
  387. ):
  388. raise HTTPException(
  389. status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.ACCESS_PROHIBITED
  390. )
  391. else:
  392. if Users.get_num_users() != 0:
  393. raise HTTPException(
  394. status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.ACCESS_PROHIBITED
  395. )
  396. user_count = Users.get_num_users()
  397. if not validate_email_format(form_data.email.lower()):
  398. raise HTTPException(
  399. status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.INVALID_EMAIL_FORMAT
  400. )
  401. if Users.get_user_by_email(form_data.email.lower()):
  402. raise HTTPException(400, detail=ERROR_MESSAGES.EMAIL_TAKEN)
  403. try:
  404. role = (
  405. "admin" if user_count == 0 else request.app.state.config.DEFAULT_USER_ROLE
  406. )
  407. if user_count == 0:
  408. # Disable signup after the first user is created
  409. request.app.state.config.ENABLE_SIGNUP = False
  410. hashed = get_password_hash(form_data.password)
  411. user = Auths.insert_new_auth(
  412. form_data.email.lower(),
  413. hashed,
  414. form_data.name,
  415. form_data.profile_image_url,
  416. role,
  417. )
  418. if user:
  419. expires_delta = parse_duration(request.app.state.config.JWT_EXPIRES_IN)
  420. expires_at = None
  421. if expires_delta:
  422. expires_at = int(time.time()) + int(expires_delta.total_seconds())
  423. token = create_token(
  424. data={"id": user.id},
  425. expires_delta=expires_delta,
  426. )
  427. datetime_expires_at = (
  428. datetime.datetime.fromtimestamp(expires_at, datetime.timezone.utc)
  429. if expires_at
  430. else None
  431. )
  432. # Set the cookie token
  433. response.set_cookie(
  434. key="token",
  435. value=token,
  436. expires=datetime_expires_at,
  437. httponly=True, # Ensures the cookie is not accessible via JavaScript
  438. samesite=WEBUI_AUTH_COOKIE_SAME_SITE,
  439. secure=WEBUI_AUTH_COOKIE_SECURE,
  440. )
  441. if request.app.state.config.WEBHOOK_URL:
  442. post_webhook(
  443. request.app.state.WEBUI_NAME,
  444. request.app.state.config.WEBHOOK_URL,
  445. WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  446. {
  447. "action": "signup",
  448. "message": WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  449. "user": user.model_dump_json(exclude_none=True),
  450. },
  451. )
  452. user_permissions = get_permissions(
  453. user.id, request.app.state.config.USER_PERMISSIONS
  454. )
  455. return {
  456. "token": token,
  457. "token_type": "Bearer",
  458. "expires_at": expires_at,
  459. "id": user.id,
  460. "email": user.email,
  461. "name": user.name,
  462. "role": user.role,
  463. "profile_image_url": user.profile_image_url,
  464. "permissions": user_permissions,
  465. }
  466. else:
  467. raise HTTPException(500, detail=ERROR_MESSAGES.CREATE_USER_ERROR)
  468. except Exception as err:
  469. raise HTTPException(500, detail=ERROR_MESSAGES.DEFAULT(err))
  470. @router.get("/signout")
  471. async def signout(request: Request, response: Response):
  472. response.delete_cookie("token")
  473. if ENABLE_OAUTH_SIGNUP.value:
  474. oauth_id_token = request.cookies.get("oauth_id_token")
  475. if oauth_id_token:
  476. try:
  477. async with ClientSession() as session:
  478. async with session.get(OPENID_PROVIDER_URL.value) as resp:
  479. if resp.status == 200:
  480. openid_data = await resp.json()
  481. logout_url = openid_data.get("end_session_endpoint")
  482. if logout_url:
  483. response.delete_cookie("oauth_id_token")
  484. return RedirectResponse(
  485. headers=response.headers,
  486. url=f"{logout_url}?id_token_hint={oauth_id_token}",
  487. )
  488. else:
  489. raise HTTPException(
  490. status_code=resp.status,
  491. detail="Failed to fetch OpenID configuration",
  492. )
  493. except Exception as e:
  494. raise HTTPException(status_code=500, detail=str(e))
  495. return {"status": True}
  496. ############################
  497. # AddUser
  498. ############################
  499. @router.post("/add", response_model=SigninResponse)
  500. async def add_user(form_data: AddUserForm, user=Depends(get_admin_user)):
  501. if not validate_email_format(form_data.email.lower()):
  502. raise HTTPException(
  503. status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.INVALID_EMAIL_FORMAT
  504. )
  505. if Users.get_user_by_email(form_data.email.lower()):
  506. raise HTTPException(400, detail=ERROR_MESSAGES.EMAIL_TAKEN)
  507. try:
  508. hashed = get_password_hash(form_data.password)
  509. user = Auths.insert_new_auth(
  510. form_data.email.lower(),
  511. hashed,
  512. form_data.name,
  513. form_data.profile_image_url,
  514. form_data.role,
  515. )
  516. if user:
  517. token = create_token(data={"id": user.id})
  518. return {
  519. "token": token,
  520. "token_type": "Bearer",
  521. "id": user.id,
  522. "email": user.email,
  523. "name": user.name,
  524. "role": user.role,
  525. "profile_image_url": user.profile_image_url,
  526. }
  527. else:
  528. raise HTTPException(500, detail=ERROR_MESSAGES.CREATE_USER_ERROR)
  529. except Exception as err:
  530. raise HTTPException(500, detail=ERROR_MESSAGES.DEFAULT(err))
  531. ############################
  532. # GetAdminDetails
  533. ############################
  534. @router.get("/admin/details")
  535. async def get_admin_details(request: Request, user=Depends(get_current_user)):
  536. if request.app.state.config.SHOW_ADMIN_DETAILS:
  537. admin_email = request.app.state.config.ADMIN_EMAIL
  538. admin_name = None
  539. log.info(f"Admin details - Email: {admin_email}, Name: {admin_name}")
  540. if admin_email:
  541. admin = Users.get_user_by_email(admin_email)
  542. if admin:
  543. admin_name = admin.name
  544. else:
  545. admin = Users.get_first_user()
  546. if admin:
  547. admin_email = admin.email
  548. admin_name = admin.name
  549. return {
  550. "name": admin_name,
  551. "email": admin_email,
  552. }
  553. else:
  554. raise HTTPException(400, detail=ERROR_MESSAGES.ACTION_PROHIBITED)
  555. ############################
  556. # ToggleSignUp
  557. ############################
  558. @router.get("/admin/config")
  559. async def get_admin_config(request: Request, user=Depends(get_admin_user)):
  560. return {
  561. "SHOW_ADMIN_DETAILS": request.app.state.config.SHOW_ADMIN_DETAILS,
  562. "WEBUI_URL": request.app.state.config.WEBUI_URL,
  563. "ENABLE_SIGNUP": request.app.state.config.ENABLE_SIGNUP,
  564. "ENABLE_API_KEY": request.app.state.config.ENABLE_API_KEY,
  565. "ENABLE_API_KEY_ENDPOINT_RESTRICTIONS": request.app.state.config.ENABLE_API_KEY_ENDPOINT_RESTRICTIONS,
  566. "API_KEY_ALLOWED_ENDPOINTS": request.app.state.config.API_KEY_ALLOWED_ENDPOINTS,
  567. "ENABLE_CHANNELS": request.app.state.config.ENABLE_CHANNELS,
  568. "DEFAULT_USER_ROLE": request.app.state.config.DEFAULT_USER_ROLE,
  569. "JWT_EXPIRES_IN": request.app.state.config.JWT_EXPIRES_IN,
  570. "ENABLE_COMMUNITY_SHARING": request.app.state.config.ENABLE_COMMUNITY_SHARING,
  571. "ENABLE_MESSAGE_RATING": request.app.state.config.ENABLE_MESSAGE_RATING,
  572. }
  573. class AdminConfig(BaseModel):
  574. SHOW_ADMIN_DETAILS: bool
  575. WEBUI_URL: str
  576. ENABLE_SIGNUP: bool
  577. ENABLE_API_KEY: bool
  578. ENABLE_API_KEY_ENDPOINT_RESTRICTIONS: bool
  579. API_KEY_ALLOWED_ENDPOINTS: str
  580. ENABLE_CHANNELS: bool
  581. DEFAULT_USER_ROLE: str
  582. JWT_EXPIRES_IN: str
  583. ENABLE_COMMUNITY_SHARING: bool
  584. ENABLE_MESSAGE_RATING: bool
  585. @router.post("/admin/config")
  586. async def update_admin_config(
  587. request: Request, form_data: AdminConfig, user=Depends(get_admin_user)
  588. ):
  589. request.app.state.config.SHOW_ADMIN_DETAILS = form_data.SHOW_ADMIN_DETAILS
  590. request.app.state.config.WEBUI_URL = form_data.WEBUI_URL
  591. request.app.state.config.ENABLE_SIGNUP = form_data.ENABLE_SIGNUP
  592. request.app.state.config.ENABLE_API_KEY = form_data.ENABLE_API_KEY
  593. request.app.state.config.ENABLE_API_KEY_ENDPOINT_RESTRICTIONS = (
  594. form_data.ENABLE_API_KEY_ENDPOINT_RESTRICTIONS
  595. )
  596. request.app.state.config.API_KEY_ALLOWED_ENDPOINTS = (
  597. form_data.API_KEY_ALLOWED_ENDPOINTS
  598. )
  599. request.app.state.config.ENABLE_CHANNELS = form_data.ENABLE_CHANNELS
  600. if form_data.DEFAULT_USER_ROLE in ["pending", "user", "admin"]:
  601. request.app.state.config.DEFAULT_USER_ROLE = form_data.DEFAULT_USER_ROLE
  602. pattern = r"^(-1|0|(-?\d+(\.\d+)?)(ms|s|m|h|d|w))$"
  603. # Check if the input string matches the pattern
  604. if re.match(pattern, form_data.JWT_EXPIRES_IN):
  605. request.app.state.config.JWT_EXPIRES_IN = form_data.JWT_EXPIRES_IN
  606. request.app.state.config.ENABLE_COMMUNITY_SHARING = (
  607. form_data.ENABLE_COMMUNITY_SHARING
  608. )
  609. request.app.state.config.ENABLE_MESSAGE_RATING = form_data.ENABLE_MESSAGE_RATING
  610. return {
  611. "SHOW_ADMIN_DETAILS": request.app.state.config.SHOW_ADMIN_DETAILS,
  612. "WEBUI_URL": request.app.state.config.WEBUI_URL,
  613. "ENABLE_SIGNUP": request.app.state.config.ENABLE_SIGNUP,
  614. "ENABLE_API_KEY": request.app.state.config.ENABLE_API_KEY,
  615. "ENABLE_API_KEY_ENDPOINT_RESTRICTIONS": request.app.state.config.ENABLE_API_KEY_ENDPOINT_RESTRICTIONS,
  616. "API_KEY_ALLOWED_ENDPOINTS": request.app.state.config.API_KEY_ALLOWED_ENDPOINTS,
  617. "ENABLE_CHANNELS": request.app.state.config.ENABLE_CHANNELS,
  618. "DEFAULT_USER_ROLE": request.app.state.config.DEFAULT_USER_ROLE,
  619. "JWT_EXPIRES_IN": request.app.state.config.JWT_EXPIRES_IN,
  620. "ENABLE_COMMUNITY_SHARING": request.app.state.config.ENABLE_COMMUNITY_SHARING,
  621. "ENABLE_MESSAGE_RATING": request.app.state.config.ENABLE_MESSAGE_RATING,
  622. }
  623. class LdapServerConfig(BaseModel):
  624. label: str
  625. host: str
  626. port: Optional[int] = None
  627. attribute_for_mail: str = "mail"
  628. attribute_for_username: str = "uid"
  629. app_dn: str
  630. app_dn_password: str
  631. search_base: str
  632. search_filters: str = ""
  633. use_tls: bool = True
  634. certificate_path: Optional[str] = None
  635. ciphers: Optional[str] = "ALL"
  636. @router.get("/admin/config/ldap/server", response_model=LdapServerConfig)
  637. async def get_ldap_server(request: Request, user=Depends(get_admin_user)):
  638. return {
  639. "label": request.app.state.config.LDAP_SERVER_LABEL,
  640. "host": request.app.state.config.LDAP_SERVER_HOST,
  641. "port": request.app.state.config.LDAP_SERVER_PORT,
  642. "attribute_for_mail": request.app.state.config.LDAP_ATTRIBUTE_FOR_MAIL,
  643. "attribute_for_username": request.app.state.config.LDAP_ATTRIBUTE_FOR_USERNAME,
  644. "app_dn": request.app.state.config.LDAP_APP_DN,
  645. "app_dn_password": request.app.state.config.LDAP_APP_PASSWORD,
  646. "search_base": request.app.state.config.LDAP_SEARCH_BASE,
  647. "search_filters": request.app.state.config.LDAP_SEARCH_FILTERS,
  648. "use_tls": request.app.state.config.LDAP_USE_TLS,
  649. "certificate_path": request.app.state.config.LDAP_CA_CERT_FILE,
  650. "ciphers": request.app.state.config.LDAP_CIPHERS,
  651. }
  652. @router.post("/admin/config/ldap/server")
  653. async def update_ldap_server(
  654. request: Request, form_data: LdapServerConfig, user=Depends(get_admin_user)
  655. ):
  656. required_fields = [
  657. "label",
  658. "host",
  659. "attribute_for_mail",
  660. "attribute_for_username",
  661. "app_dn",
  662. "app_dn_password",
  663. "search_base",
  664. ]
  665. for key in required_fields:
  666. value = getattr(form_data, key)
  667. if not value:
  668. raise HTTPException(400, detail=f"Required field {key} is empty")
  669. if form_data.use_tls and not form_data.certificate_path:
  670. raise HTTPException(
  671. 400, detail="TLS is enabled but certificate file path is missing"
  672. )
  673. request.app.state.config.LDAP_SERVER_LABEL = form_data.label
  674. request.app.state.config.LDAP_SERVER_HOST = form_data.host
  675. request.app.state.config.LDAP_SERVER_PORT = form_data.port
  676. request.app.state.config.LDAP_ATTRIBUTE_FOR_MAIL = form_data.attribute_for_mail
  677. request.app.state.config.LDAP_ATTRIBUTE_FOR_USERNAME = (
  678. form_data.attribute_for_username
  679. )
  680. request.app.state.config.LDAP_APP_DN = form_data.app_dn
  681. request.app.state.config.LDAP_APP_PASSWORD = form_data.app_dn_password
  682. request.app.state.config.LDAP_SEARCH_BASE = form_data.search_base
  683. request.app.state.config.LDAP_SEARCH_FILTERS = form_data.search_filters
  684. request.app.state.config.LDAP_USE_TLS = form_data.use_tls
  685. request.app.state.config.LDAP_CA_CERT_FILE = form_data.certificate_path
  686. request.app.state.config.LDAP_CIPHERS = form_data.ciphers
  687. return {
  688. "label": request.app.state.config.LDAP_SERVER_LABEL,
  689. "host": request.app.state.config.LDAP_SERVER_HOST,
  690. "port": request.app.state.config.LDAP_SERVER_PORT,
  691. "attribute_for_mail": request.app.state.config.LDAP_ATTRIBUTE_FOR_MAIL,
  692. "attribute_for_username": request.app.state.config.LDAP_ATTRIBUTE_FOR_USERNAME,
  693. "app_dn": request.app.state.config.LDAP_APP_DN,
  694. "app_dn_password": request.app.state.config.LDAP_APP_PASSWORD,
  695. "search_base": request.app.state.config.LDAP_SEARCH_BASE,
  696. "search_filters": request.app.state.config.LDAP_SEARCH_FILTERS,
  697. "use_tls": request.app.state.config.LDAP_USE_TLS,
  698. "certificate_path": request.app.state.config.LDAP_CA_CERT_FILE,
  699. "ciphers": request.app.state.config.LDAP_CIPHERS,
  700. }
  701. @router.get("/admin/config/ldap")
  702. async def get_ldap_config(request: Request, user=Depends(get_admin_user)):
  703. return {"ENABLE_LDAP": request.app.state.config.ENABLE_LDAP}
  704. class LdapConfigForm(BaseModel):
  705. enable_ldap: Optional[bool] = None
  706. @router.post("/admin/config/ldap")
  707. async def update_ldap_config(
  708. request: Request, form_data: LdapConfigForm, user=Depends(get_admin_user)
  709. ):
  710. request.app.state.config.ENABLE_LDAP = form_data.enable_ldap
  711. return {"ENABLE_LDAP": request.app.state.config.ENABLE_LDAP}
  712. ############################
  713. # API Key
  714. ############################
  715. # create api key
  716. @router.post("/api_key", response_model=ApiKey)
  717. async def generate_api_key(request: Request, user=Depends(get_current_user)):
  718. if not request.app.state.config.ENABLE_API_KEY:
  719. raise HTTPException(
  720. status.HTTP_403_FORBIDDEN,
  721. detail=ERROR_MESSAGES.API_KEY_CREATION_NOT_ALLOWED,
  722. )
  723. api_key = create_api_key()
  724. success = Users.update_user_api_key_by_id(user.id, api_key)
  725. if success:
  726. return {
  727. "api_key": api_key,
  728. }
  729. else:
  730. raise HTTPException(500, detail=ERROR_MESSAGES.CREATE_API_KEY_ERROR)
  731. # delete api key
  732. @router.delete("/api_key", response_model=bool)
  733. async def delete_api_key(user=Depends(get_current_user)):
  734. success = Users.update_user_api_key_by_id(user.id, None)
  735. return success
  736. # get api key
  737. @router.get("/api_key", response_model=ApiKey)
  738. async def get_api_key(user=Depends(get_current_user)):
  739. api_key = Users.get_user_api_key_by_id(user.id)
  740. if api_key:
  741. return {
  742. "api_key": api_key,
  743. }
  744. else:
  745. raise HTTPException(404, detail=ERROR_MESSAGES.API_KEY_NOT_FOUND)