auths.py 38 KB

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