auths.py 38 KB

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