auths.py 38 KB

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