auths.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050
  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. if ENABLE_OAUTH_SIGNUP.value:
  566. oauth_id_token = request.cookies.get("oauth_id_token")
  567. if oauth_id_token:
  568. try:
  569. async with ClientSession() as session:
  570. async with session.get(OPENID_PROVIDER_URL.value) as resp:
  571. if resp.status == 200:
  572. openid_data = await resp.json()
  573. logout_url = openid_data.get("end_session_endpoint")
  574. if logout_url:
  575. response.delete_cookie("oauth_id_token")
  576. return JSONResponse(
  577. status_code=200,
  578. content={
  579. "status": True,
  580. "redirect_url": f"{logout_url}?id_token_hint={oauth_id_token}",
  581. },
  582. headers=response.headers,
  583. )
  584. else:
  585. raise HTTPException(
  586. status_code=resp.status,
  587. detail="Failed to fetch OpenID configuration",
  588. )
  589. except Exception as e:
  590. log.error(f"OpenID signout error: {str(e)}")
  591. raise HTTPException(
  592. status_code=500,
  593. detail="Failed to sign out from the OpenID provider.",
  594. )
  595. if WEBUI_AUTH_SIGNOUT_REDIRECT_URL:
  596. return JSONResponse(
  597. status_code=200,
  598. content={
  599. "status": True,
  600. "redirect_url": WEBUI_AUTH_SIGNOUT_REDIRECT_URL,
  601. },
  602. headers=response.headers,
  603. )
  604. return JSONResponse(
  605. status_code=200, content={"status": True}, headers=response.headers
  606. )
  607. ############################
  608. # AddUser
  609. ############################
  610. @router.post("/add", response_model=SigninResponse)
  611. async def add_user(form_data: AddUserForm, user=Depends(get_admin_user)):
  612. if not validate_email_format(form_data.email.lower()):
  613. raise HTTPException(
  614. status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.INVALID_EMAIL_FORMAT
  615. )
  616. if Users.get_user_by_email(form_data.email.lower()):
  617. raise HTTPException(400, detail=ERROR_MESSAGES.EMAIL_TAKEN)
  618. try:
  619. hashed = get_password_hash(form_data.password)
  620. user = Auths.insert_new_auth(
  621. form_data.email.lower(),
  622. hashed,
  623. form_data.name,
  624. form_data.profile_image_url,
  625. form_data.role,
  626. )
  627. if user:
  628. token = create_token(data={"id": user.id})
  629. return {
  630. "token": token,
  631. "token_type": "Bearer",
  632. "id": user.id,
  633. "email": user.email,
  634. "name": user.name,
  635. "role": user.role,
  636. "profile_image_url": user.profile_image_url,
  637. }
  638. else:
  639. raise HTTPException(500, detail=ERROR_MESSAGES.CREATE_USER_ERROR)
  640. except Exception as err:
  641. log.error(f"Add user error: {str(err)}")
  642. raise HTTPException(
  643. 500, detail="An internal error occurred while adding the user."
  644. )
  645. ############################
  646. # GetAdminDetails
  647. ############################
  648. @router.get("/admin/details")
  649. async def get_admin_details(request: Request, user=Depends(get_current_user)):
  650. if request.app.state.config.SHOW_ADMIN_DETAILS:
  651. admin_email = request.app.state.config.ADMIN_EMAIL
  652. admin_name = None
  653. log.info(f"Admin details - Email: {admin_email}, Name: {admin_name}")
  654. if admin_email:
  655. admin = Users.get_user_by_email(admin_email)
  656. if admin:
  657. admin_name = admin.name
  658. else:
  659. admin = Users.get_first_user()
  660. if admin:
  661. admin_email = admin.email
  662. admin_name = admin.name
  663. return {
  664. "name": admin_name,
  665. "email": admin_email,
  666. }
  667. else:
  668. raise HTTPException(400, detail=ERROR_MESSAGES.ACTION_PROHIBITED)
  669. ############################
  670. # ToggleSignUp
  671. ############################
  672. @router.get("/admin/config")
  673. async def get_admin_config(request: Request, user=Depends(get_admin_user)):
  674. return {
  675. "SHOW_ADMIN_DETAILS": request.app.state.config.SHOW_ADMIN_DETAILS,
  676. "WEBUI_URL": request.app.state.config.WEBUI_URL,
  677. "ENABLE_SIGNUP": request.app.state.config.ENABLE_SIGNUP,
  678. "ENABLE_API_KEY": request.app.state.config.ENABLE_API_KEY,
  679. "ENABLE_API_KEY_ENDPOINT_RESTRICTIONS": request.app.state.config.ENABLE_API_KEY_ENDPOINT_RESTRICTIONS,
  680. "API_KEY_ALLOWED_ENDPOINTS": request.app.state.config.API_KEY_ALLOWED_ENDPOINTS,
  681. "DEFAULT_USER_ROLE": request.app.state.config.DEFAULT_USER_ROLE,
  682. "JWT_EXPIRES_IN": request.app.state.config.JWT_EXPIRES_IN,
  683. "ENABLE_COMMUNITY_SHARING": request.app.state.config.ENABLE_COMMUNITY_SHARING,
  684. "ENABLE_MESSAGE_RATING": request.app.state.config.ENABLE_MESSAGE_RATING,
  685. "ENABLE_CHANNELS": request.app.state.config.ENABLE_CHANNELS,
  686. "ENABLE_NOTES": request.app.state.config.ENABLE_NOTES,
  687. "ENABLE_USER_WEBHOOKS": request.app.state.config.ENABLE_USER_WEBHOOKS,
  688. "PENDING_USER_OVERLAY_TITLE": request.app.state.config.PENDING_USER_OVERLAY_TITLE,
  689. "PENDING_USER_OVERLAY_CONTENT": request.app.state.config.PENDING_USER_OVERLAY_CONTENT,
  690. "RESPONSE_WATERMARK": request.app.state.config.RESPONSE_WATERMARK,
  691. }
  692. class AdminConfig(BaseModel):
  693. SHOW_ADMIN_DETAILS: bool
  694. WEBUI_URL: str
  695. ENABLE_SIGNUP: bool
  696. ENABLE_API_KEY: bool
  697. ENABLE_API_KEY_ENDPOINT_RESTRICTIONS: bool
  698. API_KEY_ALLOWED_ENDPOINTS: str
  699. DEFAULT_USER_ROLE: str
  700. JWT_EXPIRES_IN: str
  701. ENABLE_COMMUNITY_SHARING: bool
  702. ENABLE_MESSAGE_RATING: bool
  703. ENABLE_CHANNELS: bool
  704. ENABLE_NOTES: bool
  705. ENABLE_USER_WEBHOOKS: bool
  706. PENDING_USER_OVERLAY_TITLE: Optional[str] = None
  707. PENDING_USER_OVERLAY_CONTENT: Optional[str] = None
  708. RESPONSE_WATERMARK: Optional[str] = None
  709. @router.post("/admin/config")
  710. async def update_admin_config(
  711. request: Request, form_data: AdminConfig, user=Depends(get_admin_user)
  712. ):
  713. request.app.state.config.SHOW_ADMIN_DETAILS = form_data.SHOW_ADMIN_DETAILS
  714. request.app.state.config.WEBUI_URL = form_data.WEBUI_URL
  715. request.app.state.config.ENABLE_SIGNUP = form_data.ENABLE_SIGNUP
  716. request.app.state.config.ENABLE_API_KEY = form_data.ENABLE_API_KEY
  717. request.app.state.config.ENABLE_API_KEY_ENDPOINT_RESTRICTIONS = (
  718. form_data.ENABLE_API_KEY_ENDPOINT_RESTRICTIONS
  719. )
  720. request.app.state.config.API_KEY_ALLOWED_ENDPOINTS = (
  721. form_data.API_KEY_ALLOWED_ENDPOINTS
  722. )
  723. request.app.state.config.ENABLE_CHANNELS = form_data.ENABLE_CHANNELS
  724. request.app.state.config.ENABLE_NOTES = form_data.ENABLE_NOTES
  725. if form_data.DEFAULT_USER_ROLE in ["pending", "user", "admin"]:
  726. request.app.state.config.DEFAULT_USER_ROLE = form_data.DEFAULT_USER_ROLE
  727. pattern = r"^(-1|0|(-?\d+(\.\d+)?)(ms|s|m|h|d|w))$"
  728. # Check if the input string matches the pattern
  729. if re.match(pattern, form_data.JWT_EXPIRES_IN):
  730. request.app.state.config.JWT_EXPIRES_IN = form_data.JWT_EXPIRES_IN
  731. request.app.state.config.ENABLE_COMMUNITY_SHARING = (
  732. form_data.ENABLE_COMMUNITY_SHARING
  733. )
  734. request.app.state.config.ENABLE_MESSAGE_RATING = form_data.ENABLE_MESSAGE_RATING
  735. request.app.state.config.ENABLE_USER_WEBHOOKS = form_data.ENABLE_USER_WEBHOOKS
  736. request.app.state.config.PENDING_USER_OVERLAY_TITLE = (
  737. form_data.PENDING_USER_OVERLAY_TITLE
  738. )
  739. request.app.state.config.PENDING_USER_OVERLAY_CONTENT = (
  740. form_data.PENDING_USER_OVERLAY_CONTENT
  741. )
  742. request.app.state.config.RESPONSE_WATERMARK = form_data.RESPONSE_WATERMARK
  743. return {
  744. "SHOW_ADMIN_DETAILS": request.app.state.config.SHOW_ADMIN_DETAILS,
  745. "WEBUI_URL": request.app.state.config.WEBUI_URL,
  746. "ENABLE_SIGNUP": request.app.state.config.ENABLE_SIGNUP,
  747. "ENABLE_API_KEY": request.app.state.config.ENABLE_API_KEY,
  748. "ENABLE_API_KEY_ENDPOINT_RESTRICTIONS": request.app.state.config.ENABLE_API_KEY_ENDPOINT_RESTRICTIONS,
  749. "API_KEY_ALLOWED_ENDPOINTS": request.app.state.config.API_KEY_ALLOWED_ENDPOINTS,
  750. "DEFAULT_USER_ROLE": request.app.state.config.DEFAULT_USER_ROLE,
  751. "JWT_EXPIRES_IN": request.app.state.config.JWT_EXPIRES_IN,
  752. "ENABLE_COMMUNITY_SHARING": request.app.state.config.ENABLE_COMMUNITY_SHARING,
  753. "ENABLE_MESSAGE_RATING": request.app.state.config.ENABLE_MESSAGE_RATING,
  754. "ENABLE_CHANNELS": request.app.state.config.ENABLE_CHANNELS,
  755. "ENABLE_NOTES": request.app.state.config.ENABLE_NOTES,
  756. "ENABLE_USER_WEBHOOKS": request.app.state.config.ENABLE_USER_WEBHOOKS,
  757. "PENDING_USER_OVERLAY_TITLE": request.app.state.config.PENDING_USER_OVERLAY_TITLE,
  758. "PENDING_USER_OVERLAY_CONTENT": request.app.state.config.PENDING_USER_OVERLAY_CONTENT,
  759. "RESPONSE_WATERMARK": request.app.state.config.RESPONSE_WATERMARK,
  760. }
  761. class LdapServerConfig(BaseModel):
  762. label: str
  763. host: str
  764. port: Optional[int] = None
  765. attribute_for_mail: str = "mail"
  766. attribute_for_username: str = "uid"
  767. app_dn: str
  768. app_dn_password: str
  769. search_base: str
  770. search_filters: str = ""
  771. use_tls: bool = True
  772. certificate_path: Optional[str] = None
  773. validate_cert: bool = True
  774. ciphers: Optional[str] = "ALL"
  775. @router.get("/admin/config/ldap/server", response_model=LdapServerConfig)
  776. async def get_ldap_server(request: Request, user=Depends(get_admin_user)):
  777. return {
  778. "label": request.app.state.config.LDAP_SERVER_LABEL,
  779. "host": request.app.state.config.LDAP_SERVER_HOST,
  780. "port": request.app.state.config.LDAP_SERVER_PORT,
  781. "attribute_for_mail": request.app.state.config.LDAP_ATTRIBUTE_FOR_MAIL,
  782. "attribute_for_username": request.app.state.config.LDAP_ATTRIBUTE_FOR_USERNAME,
  783. "app_dn": request.app.state.config.LDAP_APP_DN,
  784. "app_dn_password": request.app.state.config.LDAP_APP_PASSWORD,
  785. "search_base": request.app.state.config.LDAP_SEARCH_BASE,
  786. "search_filters": request.app.state.config.LDAP_SEARCH_FILTERS,
  787. "use_tls": request.app.state.config.LDAP_USE_TLS,
  788. "certificate_path": request.app.state.config.LDAP_CA_CERT_FILE,
  789. "validate_cert": request.app.state.config.LDAP_VALIDATE_CERT,
  790. "ciphers": request.app.state.config.LDAP_CIPHERS,
  791. }
  792. @router.post("/admin/config/ldap/server")
  793. async def update_ldap_server(
  794. request: Request, form_data: LdapServerConfig, user=Depends(get_admin_user)
  795. ):
  796. required_fields = [
  797. "label",
  798. "host",
  799. "attribute_for_mail",
  800. "attribute_for_username",
  801. "app_dn",
  802. "app_dn_password",
  803. "search_base",
  804. ]
  805. for key in required_fields:
  806. value = getattr(form_data, key)
  807. if not value:
  808. raise HTTPException(400, detail=f"Required field {key} is empty")
  809. request.app.state.config.LDAP_SERVER_LABEL = form_data.label
  810. request.app.state.config.LDAP_SERVER_HOST = form_data.host
  811. request.app.state.config.LDAP_SERVER_PORT = form_data.port
  812. request.app.state.config.LDAP_ATTRIBUTE_FOR_MAIL = form_data.attribute_for_mail
  813. request.app.state.config.LDAP_ATTRIBUTE_FOR_USERNAME = (
  814. form_data.attribute_for_username
  815. )
  816. request.app.state.config.LDAP_APP_DN = form_data.app_dn
  817. request.app.state.config.LDAP_APP_PASSWORD = form_data.app_dn_password
  818. request.app.state.config.LDAP_SEARCH_BASE = form_data.search_base
  819. request.app.state.config.LDAP_SEARCH_FILTERS = form_data.search_filters
  820. request.app.state.config.LDAP_USE_TLS = form_data.use_tls
  821. request.app.state.config.LDAP_CA_CERT_FILE = form_data.certificate_path
  822. request.app.state.config.LDAP_VALIDATE_CERT = form_data.validate_cert
  823. request.app.state.config.LDAP_CIPHERS = form_data.ciphers
  824. return {
  825. "label": request.app.state.config.LDAP_SERVER_LABEL,
  826. "host": request.app.state.config.LDAP_SERVER_HOST,
  827. "port": request.app.state.config.LDAP_SERVER_PORT,
  828. "attribute_for_mail": request.app.state.config.LDAP_ATTRIBUTE_FOR_MAIL,
  829. "attribute_for_username": request.app.state.config.LDAP_ATTRIBUTE_FOR_USERNAME,
  830. "app_dn": request.app.state.config.LDAP_APP_DN,
  831. "app_dn_password": request.app.state.config.LDAP_APP_PASSWORD,
  832. "search_base": request.app.state.config.LDAP_SEARCH_BASE,
  833. "search_filters": request.app.state.config.LDAP_SEARCH_FILTERS,
  834. "use_tls": request.app.state.config.LDAP_USE_TLS,
  835. "certificate_path": request.app.state.config.LDAP_CA_CERT_FILE,
  836. "validate_cert": request.app.state.config.LDAP_VALIDATE_CERT,
  837. "ciphers": request.app.state.config.LDAP_CIPHERS,
  838. }
  839. @router.get("/admin/config/ldap")
  840. async def get_ldap_config(request: Request, user=Depends(get_admin_user)):
  841. return {"ENABLE_LDAP": request.app.state.config.ENABLE_LDAP}
  842. class LdapConfigForm(BaseModel):
  843. enable_ldap: Optional[bool] = None
  844. @router.post("/admin/config/ldap")
  845. async def update_ldap_config(
  846. request: Request, form_data: LdapConfigForm, user=Depends(get_admin_user)
  847. ):
  848. request.app.state.config.ENABLE_LDAP = form_data.enable_ldap
  849. return {"ENABLE_LDAP": request.app.state.config.ENABLE_LDAP}
  850. ############################
  851. # API Key
  852. ############################
  853. # create api key
  854. @router.post("/api_key", response_model=ApiKey)
  855. async def generate_api_key(request: Request, user=Depends(get_current_user)):
  856. if not request.app.state.config.ENABLE_API_KEY:
  857. raise HTTPException(
  858. status.HTTP_403_FORBIDDEN,
  859. detail=ERROR_MESSAGES.API_KEY_CREATION_NOT_ALLOWED,
  860. )
  861. api_key = create_api_key()
  862. success = Users.update_user_api_key_by_id(user.id, api_key)
  863. if success:
  864. return {
  865. "api_key": api_key,
  866. }
  867. else:
  868. raise HTTPException(500, detail=ERROR_MESSAGES.CREATE_API_KEY_ERROR)
  869. # delete api key
  870. @router.delete("/api_key", response_model=bool)
  871. async def delete_api_key(user=Depends(get_current_user)):
  872. success = Users.update_user_api_key_by_id(user.id, None)
  873. return success
  874. # get api key
  875. @router.get("/api_key", response_model=ApiKey)
  876. async def get_api_key(user=Depends(get_current_user)):
  877. api_key = Users.get_user_api_key_by_id(user.id)
  878. if api_key:
  879. return {
  880. "api_key": api_key,
  881. }
  882. else:
  883. raise HTTPException(404, detail=ERROR_MESSAGES.API_KEY_NOT_FOUND)