auths.py 38 KB

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