auths.py 33 KB

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