auths.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956
  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.models.groups import Groups
  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_NAME_HEADER,
  27. WEBUI_AUTH_TRUSTED_GROUPS_HEADER,
  28. WEBUI_AUTH_COOKIE_SAME_SITE,
  29. WEBUI_AUTH_COOKIE_SECURE,
  30. WEBUI_AUTH_SIGNOUT_REDIRECT_URL,
  31. SRC_LOG_LEVELS,
  32. )
  33. from fastapi import APIRouter, Depends, HTTPException, Request, status
  34. from fastapi.responses import RedirectResponse, Response, JSONResponse
  35. from open_webui.config import OPENID_PROVIDER_URL, ENABLE_OAUTH_SIGNUP, ENABLE_LDAP
  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. decode_token,
  40. create_api_key,
  41. create_token,
  42. get_admin_user,
  43. get_verified_user,
  44. get_current_user,
  45. get_password_hash,
  46. get_http_authorization_cred,
  47. )
  48. from open_webui.utils.webhook import post_webhook
  49. from open_webui.utils.access_control import get_permissions
  50. from typing import Optional, List
  51. from ssl import CERT_NONE, CERT_REQUIRED, PROTOCOL_TLS
  52. if ENABLE_LDAP.value:
  53. from ldap3 import Server, Connection, NONE, Tls
  54. from ldap3.utils.conv import escape_filter_chars
  55. router = APIRouter()
  56. log = logging.getLogger(__name__)
  57. log.setLevel(SRC_LOG_LEVELS["MAIN"])
  58. ############################
  59. # GetSessionUser
  60. ############################
  61. class SessionUserResponse(Token, UserResponse):
  62. expires_at: Optional[int] = None
  63. permissions: Optional[dict] = None
  64. @router.get("/", response_model=SessionUserResponse)
  65. async def get_session_user(
  66. request: Request, response: Response, user=Depends(get_current_user)
  67. ):
  68. auth_header = request.headers.get("Authorization")
  69. auth_token = get_http_authorization_cred(auth_header)
  70. token = auth_token.credentials
  71. data = decode_token(token)
  72. expires_at = None
  73. if data:
  74. expires_at = data.get("exp")
  75. if (expires_at is not None) and int(time.time()) > expires_at:
  76. raise HTTPException(
  77. status_code=status.HTTP_401_UNAUTHORIZED,
  78. detail=ERROR_MESSAGES.INVALID_TOKEN,
  79. )
  80. # Set the cookie token
  81. response.set_cookie(
  82. key="token",
  83. value=token,
  84. expires=(
  85. datetime.datetime.fromtimestamp(expires_at, datetime.timezone.utc)
  86. if expires_at
  87. else None
  88. ),
  89. httponly=True, # Ensures the cookie is not accessible via JavaScript
  90. samesite=WEBUI_AUTH_COOKIE_SAME_SITE,
  91. secure=WEBUI_AUTH_COOKIE_SECURE,
  92. )
  93. user_permissions = get_permissions(
  94. user.id, request.app.state.config.USER_PERMISSIONS
  95. )
  96. return {
  97. "token": token,
  98. "token_type": "Bearer",
  99. "expires_at": expires_at,
  100. "id": user.id,
  101. "email": user.email,
  102. "name": user.name,
  103. "role": user.role,
  104. "profile_image_url": user.profile_image_url,
  105. "permissions": user_permissions,
  106. }
  107. ############################
  108. # Update Profile
  109. ############################
  110. @router.post("/update/profile", response_model=UserResponse)
  111. async def update_profile(
  112. form_data: UpdateProfileForm, session_user=Depends(get_verified_user)
  113. ):
  114. if session_user:
  115. user = Users.update_user_by_id(
  116. session_user.id,
  117. {"profile_image_url": form_data.profile_image_url, "name": form_data.name},
  118. )
  119. if user:
  120. return user
  121. else:
  122. raise HTTPException(400, detail=ERROR_MESSAGES.DEFAULT())
  123. else:
  124. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  125. ############################
  126. # Update Password
  127. ############################
  128. @router.post("/update/password", response_model=bool)
  129. async def update_password(
  130. form_data: UpdatePasswordForm, session_user=Depends(get_current_user)
  131. ):
  132. if WEBUI_AUTH_TRUSTED_EMAIL_HEADER:
  133. raise HTTPException(400, detail=ERROR_MESSAGES.ACTION_PROHIBITED)
  134. if session_user:
  135. user = Auths.authenticate_user(session_user.email, form_data.password)
  136. if user:
  137. hashed = get_password_hash(form_data.new_password)
  138. return Auths.update_user_password_by_id(user.id, hashed)
  139. else:
  140. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_PASSWORD)
  141. else:
  142. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  143. ############################
  144. # LDAP Authentication
  145. ############################
  146. @router.post("/ldap", response_model=SessionUserResponse)
  147. async def ldap_auth(request: Request, response: Response, form_data: LdapForm):
  148. ENABLE_LDAP = request.app.state.config.ENABLE_LDAP
  149. LDAP_SERVER_LABEL = request.app.state.config.LDAP_SERVER_LABEL
  150. LDAP_SERVER_HOST = request.app.state.config.LDAP_SERVER_HOST
  151. LDAP_SERVER_PORT = request.app.state.config.LDAP_SERVER_PORT
  152. LDAP_ATTRIBUTE_FOR_MAIL = request.app.state.config.LDAP_ATTRIBUTE_FOR_MAIL
  153. LDAP_ATTRIBUTE_FOR_USERNAME = request.app.state.config.LDAP_ATTRIBUTE_FOR_USERNAME
  154. LDAP_SEARCH_BASE = request.app.state.config.LDAP_SEARCH_BASE
  155. LDAP_SEARCH_FILTERS = request.app.state.config.LDAP_SEARCH_FILTERS
  156. LDAP_APP_DN = request.app.state.config.LDAP_APP_DN
  157. LDAP_APP_PASSWORD = request.app.state.config.LDAP_APP_PASSWORD
  158. LDAP_USE_TLS = request.app.state.config.LDAP_USE_TLS
  159. LDAP_CA_CERT_FILE = request.app.state.config.LDAP_CA_CERT_FILE
  160. LDAP_VALIDATE_CERT = (
  161. CERT_REQUIRED if request.app.state.config.LDAP_VALIDATE_CERT else CERT_NONE
  162. )
  163. LDAP_CIPHERS = (
  164. request.app.state.config.LDAP_CIPHERS
  165. if request.app.state.config.LDAP_CIPHERS
  166. else "ALL"
  167. )
  168. if not ENABLE_LDAP:
  169. raise HTTPException(400, detail="LDAP authentication is not enabled")
  170. try:
  171. tls = Tls(
  172. validate=LDAP_VALIDATE_CERT,
  173. version=PROTOCOL_TLS,
  174. ca_certs_file=LDAP_CA_CERT_FILE,
  175. ciphers=LDAP_CIPHERS,
  176. )
  177. except Exception as e:
  178. log.error(f"TLS configuration error: {str(e)}")
  179. raise HTTPException(400, detail="Failed to configure TLS for LDAP connection.")
  180. try:
  181. server = Server(
  182. host=LDAP_SERVER_HOST,
  183. port=LDAP_SERVER_PORT,
  184. get_info=NONE,
  185. use_ssl=LDAP_USE_TLS,
  186. tls=tls,
  187. )
  188. connection_app = Connection(
  189. server,
  190. LDAP_APP_DN,
  191. LDAP_APP_PASSWORD,
  192. auto_bind="NONE",
  193. authentication="SIMPLE" if LDAP_APP_DN else "ANONYMOUS",
  194. )
  195. if not connection_app.bind():
  196. raise HTTPException(400, detail="Application account bind failed")
  197. search_success = connection_app.search(
  198. search_base=LDAP_SEARCH_BASE,
  199. search_filter=f"(&({LDAP_ATTRIBUTE_FOR_USERNAME}={escape_filter_chars(form_data.user.lower())}){LDAP_SEARCH_FILTERS})",
  200. attributes=[
  201. f"{LDAP_ATTRIBUTE_FOR_USERNAME}",
  202. f"{LDAP_ATTRIBUTE_FOR_MAIL}",
  203. "cn",
  204. ],
  205. )
  206. if not search_success or not connection_app.entries:
  207. raise HTTPException(400, detail="User not found in the LDAP server")
  208. entry = connection_app.entries[0]
  209. username = str(entry[f"{LDAP_ATTRIBUTE_FOR_USERNAME}"]).lower()
  210. email = entry[
  211. f"{LDAP_ATTRIBUTE_FOR_MAIL}"
  212. ].value # retrieve the Attribute value
  213. if not email:
  214. raise HTTPException(400, "User does not have a valid email address.")
  215. elif isinstance(email, str):
  216. email = email.lower()
  217. elif isinstance(email, list):
  218. email = email[0].lower()
  219. else:
  220. email = str(email).lower()
  221. cn = str(entry["cn"])
  222. user_dn = entry.entry_dn
  223. if username == form_data.user.lower():
  224. connection_user = Connection(
  225. server,
  226. user_dn,
  227. form_data.password,
  228. auto_bind="NONE",
  229. authentication="SIMPLE",
  230. )
  231. if not connection_user.bind():
  232. raise HTTPException(400, "Authentication failed.")
  233. user = Users.get_user_by_email(email)
  234. if not user:
  235. try:
  236. user_count = Users.get_num_users()
  237. role = (
  238. "admin"
  239. if user_count == 0
  240. else request.app.state.config.DEFAULT_USER_ROLE
  241. )
  242. user = Auths.insert_new_auth(
  243. email=email,
  244. password=str(uuid.uuid4()),
  245. name=cn,
  246. role=role,
  247. )
  248. if not user:
  249. raise HTTPException(
  250. 500, detail=ERROR_MESSAGES.CREATE_USER_ERROR
  251. )
  252. except HTTPException:
  253. raise
  254. except Exception as err:
  255. log.error(f"LDAP user creation error: {str(err)}")
  256. raise HTTPException(
  257. 500, detail="Internal error occurred during LDAP user creation."
  258. )
  259. user = Auths.authenticate_user_by_email(email)
  260. if user:
  261. expires_delta = parse_duration(request.app.state.config.JWT_EXPIRES_IN)
  262. expires_at = None
  263. if expires_delta:
  264. expires_at = int(time.time()) + int(expires_delta.total_seconds())
  265. token = create_token(
  266. data={"id": user.id},
  267. expires_delta=expires_delta,
  268. )
  269. # Set the cookie token
  270. response.set_cookie(
  271. key="token",
  272. value=token,
  273. expires=(
  274. datetime.datetime.fromtimestamp(
  275. expires_at, datetime.timezone.utc
  276. )
  277. if expires_at
  278. else None
  279. ),
  280. httponly=True, # Ensures the cookie is not accessible via JavaScript
  281. samesite=WEBUI_AUTH_COOKIE_SAME_SITE,
  282. secure=WEBUI_AUTH_COOKIE_SECURE,
  283. )
  284. user_permissions = get_permissions(
  285. user.id, request.app.state.config.USER_PERMISSIONS
  286. )
  287. return {
  288. "token": token,
  289. "token_type": "Bearer",
  290. "expires_at": expires_at,
  291. "id": user.id,
  292. "email": user.email,
  293. "name": user.name,
  294. "role": user.role,
  295. "profile_image_url": user.profile_image_url,
  296. "permissions": user_permissions,
  297. }
  298. else:
  299. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  300. else:
  301. raise HTTPException(400, "User record mismatch.")
  302. except Exception as e:
  303. log.error(f"LDAP authentication error: {str(e)}")
  304. raise HTTPException(400, detail="LDAP authentication failed.")
  305. ############################
  306. # SignIn
  307. ############################
  308. @router.post("/signin", response_model=SessionUserResponse)
  309. async def signin(request: Request, response: Response, form_data: SigninForm):
  310. if WEBUI_AUTH_TRUSTED_EMAIL_HEADER:
  311. if WEBUI_AUTH_TRUSTED_EMAIL_HEADER not in request.headers:
  312. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_TRUSTED_HEADER)
  313. email = request.headers[WEBUI_AUTH_TRUSTED_EMAIL_HEADER].lower()
  314. name = email
  315. if WEBUI_AUTH_TRUSTED_NAME_HEADER:
  316. name = request.headers.get(WEBUI_AUTH_TRUSTED_NAME_HEADER, email)
  317. if not Users.get_user_by_email(email.lower()):
  318. await signup(
  319. request,
  320. response,
  321. SignupForm(email=email, password=str(uuid.uuid4()), name=name),
  322. )
  323. user = Auths.authenticate_user_by_email(email)
  324. if WEBUI_AUTH_TRUSTED_GROUPS_HEADER and user and user.role != "admin":
  325. group_names = request.headers.get(
  326. WEBUI_AUTH_TRUSTED_GROUPS_HEADER, ""
  327. ).split(",")
  328. group_names = [name.strip() for name in group_names if name.strip()]
  329. if group_names:
  330. Groups.sync_user_groups_by_group_names(user.id, group_names)
  331. elif WEBUI_AUTH == False:
  332. admin_email = "admin@localhost"
  333. admin_password = "admin"
  334. if Users.get_user_by_email(admin_email.lower()):
  335. user = Auths.authenticate_user(admin_email.lower(), admin_password)
  336. else:
  337. if Users.get_num_users() != 0:
  338. raise HTTPException(400, detail=ERROR_MESSAGES.EXISTING_USERS)
  339. await signup(
  340. request,
  341. response,
  342. SignupForm(email=admin_email, password=admin_password, name="User"),
  343. )
  344. user = Auths.authenticate_user(admin_email.lower(), admin_password)
  345. else:
  346. user = Auths.authenticate_user(form_data.email.lower(), form_data.password)
  347. if user:
  348. expires_delta = parse_duration(request.app.state.config.JWT_EXPIRES_IN)
  349. expires_at = None
  350. if expires_delta:
  351. expires_at = int(time.time()) + int(expires_delta.total_seconds())
  352. token = create_token(
  353. data={"id": user.id},
  354. expires_delta=expires_delta,
  355. )
  356. datetime_expires_at = (
  357. datetime.datetime.fromtimestamp(expires_at, datetime.timezone.utc)
  358. if expires_at
  359. else None
  360. )
  361. # Set the cookie token
  362. response.set_cookie(
  363. key="token",
  364. value=token,
  365. expires=datetime_expires_at,
  366. httponly=True, # Ensures the cookie is not accessible via JavaScript
  367. samesite=WEBUI_AUTH_COOKIE_SAME_SITE,
  368. secure=WEBUI_AUTH_COOKIE_SECURE,
  369. )
  370. user_permissions = get_permissions(
  371. user.id, request.app.state.config.USER_PERMISSIONS
  372. )
  373. return {
  374. "token": token,
  375. "token_type": "Bearer",
  376. "expires_at": expires_at,
  377. "id": user.id,
  378. "email": user.email,
  379. "name": user.name,
  380. "role": user.role,
  381. "profile_image_url": user.profile_image_url,
  382. "permissions": user_permissions,
  383. }
  384. else:
  385. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  386. ############################
  387. # SignUp
  388. ############################
  389. @router.post("/signup", response_model=SessionUserResponse)
  390. async def signup(request: Request, response: Response, form_data: SignupForm):
  391. if WEBUI_AUTH:
  392. if (
  393. not request.app.state.config.ENABLE_SIGNUP
  394. or not request.app.state.config.ENABLE_LOGIN_FORM
  395. ):
  396. raise HTTPException(
  397. status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.ACCESS_PROHIBITED
  398. )
  399. else:
  400. if Users.get_num_users() != 0:
  401. raise HTTPException(
  402. status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.ACCESS_PROHIBITED
  403. )
  404. user_count = Users.get_num_users()
  405. if not validate_email_format(form_data.email.lower()):
  406. raise HTTPException(
  407. status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.INVALID_EMAIL_FORMAT
  408. )
  409. if Users.get_user_by_email(form_data.email.lower()):
  410. raise HTTPException(400, detail=ERROR_MESSAGES.EMAIL_TAKEN)
  411. try:
  412. role = (
  413. "admin" if user_count == 0 else request.app.state.config.DEFAULT_USER_ROLE
  414. )
  415. # The password passed to bcrypt must be 72 bytes or fewer. If it is longer, it will be truncated before hashing.
  416. if len(form_data.password.encode("utf-8")) > 72:
  417. raise HTTPException(
  418. status.HTTP_400_BAD_REQUEST,
  419. detail=ERROR_MESSAGES.PASSWORD_TOO_LONG,
  420. )
  421. hashed = get_password_hash(form_data.password)
  422. user = Auths.insert_new_auth(
  423. form_data.email.lower(),
  424. hashed,
  425. form_data.name,
  426. form_data.profile_image_url,
  427. role,
  428. )
  429. if user:
  430. expires_delta = parse_duration(request.app.state.config.JWT_EXPIRES_IN)
  431. expires_at = None
  432. if expires_delta:
  433. expires_at = int(time.time()) + int(expires_delta.total_seconds())
  434. token = create_token(
  435. data={"id": user.id},
  436. expires_delta=expires_delta,
  437. )
  438. datetime_expires_at = (
  439. datetime.datetime.fromtimestamp(expires_at, datetime.timezone.utc)
  440. if expires_at
  441. else None
  442. )
  443. # Set the cookie token
  444. response.set_cookie(
  445. key="token",
  446. value=token,
  447. expires=datetime_expires_at,
  448. httponly=True, # Ensures the cookie is not accessible via JavaScript
  449. samesite=WEBUI_AUTH_COOKIE_SAME_SITE,
  450. secure=WEBUI_AUTH_COOKIE_SECURE,
  451. )
  452. if request.app.state.config.WEBHOOK_URL:
  453. post_webhook(
  454. request.app.state.WEBUI_NAME,
  455. request.app.state.config.WEBHOOK_URL,
  456. WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  457. {
  458. "action": "signup",
  459. "message": WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  460. "user": user.model_dump_json(exclude_none=True),
  461. },
  462. )
  463. user_permissions = get_permissions(
  464. user.id, request.app.state.config.USER_PERMISSIONS
  465. )
  466. if user_count == 0:
  467. # Disable signup after the first user is created
  468. request.app.state.config.ENABLE_SIGNUP = False
  469. return {
  470. "token": token,
  471. "token_type": "Bearer",
  472. "expires_at": expires_at,
  473. "id": user.id,
  474. "email": user.email,
  475. "name": user.name,
  476. "role": user.role,
  477. "profile_image_url": user.profile_image_url,
  478. "permissions": user_permissions,
  479. }
  480. else:
  481. raise HTTPException(500, detail=ERROR_MESSAGES.CREATE_USER_ERROR)
  482. except Exception as err:
  483. log.error(f"Signup error: {str(err)}")
  484. raise HTTPException(500, detail="An internal error occurred during signup.")
  485. @router.get("/signout")
  486. async def signout(request: Request, response: Response):
  487. response.delete_cookie("token")
  488. if ENABLE_OAUTH_SIGNUP.value:
  489. oauth_id_token = request.cookies.get("oauth_id_token")
  490. if oauth_id_token:
  491. try:
  492. async with ClientSession() as session:
  493. async with session.get(OPENID_PROVIDER_URL.value) as resp:
  494. if resp.status == 200:
  495. openid_data = await resp.json()
  496. logout_url = openid_data.get("end_session_endpoint")
  497. if logout_url:
  498. response.delete_cookie("oauth_id_token")
  499. return JSONResponse(
  500. status_code=200,
  501. content={
  502. "status": True,
  503. "redirect_url": f"{logout_url}?id_token_hint={oauth_id_token}",
  504. },
  505. headers=response.headers,
  506. )
  507. else:
  508. raise HTTPException(
  509. status_code=resp.status,
  510. detail="Failed to fetch OpenID configuration",
  511. )
  512. except Exception as e:
  513. log.error(f"OpenID signout error: {str(e)}")
  514. raise HTTPException(
  515. status_code=500,
  516. detail="Failed to sign out from the OpenID provider.",
  517. )
  518. if WEBUI_AUTH_SIGNOUT_REDIRECT_URL:
  519. return JSONResponse(
  520. status_code=200,
  521. content={
  522. "status": True,
  523. "redirect_url": WEBUI_AUTH_SIGNOUT_REDIRECT_URL,
  524. },
  525. headers=response.headers,
  526. )
  527. return JSONResponse(
  528. status_code=200, content={"status": True}, headers=response.headers
  529. )
  530. ############################
  531. # AddUser
  532. ############################
  533. @router.post("/add", response_model=SigninResponse)
  534. async def add_user(form_data: AddUserForm, user=Depends(get_admin_user)):
  535. if not validate_email_format(form_data.email.lower()):
  536. raise HTTPException(
  537. status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.INVALID_EMAIL_FORMAT
  538. )
  539. if Users.get_user_by_email(form_data.email.lower()):
  540. raise HTTPException(400, detail=ERROR_MESSAGES.EMAIL_TAKEN)
  541. try:
  542. hashed = get_password_hash(form_data.password)
  543. user = Auths.insert_new_auth(
  544. form_data.email.lower(),
  545. hashed,
  546. form_data.name,
  547. form_data.profile_image_url,
  548. form_data.role,
  549. )
  550. if user:
  551. token = create_token(data={"id": user.id})
  552. return {
  553. "token": token,
  554. "token_type": "Bearer",
  555. "id": user.id,
  556. "email": user.email,
  557. "name": user.name,
  558. "role": user.role,
  559. "profile_image_url": user.profile_image_url,
  560. }
  561. else:
  562. raise HTTPException(500, detail=ERROR_MESSAGES.CREATE_USER_ERROR)
  563. except Exception as err:
  564. log.error(f"Add user error: {str(err)}")
  565. raise HTTPException(
  566. 500, detail="An internal error occurred while adding the user."
  567. )
  568. ############################
  569. # GetAdminDetails
  570. ############################
  571. @router.get("/admin/details")
  572. async def get_admin_details(request: Request, user=Depends(get_current_user)):
  573. if request.app.state.config.SHOW_ADMIN_DETAILS:
  574. admin_email = request.app.state.config.ADMIN_EMAIL
  575. admin_name = None
  576. log.info(f"Admin details - Email: {admin_email}, Name: {admin_name}")
  577. if admin_email:
  578. admin = Users.get_user_by_email(admin_email)
  579. if admin:
  580. admin_name = admin.name
  581. else:
  582. admin = Users.get_first_user()
  583. if admin:
  584. admin_email = admin.email
  585. admin_name = admin.name
  586. return {
  587. "name": admin_name,
  588. "email": admin_email,
  589. }
  590. else:
  591. raise HTTPException(400, detail=ERROR_MESSAGES.ACTION_PROHIBITED)
  592. ############################
  593. # ToggleSignUp
  594. ############################
  595. @router.get("/admin/config")
  596. async def get_admin_config(request: Request, user=Depends(get_admin_user)):
  597. return {
  598. "SHOW_ADMIN_DETAILS": request.app.state.config.SHOW_ADMIN_DETAILS,
  599. "WEBUI_URL": request.app.state.config.WEBUI_URL,
  600. "ENABLE_SIGNUP": request.app.state.config.ENABLE_SIGNUP,
  601. "ENABLE_API_KEY": request.app.state.config.ENABLE_API_KEY,
  602. "ENABLE_API_KEY_ENDPOINT_RESTRICTIONS": request.app.state.config.ENABLE_API_KEY_ENDPOINT_RESTRICTIONS,
  603. "API_KEY_ALLOWED_ENDPOINTS": request.app.state.config.API_KEY_ALLOWED_ENDPOINTS,
  604. "DEFAULT_USER_ROLE": request.app.state.config.DEFAULT_USER_ROLE,
  605. "JWT_EXPIRES_IN": request.app.state.config.JWT_EXPIRES_IN,
  606. "ENABLE_COMMUNITY_SHARING": request.app.state.config.ENABLE_COMMUNITY_SHARING,
  607. "ENABLE_MESSAGE_RATING": request.app.state.config.ENABLE_MESSAGE_RATING,
  608. "ENABLE_CHANNELS": request.app.state.config.ENABLE_CHANNELS,
  609. "ENABLE_NOTES": request.app.state.config.ENABLE_NOTES,
  610. "ENABLE_USER_WEBHOOKS": request.app.state.config.ENABLE_USER_WEBHOOKS,
  611. "PENDING_USER_OVERLAY_TITLE": request.app.state.config.PENDING_USER_OVERLAY_TITLE,
  612. "PENDING_USER_OVERLAY_CONTENT": request.app.state.config.PENDING_USER_OVERLAY_CONTENT,
  613. "RESPONSE_WATERMARK": request.app.state.config.RESPONSE_WATERMARK,
  614. }
  615. class AdminConfig(BaseModel):
  616. SHOW_ADMIN_DETAILS: bool
  617. WEBUI_URL: str
  618. ENABLE_SIGNUP: bool
  619. ENABLE_API_KEY: bool
  620. ENABLE_API_KEY_ENDPOINT_RESTRICTIONS: bool
  621. API_KEY_ALLOWED_ENDPOINTS: str
  622. DEFAULT_USER_ROLE: str
  623. JWT_EXPIRES_IN: str
  624. ENABLE_COMMUNITY_SHARING: bool
  625. ENABLE_MESSAGE_RATING: bool
  626. ENABLE_CHANNELS: bool
  627. ENABLE_NOTES: bool
  628. ENABLE_USER_WEBHOOKS: bool
  629. PENDING_USER_OVERLAY_TITLE: Optional[str] = None
  630. PENDING_USER_OVERLAY_CONTENT: Optional[str] = None
  631. RESPONSE_WATERMARK: Optional[str] = None
  632. @router.post("/admin/config")
  633. async def update_admin_config(
  634. request: Request, form_data: AdminConfig, user=Depends(get_admin_user)
  635. ):
  636. request.app.state.config.SHOW_ADMIN_DETAILS = form_data.SHOW_ADMIN_DETAILS
  637. request.app.state.config.WEBUI_URL = form_data.WEBUI_URL
  638. request.app.state.config.ENABLE_SIGNUP = form_data.ENABLE_SIGNUP
  639. request.app.state.config.ENABLE_API_KEY = form_data.ENABLE_API_KEY
  640. request.app.state.config.ENABLE_API_KEY_ENDPOINT_RESTRICTIONS = (
  641. form_data.ENABLE_API_KEY_ENDPOINT_RESTRICTIONS
  642. )
  643. request.app.state.config.API_KEY_ALLOWED_ENDPOINTS = (
  644. form_data.API_KEY_ALLOWED_ENDPOINTS
  645. )
  646. request.app.state.config.ENABLE_CHANNELS = form_data.ENABLE_CHANNELS
  647. request.app.state.config.ENABLE_NOTES = form_data.ENABLE_NOTES
  648. if form_data.DEFAULT_USER_ROLE in ["pending", "user", "admin"]:
  649. request.app.state.config.DEFAULT_USER_ROLE = form_data.DEFAULT_USER_ROLE
  650. pattern = r"^(-1|0|(-?\d+(\.\d+)?)(ms|s|m|h|d|w))$"
  651. # Check if the input string matches the pattern
  652. if re.match(pattern, form_data.JWT_EXPIRES_IN):
  653. request.app.state.config.JWT_EXPIRES_IN = form_data.JWT_EXPIRES_IN
  654. request.app.state.config.ENABLE_COMMUNITY_SHARING = (
  655. form_data.ENABLE_COMMUNITY_SHARING
  656. )
  657. request.app.state.config.ENABLE_MESSAGE_RATING = form_data.ENABLE_MESSAGE_RATING
  658. request.app.state.config.ENABLE_USER_WEBHOOKS = form_data.ENABLE_USER_WEBHOOKS
  659. request.app.state.config.PENDING_USER_OVERLAY_TITLE = (
  660. form_data.PENDING_USER_OVERLAY_TITLE
  661. )
  662. request.app.state.config.PENDING_USER_OVERLAY_CONTENT = (
  663. form_data.PENDING_USER_OVERLAY_CONTENT
  664. )
  665. request.app.state.config.RESPONSE_WATERMARK = form_data.RESPONSE_WATERMARK
  666. return {
  667. "SHOW_ADMIN_DETAILS": request.app.state.config.SHOW_ADMIN_DETAILS,
  668. "WEBUI_URL": request.app.state.config.WEBUI_URL,
  669. "ENABLE_SIGNUP": request.app.state.config.ENABLE_SIGNUP,
  670. "ENABLE_API_KEY": request.app.state.config.ENABLE_API_KEY,
  671. "ENABLE_API_KEY_ENDPOINT_RESTRICTIONS": request.app.state.config.ENABLE_API_KEY_ENDPOINT_RESTRICTIONS,
  672. "API_KEY_ALLOWED_ENDPOINTS": request.app.state.config.API_KEY_ALLOWED_ENDPOINTS,
  673. "DEFAULT_USER_ROLE": request.app.state.config.DEFAULT_USER_ROLE,
  674. "JWT_EXPIRES_IN": request.app.state.config.JWT_EXPIRES_IN,
  675. "ENABLE_COMMUNITY_SHARING": request.app.state.config.ENABLE_COMMUNITY_SHARING,
  676. "ENABLE_MESSAGE_RATING": request.app.state.config.ENABLE_MESSAGE_RATING,
  677. "ENABLE_CHANNELS": request.app.state.config.ENABLE_CHANNELS,
  678. "ENABLE_NOTES": request.app.state.config.ENABLE_NOTES,
  679. "ENABLE_USER_WEBHOOKS": request.app.state.config.ENABLE_USER_WEBHOOKS,
  680. "PENDING_USER_OVERLAY_TITLE": request.app.state.config.PENDING_USER_OVERLAY_TITLE,
  681. "PENDING_USER_OVERLAY_CONTENT": request.app.state.config.PENDING_USER_OVERLAY_CONTENT,
  682. "RESPONSE_WATERMARK": request.app.state.config.RESPONSE_WATERMARK,
  683. }
  684. class LdapServerConfig(BaseModel):
  685. label: str
  686. host: str
  687. port: Optional[int] = None
  688. attribute_for_mail: str = "mail"
  689. attribute_for_username: str = "uid"
  690. app_dn: str
  691. app_dn_password: str
  692. search_base: str
  693. search_filters: str = ""
  694. use_tls: bool = True
  695. certificate_path: Optional[str] = None
  696. validate_cert: bool = True
  697. ciphers: Optional[str] = "ALL"
  698. @router.get("/admin/config/ldap/server", response_model=LdapServerConfig)
  699. async def get_ldap_server(request: Request, user=Depends(get_admin_user)):
  700. return {
  701. "label": request.app.state.config.LDAP_SERVER_LABEL,
  702. "host": request.app.state.config.LDAP_SERVER_HOST,
  703. "port": request.app.state.config.LDAP_SERVER_PORT,
  704. "attribute_for_mail": request.app.state.config.LDAP_ATTRIBUTE_FOR_MAIL,
  705. "attribute_for_username": request.app.state.config.LDAP_ATTRIBUTE_FOR_USERNAME,
  706. "app_dn": request.app.state.config.LDAP_APP_DN,
  707. "app_dn_password": request.app.state.config.LDAP_APP_PASSWORD,
  708. "search_base": request.app.state.config.LDAP_SEARCH_BASE,
  709. "search_filters": request.app.state.config.LDAP_SEARCH_FILTERS,
  710. "use_tls": request.app.state.config.LDAP_USE_TLS,
  711. "certificate_path": request.app.state.config.LDAP_CA_CERT_FILE,
  712. "validate_cert": request.app.state.config.LDAP_VALIDATE_CERT,
  713. "ciphers": request.app.state.config.LDAP_CIPHERS,
  714. }
  715. @router.post("/admin/config/ldap/server")
  716. async def update_ldap_server(
  717. request: Request, form_data: LdapServerConfig, user=Depends(get_admin_user)
  718. ):
  719. required_fields = [
  720. "label",
  721. "host",
  722. "attribute_for_mail",
  723. "attribute_for_username",
  724. "app_dn",
  725. "app_dn_password",
  726. "search_base",
  727. ]
  728. for key in required_fields:
  729. value = getattr(form_data, key)
  730. if not value:
  731. raise HTTPException(400, detail=f"Required field {key} is empty")
  732. request.app.state.config.LDAP_SERVER_LABEL = form_data.label
  733. request.app.state.config.LDAP_SERVER_HOST = form_data.host
  734. request.app.state.config.LDAP_SERVER_PORT = form_data.port
  735. request.app.state.config.LDAP_ATTRIBUTE_FOR_MAIL = form_data.attribute_for_mail
  736. request.app.state.config.LDAP_ATTRIBUTE_FOR_USERNAME = (
  737. form_data.attribute_for_username
  738. )
  739. request.app.state.config.LDAP_APP_DN = form_data.app_dn
  740. request.app.state.config.LDAP_APP_PASSWORD = form_data.app_dn_password
  741. request.app.state.config.LDAP_SEARCH_BASE = form_data.search_base
  742. request.app.state.config.LDAP_SEARCH_FILTERS = form_data.search_filters
  743. request.app.state.config.LDAP_USE_TLS = form_data.use_tls
  744. request.app.state.config.LDAP_CA_CERT_FILE = form_data.certificate_path
  745. request.app.state.config.LDAP_VALIDATE_CERT = form_data.validate_cert
  746. request.app.state.config.LDAP_CIPHERS = form_data.ciphers
  747. return {
  748. "label": request.app.state.config.LDAP_SERVER_LABEL,
  749. "host": request.app.state.config.LDAP_SERVER_HOST,
  750. "port": request.app.state.config.LDAP_SERVER_PORT,
  751. "attribute_for_mail": request.app.state.config.LDAP_ATTRIBUTE_FOR_MAIL,
  752. "attribute_for_username": request.app.state.config.LDAP_ATTRIBUTE_FOR_USERNAME,
  753. "app_dn": request.app.state.config.LDAP_APP_DN,
  754. "app_dn_password": request.app.state.config.LDAP_APP_PASSWORD,
  755. "search_base": request.app.state.config.LDAP_SEARCH_BASE,
  756. "search_filters": request.app.state.config.LDAP_SEARCH_FILTERS,
  757. "use_tls": request.app.state.config.LDAP_USE_TLS,
  758. "certificate_path": request.app.state.config.LDAP_CA_CERT_FILE,
  759. "validate_cert": request.app.state.config.LDAP_VALIDATE_CERT,
  760. "ciphers": request.app.state.config.LDAP_CIPHERS,
  761. }
  762. @router.get("/admin/config/ldap")
  763. async def get_ldap_config(request: Request, user=Depends(get_admin_user)):
  764. return {"ENABLE_LDAP": request.app.state.config.ENABLE_LDAP}
  765. class LdapConfigForm(BaseModel):
  766. enable_ldap: Optional[bool] = None
  767. @router.post("/admin/config/ldap")
  768. async def update_ldap_config(
  769. request: Request, form_data: LdapConfigForm, user=Depends(get_admin_user)
  770. ):
  771. request.app.state.config.ENABLE_LDAP = form_data.enable_ldap
  772. return {"ENABLE_LDAP": request.app.state.config.ENABLE_LDAP}
  773. ############################
  774. # API Key
  775. ############################
  776. # create api key
  777. @router.post("/api_key", response_model=ApiKey)
  778. async def generate_api_key(request: Request, user=Depends(get_current_user)):
  779. if not request.app.state.config.ENABLE_API_KEY:
  780. raise HTTPException(
  781. status.HTTP_403_FORBIDDEN,
  782. detail=ERROR_MESSAGES.API_KEY_CREATION_NOT_ALLOWED,
  783. )
  784. api_key = create_api_key()
  785. success = Users.update_user_api_key_by_id(user.id, api_key)
  786. if success:
  787. return {
  788. "api_key": api_key,
  789. }
  790. else:
  791. raise HTTPException(500, detail=ERROR_MESSAGES.CREATE_API_KEY_ERROR)
  792. # delete api key
  793. @router.delete("/api_key", response_model=bool)
  794. async def delete_api_key(user=Depends(get_current_user)):
  795. success = Users.update_user_api_key_by_id(user.id, None)
  796. return success
  797. # get api key
  798. @router.get("/api_key", response_model=ApiKey)
  799. async def get_api_key(user=Depends(get_current_user)):
  800. api_key = Users.get_user_api_key_by_id(user.id)
  801. if api_key:
  802. return {
  803. "api_key": api_key,
  804. }
  805. else:
  806. raise HTTPException(404, detail=ERROR_MESSAGES.API_KEY_NOT_FOUND)