users_router.py 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534
  1. import textwrap
  2. from typing import Optional
  3. from uuid import UUID
  4. from fastapi import Body, Depends, Path, Query
  5. from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
  6. from pydantic import EmailStr
  7. from core.base import R2RException
  8. from core.base.api.models import (
  9. GenericBooleanResponse,
  10. GenericMessageResponse,
  11. WrappedAPIKeyResponse,
  12. WrappedAPIKeysResponse,
  13. WrappedBooleanResponse,
  14. WrappedCollectionsResponse,
  15. WrappedGenericMessageResponse,
  16. WrappedTokenResponse,
  17. WrappedUserResponse,
  18. WrappedUsersResponse,
  19. )
  20. from ...abstractions import R2RProviders, R2RServices
  21. from .base_router import BaseRouterV3
  22. oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
  23. class UsersRouter(BaseRouterV3):
  24. def __init__(self, providers: R2RProviders, services: R2RServices):
  25. super().__init__(providers, services)
  26. def _setup_routes(self):
  27. @self.router.post(
  28. "/users",
  29. # dependencies=[Depends(self.rate_limit_dependency)],
  30. response_model=WrappedUserResponse,
  31. openapi_extra={
  32. "x-codeSamples": [
  33. {
  34. "lang": "Python",
  35. "source": textwrap.dedent(
  36. """
  37. from r2r import R2RClient
  38. client = R2RClient("http://localhost:7272")
  39. new_user = client.users.create(
  40. email="jane.doe@example.com",
  41. password="secure_password123"
  42. )"""
  43. ),
  44. },
  45. {
  46. "lang": "JavaScript",
  47. "source": textwrap.dedent(
  48. """
  49. const { r2rClient } = require("r2r-js");
  50. const client = new r2rClient("http://localhost:7272");
  51. function main() {
  52. const response = await client.users.create({
  53. email: "jane.doe@example.com",
  54. password: "secure_password123"
  55. });
  56. }
  57. main();
  58. """
  59. ),
  60. },
  61. {
  62. "lang": "CLI",
  63. "source": textwrap.dedent(
  64. """
  65. r2r users create jane.doe@example.com secure_password123
  66. """
  67. ),
  68. },
  69. {
  70. "lang": "cURL",
  71. "source": textwrap.dedent(
  72. """
  73. curl -X POST "https://api.example.com/v3/users" \\
  74. -H "Content-Type: application/json" \\
  75. -d '{
  76. "email": "jane.doe@example.com",
  77. "password": "secure_password123"
  78. }'"""
  79. ),
  80. },
  81. ]
  82. },
  83. )
  84. @self.base_endpoint
  85. async def register(
  86. email: EmailStr = Body(..., description="User's email address"),
  87. password: str = Body(..., description="User's password"),
  88. name: str | None = Body(
  89. None, description="The name for the new user"
  90. ),
  91. bio: str | None = Body(
  92. None, description="The bio for the new user"
  93. ),
  94. profile_picture: str | None = Body(
  95. None, description="Updated user profile picture"
  96. ),
  97. # auth_user=Depends(self.providers.auth.auth_wrapper()),
  98. ) -> WrappedUserResponse:
  99. """Register a new user with the given email and password."""
  100. # TODO: Do we really want this validation? The default password for the superuser would not pass...
  101. def validate_password(password: str) -> bool:
  102. if len(password) < 10:
  103. return False
  104. if not any(c.isupper() for c in password):
  105. return False
  106. if not any(c.islower() for c in password):
  107. return False
  108. if not any(c.isdigit() for c in password):
  109. return False
  110. if not any(c in "!@#$%^&*" for c in password):
  111. return False
  112. return True
  113. validate_password(password)
  114. registration_response = await self.services.auth.register(
  115. email, password
  116. )
  117. if name or bio or profile_picture:
  118. return await self.services.auth.update_user(
  119. user_id=registration_response.id,
  120. name=name,
  121. bio=bio,
  122. profile_picture=profile_picture,
  123. )
  124. return registration_response
  125. # TODO: deprecated, remove in next release
  126. @self.router.post(
  127. "/users/register",
  128. # dependencies=[Depends(self.rate_limit_dependency)],
  129. response_model=WrappedUserResponse,
  130. openapi_extra={
  131. "x-codeSamples": [
  132. {
  133. "lang": "Python",
  134. "source": textwrap.dedent(
  135. """
  136. from r2r import R2RClient
  137. client = R2RClient("http://localhost:7272")
  138. new_user = client.users.register(
  139. email="jane.doe@example.com",
  140. password="secure_password123"
  141. )"""
  142. ),
  143. },
  144. {
  145. "lang": "JavaScript",
  146. "source": textwrap.dedent(
  147. """
  148. const { r2rClient } = require("r2r-js");
  149. const client = new r2rClient("http://localhost:7272");
  150. function main() {
  151. const response = await client.users.register({
  152. email: "jane.doe@example.com",
  153. password: "secure_password123"
  154. });
  155. }
  156. main();
  157. """
  158. ),
  159. },
  160. {
  161. "lang": "CLI",
  162. "source": textwrap.dedent(
  163. """
  164. r2r users register jane.doe@example.com secure_password123
  165. """
  166. ),
  167. },
  168. {
  169. "lang": "cURL",
  170. "source": textwrap.dedent(
  171. """
  172. curl -X POST "https://api.example.com/v3/users/register" \\
  173. -H "Content-Type: application/json" \\
  174. -d '{
  175. "email": "jane.doe@example.com",
  176. "password": "secure_password123"
  177. }'"""
  178. ),
  179. },
  180. ]
  181. },
  182. )
  183. @self.base_endpoint
  184. async def register(
  185. email: EmailStr = Body(..., description="User's email address"),
  186. password: str = Body(..., description="User's password"),
  187. ):
  188. """Register a new user with the given email and password."""
  189. return await self.services.auth.register(email, password)
  190. @self.router.post(
  191. "/users/verify-email",
  192. # dependencies=[Depends(self.rate_limit_dependency)],
  193. response_model=WrappedGenericMessageResponse,
  194. openapi_extra={
  195. "x-codeSamples": [
  196. {
  197. "lang": "Python",
  198. "source": textwrap.dedent(
  199. """
  200. from r2r import R2RClient
  201. client = R2RClient("http://localhost:7272")
  202. tokens = client.users.verify_email(
  203. email="jane.doe@example.com",
  204. verification_code="1lklwal!awdclm"
  205. )"""
  206. ),
  207. },
  208. {
  209. "lang": "JavaScript",
  210. "source": textwrap.dedent(
  211. """
  212. const { r2rClient } = require("r2r-js");
  213. const client = new r2rClient("http://localhost:7272");
  214. function main() {
  215. const response = await client.users.verifyEmail({
  216. email: jane.doe@example.com",
  217. verificationCode: "1lklwal!awdclm"
  218. });
  219. }
  220. main();
  221. """
  222. ),
  223. },
  224. {
  225. "lang": "cURL",
  226. "source": textwrap.dedent(
  227. """
  228. curl -X POST "https://api.example.com/v3/users/login" \\
  229. -H "Content-Type: application/x-www-form-urlencoded" \\
  230. -d "email=jane.doe@example.com&verification_code=1lklwal!awdclm"
  231. """
  232. ),
  233. },
  234. ]
  235. },
  236. )
  237. @self.base_endpoint
  238. async def verify_email(
  239. email: EmailStr = Body(..., description="User's email address"),
  240. verification_code: str = Body(
  241. ..., description="Email verification code"
  242. ),
  243. ) -> WrappedGenericMessageResponse:
  244. """Verify a user's email address."""
  245. user = (
  246. await self.providers.database.users_handler.get_user_by_email(
  247. email
  248. )
  249. )
  250. if user and user.is_verified:
  251. raise R2RException(
  252. status_code=400,
  253. message="This email is already verified. Please log in.",
  254. )
  255. result = await self.services.auth.verify_email(
  256. email, verification_code
  257. )
  258. return GenericMessageResponse(message=result["message"]) # type: ignore
  259. @self.router.post(
  260. "/users/login",
  261. # dependencies=[Depends(self.rate_limit_dependency)],
  262. response_model=WrappedTokenResponse,
  263. openapi_extra={
  264. "x-codeSamples": [
  265. {
  266. "lang": "Python",
  267. "source": textwrap.dedent(
  268. """
  269. from r2r import R2RClient
  270. client = R2RClient("http://localhost:7272")
  271. tokens = client.users.login(
  272. email="jane.doe@example.com",
  273. password="secure_password123"
  274. )
  275. """
  276. ),
  277. },
  278. {
  279. "lang": "JavaScript",
  280. "source": textwrap.dedent(
  281. """
  282. const { r2rClient } = require("r2r-js");
  283. const client = new r2rClient("http://localhost:7272");
  284. function main() {
  285. const response = await client.users.login({
  286. email: jane.doe@example.com",
  287. password: "secure_password123"
  288. });
  289. }
  290. main();
  291. """
  292. ),
  293. },
  294. {
  295. "lang": "cURL",
  296. "source": textwrap.dedent(
  297. """
  298. curl -X POST "https://api.example.com/v3/users/login" \\
  299. -H "Content-Type: application/x-www-form-urlencoded" \\
  300. -d "username=jane.doe@example.com&password=secure_password123"
  301. """
  302. ),
  303. },
  304. ]
  305. },
  306. )
  307. @self.base_endpoint
  308. async def login(form_data: OAuth2PasswordRequestForm = Depends()):
  309. """Authenticate a user and provide access tokens."""
  310. return await self.services.auth.login(
  311. form_data.username, form_data.password
  312. )
  313. @self.router.post(
  314. "/users/logout",
  315. response_model=WrappedGenericMessageResponse,
  316. openapi_extra={
  317. "x-codeSamples": [
  318. {
  319. "lang": "Python",
  320. "source": textwrap.dedent(
  321. """
  322. from r2r import R2RClient
  323. client = R2RClient("http://localhost:7272")
  324. # client.login(...)
  325. result = client.users.logout()
  326. """
  327. ),
  328. },
  329. {
  330. "lang": "JavaScript",
  331. "source": textwrap.dedent(
  332. """
  333. const { r2rClient } = require("r2r-js");
  334. const client = new r2rClient("http://localhost:7272");
  335. function main() {
  336. const response = await client.users.logout();
  337. }
  338. main();
  339. """
  340. ),
  341. },
  342. {
  343. "lang": "cURL",
  344. "source": textwrap.dedent(
  345. """
  346. curl -X POST "https://api.example.com/v3/users/logout" \\
  347. -H "Authorization: Bearer YOUR_API_KEY"
  348. """
  349. ),
  350. },
  351. ]
  352. },
  353. )
  354. @self.base_endpoint
  355. async def logout(
  356. token: str = Depends(oauth2_scheme),
  357. auth_user=Depends(self.providers.auth.auth_wrapper()),
  358. ) -> WrappedGenericMessageResponse:
  359. """Log out the current user."""
  360. result = await self.services.auth.logout(token)
  361. return GenericMessageResponse(message=result["message"]) # type: ignore
  362. @self.router.post(
  363. "/users/refresh-token",
  364. dependencies=[Depends(self.rate_limit_dependency)],
  365. openapi_extra={
  366. "x-codeSamples": [
  367. {
  368. "lang": "Python",
  369. "source": textwrap.dedent(
  370. """
  371. from r2r import R2RClient
  372. client = R2RClient("http://localhost:7272")
  373. # client.login(...)
  374. new_tokens = client.users.refresh_token()
  375. # New tokens are automatically stored in the client"""
  376. ),
  377. },
  378. {
  379. "lang": "JavaScript",
  380. "source": textwrap.dedent(
  381. """
  382. const { r2rClient } = require("r2r-js");
  383. const client = new r2rClient("http://localhost:7272");
  384. function main() {
  385. const response = await client.users.refreshAccessToken();
  386. }
  387. main();
  388. """
  389. ),
  390. },
  391. {
  392. "lang": "cURL",
  393. "source": textwrap.dedent(
  394. """
  395. curl -X POST "https://api.example.com/v3/users/refresh-token" \\
  396. -H "Content-Type: application/json" \\
  397. -d '{
  398. "refresh_token": "YOUR_REFRESH_TOKEN"
  399. }'"""
  400. ),
  401. },
  402. ]
  403. },
  404. )
  405. @self.base_endpoint
  406. async def refresh_token(
  407. refresh_token: str = Body(..., description="Refresh token")
  408. ) -> WrappedTokenResponse:
  409. """Refresh the access token using a refresh token."""
  410. result = await self.services.auth.refresh_access_token(
  411. refresh_token=refresh_token
  412. )
  413. return result
  414. @self.router.post(
  415. "/users/change-password",
  416. dependencies=[Depends(self.rate_limit_dependency)],
  417. response_model=WrappedGenericMessageResponse,
  418. openapi_extra={
  419. "x-codeSamples": [
  420. {
  421. "lang": "Python",
  422. "source": textwrap.dedent(
  423. """
  424. from r2r import R2RClient
  425. client = R2RClient("http://localhost:7272")
  426. # client.login(...)
  427. result = client.users.change_password(
  428. current_password="old_password123",
  429. new_password="new_secure_password456"
  430. )"""
  431. ),
  432. },
  433. {
  434. "lang": "JavaScript",
  435. "source": textwrap.dedent(
  436. """
  437. const { r2rClient } = require("r2r-js");
  438. const client = new r2rClient("http://localhost:7272");
  439. function main() {
  440. const response = await client.users.changePassword({
  441. currentPassword: "old_password123",
  442. newPassword: "new_secure_password456"
  443. });
  444. }
  445. main();
  446. """
  447. ),
  448. },
  449. {
  450. "lang": "cURL",
  451. "source": textwrap.dedent(
  452. """
  453. curl -X POST "https://api.example.com/v3/users/change-password" \\
  454. -H "Authorization: Bearer YOUR_API_KEY" \\
  455. -H "Content-Type: application/json" \\
  456. -d '{
  457. "current_password": "old_password123",
  458. "new_password": "new_secure_password456"
  459. }'"""
  460. ),
  461. },
  462. ]
  463. },
  464. )
  465. @self.base_endpoint
  466. async def change_password(
  467. current_password: str = Body(..., description="Current password"),
  468. new_password: str = Body(..., description="New password"),
  469. auth_user=Depends(self.providers.auth.auth_wrapper()),
  470. ) -> GenericMessageResponse:
  471. """Change the authenticated user's password."""
  472. result = await self.services.auth.change_password(
  473. auth_user, current_password, new_password
  474. )
  475. return GenericMessageResponse(message=result["message"]) # type: ignore
  476. @self.router.post(
  477. "/users/request-password-reset",
  478. dependencies=[
  479. Depends(self.providers.auth.auth_wrapper(public=True))
  480. ],
  481. response_model=WrappedGenericMessageResponse,
  482. openapi_extra={
  483. "x-codeSamples": [
  484. {
  485. "lang": "Python",
  486. "source": textwrap.dedent(
  487. """
  488. from r2r import R2RClient
  489. client = R2RClient("http://localhost:7272")
  490. result = client.users.request_password_reset(
  491. email="jane.doe@example.com"
  492. )"""
  493. ),
  494. },
  495. {
  496. "lang": "JavaScript",
  497. "source": textwrap.dedent(
  498. """
  499. const { r2rClient } = require("r2r-js");
  500. const client = new r2rClient("http://localhost:7272");
  501. function main() {
  502. const response = await client.users.requestPasswordReset({
  503. email: jane.doe@example.com",
  504. });
  505. }
  506. main();
  507. """
  508. ),
  509. },
  510. {
  511. "lang": "cURL",
  512. "source": textwrap.dedent(
  513. """
  514. curl -X POST "https://api.example.com/v3/users/request-password-reset" \\
  515. -H "Content-Type: application/json" \\
  516. -d '{
  517. "email": "jane.doe@example.com"
  518. }'"""
  519. ),
  520. },
  521. ]
  522. },
  523. )
  524. @self.base_endpoint
  525. async def request_password_reset(
  526. email: EmailStr = Body(..., description="User's email address"),
  527. ) -> WrappedGenericMessageResponse:
  528. """Request a password reset for a user."""
  529. result = await self.services.auth.request_password_reset(email)
  530. return GenericMessageResponse(message=result["message"]) # type: ignore
  531. @self.router.post(
  532. "/users/reset-password",
  533. dependencies=[Depends(self.rate_limit_dependency)],
  534. response_model=WrappedGenericMessageResponse,
  535. openapi_extra={
  536. "x-codeSamples": [
  537. {
  538. "lang": "Python",
  539. "source": textwrap.dedent(
  540. """
  541. from r2r import R2RClient
  542. client = R2RClient("http://localhost:7272")
  543. result = client.users.reset_password(
  544. reset_token="reset_token_received_via_email",
  545. new_password="new_secure_password789"
  546. )"""
  547. ),
  548. },
  549. {
  550. "lang": "JavaScript",
  551. "source": textwrap.dedent(
  552. """
  553. const { r2rClient } = require("r2r-js");
  554. const client = new r2rClient("http://localhost:7272");
  555. function main() {
  556. const response = await client.users.resetPassword({
  557. resestToken: "reset_token_received_via_email",
  558. newPassword: "new_secure_password789"
  559. });
  560. }
  561. main();
  562. """
  563. ),
  564. },
  565. {
  566. "lang": "cURL",
  567. "source": textwrap.dedent(
  568. """
  569. curl -X POST "https://api.example.com/v3/users/reset-password" \\
  570. -H "Content-Type: application/json" \\
  571. -d '{
  572. "reset_token": "reset_token_received_via_email",
  573. "new_password": "new_secure_password789"
  574. }'"""
  575. ),
  576. },
  577. ]
  578. },
  579. )
  580. @self.base_endpoint
  581. async def reset_password(
  582. reset_token: str = Body(..., description="Password reset token"),
  583. new_password: str = Body(..., description="New password"),
  584. ) -> WrappedGenericMessageResponse:
  585. """Reset a user's password using a reset token."""
  586. result = await self.services.auth.confirm_password_reset(
  587. reset_token, new_password
  588. )
  589. return GenericMessageResponse(message=result["message"]) # type: ignore
  590. @self.router.get(
  591. "/users",
  592. dependencies=[Depends(self.rate_limit_dependency)],
  593. summary="List Users",
  594. openapi_extra={
  595. "x-codeSamples": [
  596. {
  597. "lang": "Python",
  598. "source": textwrap.dedent(
  599. """
  600. from r2r import R2RClient
  601. client = R2RClient("http://localhost:7272")
  602. # client.login(...)
  603. # List users with filters
  604. users = client.users.list(
  605. offset=0,
  606. limit=100,
  607. )
  608. """
  609. ),
  610. },
  611. {
  612. "lang": "JavaScript",
  613. "source": textwrap.dedent(
  614. """
  615. const { r2rClient } = require("r2r-js");
  616. const client = new r2rClient("http://localhost:7272");
  617. function main() {
  618. const response = await client.users.list();
  619. }
  620. main();
  621. """
  622. ),
  623. },
  624. {
  625. "lang": "CLI",
  626. "source": textwrap.dedent(
  627. """
  628. r2r users list
  629. """
  630. ),
  631. },
  632. {
  633. "lang": "Shell",
  634. "source": textwrap.dedent(
  635. """
  636. curl -X GET "https://api.example.com/users?offset=0&limit=100&username=john&email=john@example.com&is_active=true&is_superuser=false" \\
  637. -H "Authorization: Bearer YOUR_API_KEY"
  638. """
  639. ),
  640. },
  641. ]
  642. },
  643. )
  644. @self.base_endpoint
  645. async def list_users(
  646. # TODO - Implement the following parameters
  647. # offset: int = Query(0, ge=0, example=0),
  648. # limit: int = Query(100, ge=1, le=1000, example=100),
  649. # username: Optional[str] = Query(None, example="john"),
  650. # email: Optional[str] = Query(None, example="john@example.com"),
  651. # is_active: Optional[bool] = Query(None, example=True),
  652. # is_superuser: Optional[bool] = Query(None, example=False),
  653. # auth_user=Depends(self.providers.auth.auth_wrapper()),
  654. ids: list[str] = Query(
  655. [], description="List of user IDs to filter by"
  656. ),
  657. offset: int = Query(
  658. 0,
  659. ge=0,
  660. description="Specifies the number of objects to skip. Defaults to 0.",
  661. ),
  662. limit: int = Query(
  663. 100,
  664. ge=1,
  665. le=1000,
  666. description="Specifies a limit on the number of objects to return, ranging between 1 and 100. Defaults to 100.",
  667. ),
  668. auth_user=Depends(self.providers.auth.auth_wrapper()),
  669. ) -> WrappedUsersResponse:
  670. """
  671. List all users with pagination and filtering options.
  672. Only accessible by superusers.
  673. """
  674. if not auth_user.is_superuser:
  675. raise R2RException(
  676. "Only a superuser can call the `users_overview` endpoint.",
  677. 403,
  678. )
  679. user_uuids = [UUID(user_id) for user_id in ids]
  680. users_overview_response = (
  681. await self.services.management.users_overview(
  682. user_ids=user_uuids, offset=offset, limit=limit
  683. )
  684. )
  685. return users_overview_response["results"], { # type: ignore
  686. "total_entries": users_overview_response["total_entries"]
  687. }
  688. @self.router.get(
  689. "/users/me",
  690. dependencies=[Depends(self.rate_limit_dependency)],
  691. summary="Get the Current User",
  692. openapi_extra={
  693. "x-codeSamples": [
  694. {
  695. "lang": "Python",
  696. "source": textwrap.dedent(
  697. """
  698. from r2r import R2RClient
  699. client = R2RClient("http://localhost:7272")
  700. # client.login(...)
  701. # Get user details
  702. users = client.users.me()
  703. """
  704. ),
  705. },
  706. {
  707. "lang": "JavaScript",
  708. "source": textwrap.dedent(
  709. """
  710. const { r2rClient } = require("r2r-js");
  711. const client = new r2rClient("http://localhost:7272");
  712. function main() {
  713. const response = await client.users.retrieve();
  714. }
  715. main();
  716. """
  717. ),
  718. },
  719. {
  720. "lang": "CLI",
  721. "source": textwrap.dedent(
  722. """
  723. r2r users me
  724. """
  725. ),
  726. },
  727. {
  728. "lang": "Shell",
  729. "source": textwrap.dedent(
  730. """
  731. curl -X GET "https://api.example.com/users/me" \\
  732. -H "Authorization: Bearer YOUR_API_KEY"
  733. """
  734. ),
  735. },
  736. ]
  737. },
  738. )
  739. @self.base_endpoint
  740. async def get_current_user(
  741. auth_user=Depends(self.providers.auth.auth_wrapper()),
  742. ) -> WrappedUserResponse:
  743. """
  744. Get detailed information about the currently authenticated user.
  745. """
  746. return auth_user
  747. @self.router.get(
  748. "/users/{id}",
  749. dependencies=[Depends(self.rate_limit_dependency)],
  750. summary="Get User Details",
  751. openapi_extra={
  752. "x-codeSamples": [
  753. {
  754. "lang": "Python",
  755. "source": textwrap.dedent(
  756. """
  757. from r2r import R2RClient
  758. client = R2RClient("http://localhost:7272")
  759. # client.login(...)
  760. # Get user details
  761. users = client.users.retrieve(
  762. id="b4ac4dd6-5f27-596e-a55b-7cf242ca30aa"
  763. )
  764. """
  765. ),
  766. },
  767. {
  768. "lang": "JavaScript",
  769. "source": textwrap.dedent(
  770. """
  771. const { r2rClient } = require("r2r-js");
  772. const client = new r2rClient("http://localhost:7272");
  773. function main() {
  774. const response = await client.users.retrieve({
  775. id: "b4ac4dd6-5f27-596e-a55b-7cf242ca30aa"
  776. });
  777. }
  778. main();
  779. """
  780. ),
  781. },
  782. {
  783. "lang": "CLI",
  784. "source": textwrap.dedent(
  785. """
  786. r2r users retrieve b4ac4dd6-5f27-596e-a55b-7cf242ca30aa
  787. """
  788. ),
  789. },
  790. {
  791. "lang": "Shell",
  792. "source": textwrap.dedent(
  793. """
  794. curl -X GET "https://api.example.com/users/550e8400-e29b-41d4-a716-446655440000" \\
  795. -H "Authorization: Bearer YOUR_API_KEY"
  796. """
  797. ),
  798. },
  799. ]
  800. },
  801. )
  802. @self.base_endpoint
  803. async def get_user(
  804. id: UUID = Path(
  805. ..., example="550e8400-e29b-41d4-a716-446655440000"
  806. ),
  807. auth_user=Depends(self.providers.auth.auth_wrapper()),
  808. ) -> WrappedUserResponse:
  809. """
  810. Get detailed information about a specific user.
  811. Users can only access their own information unless they are superusers.
  812. """
  813. if not auth_user.is_superuser and auth_user.id != id:
  814. raise R2RException(
  815. "Only a superuser can call the get `user` endpoint for other users.",
  816. 403,
  817. )
  818. users_overview_response = (
  819. await self.services.management.users_overview(
  820. offset=0,
  821. limit=1,
  822. user_ids=[id],
  823. )
  824. )
  825. return users_overview_response["results"][0]
  826. @self.router.delete(
  827. "/users/{id}",
  828. dependencies=[Depends(self.rate_limit_dependency)],
  829. summary="Delete User",
  830. openapi_extra={
  831. "x-codeSamples": [
  832. {
  833. "lang": "Python",
  834. "source": textwrap.dedent(
  835. """
  836. from r2r import R2RClient
  837. client = R2RClient("http://localhost:7272")
  838. # client.login(...)
  839. # Delete user
  840. client.users.delete(id="550e8400-e29b-41d4-a716-446655440000", password="secure_password123")
  841. """
  842. ),
  843. },
  844. {
  845. "lang": "JavaScript",
  846. "source": textwrap.dedent(
  847. """
  848. const { r2rClient } = require("r2r-js");
  849. const client = new r2rClient("http://localhost:7272");
  850. function main() {
  851. const response = await client.users.delete({
  852. id: "550e8400-e29b-41d4-a716-446655440000",
  853. password: "secure_password123"
  854. });
  855. }
  856. main();
  857. """
  858. ),
  859. },
  860. ]
  861. },
  862. )
  863. @self.base_endpoint
  864. async def delete_user(
  865. id: UUID = Path(
  866. ..., example="550e8400-e29b-41d4-a716-446655440000"
  867. ),
  868. password: Optional[str] = Body(
  869. None, description="User's current password"
  870. ),
  871. delete_vector_data: Optional[bool] = Body(
  872. False,
  873. description="Whether to delete the user's vector data",
  874. ),
  875. auth_user=Depends(self.providers.auth.auth_wrapper()),
  876. ) -> WrappedBooleanResponse:
  877. """
  878. Delete a specific user.
  879. Users can only delete their own account unless they are superusers.
  880. """
  881. if not auth_user.is_superuser and auth_user.id != id:
  882. raise R2RException(
  883. "Only a superuser can delete other users.",
  884. 403,
  885. )
  886. await self.services.auth.delete_user(
  887. user_id=id,
  888. password=password,
  889. delete_vector_data=delete_vector_data,
  890. is_superuser=auth_user.is_superuser,
  891. )
  892. return GenericBooleanResponse(success=True) # type: ignore
  893. @self.router.get(
  894. "/users/{id}/collections",
  895. dependencies=[Depends(self.rate_limit_dependency)],
  896. summary="Get User Collections",
  897. openapi_extra={
  898. "x-codeSamples": [
  899. {
  900. "lang": "Python",
  901. "source": textwrap.dedent(
  902. """
  903. from r2r import R2RClient
  904. client = R2RClient("http://localhost:7272")
  905. # client.login(...)
  906. # Get user collections
  907. collections = client.user.list_collections(
  908. "550e8400-e29b-41d4-a716-446655440000",
  909. offset=0,
  910. limit=100
  911. )
  912. """
  913. ),
  914. },
  915. {
  916. "lang": "JavaScript",
  917. "source": textwrap.dedent(
  918. """
  919. const { r2rClient } = require("r2r-js");
  920. const client = new r2rClient("http://localhost:7272");
  921. function main() {
  922. const response = await client.users.listCollections({
  923. id: "550e8400-e29b-41d4-a716-446655440000",
  924. offset: 0,
  925. limit: 100
  926. });
  927. }
  928. main();
  929. """
  930. ),
  931. },
  932. {
  933. "lang": "CLI",
  934. "source": textwrap.dedent(
  935. """
  936. r2r users list-collections 550e8400-e29b-41d4-a716-446655440000
  937. """
  938. ),
  939. },
  940. {
  941. "lang": "Shell",
  942. "source": textwrap.dedent(
  943. """
  944. curl -X GET "https://api.example.com/users/550e8400-e29b-41d4-a716-446655440000/collections?offset=0&limit=100" \\
  945. -H "Authorization: Bearer YOUR_API_KEY"
  946. """
  947. ),
  948. },
  949. ]
  950. },
  951. )
  952. @self.base_endpoint
  953. async def get_user_collections(
  954. id: UUID = Path(
  955. ..., example="550e8400-e29b-41d4-a716-446655440000"
  956. ),
  957. offset: int = Query(
  958. 0,
  959. ge=0,
  960. description="Specifies the number of objects to skip. Defaults to 0.",
  961. ),
  962. limit: int = Query(
  963. 100,
  964. ge=1,
  965. le=1000,
  966. description="Specifies a limit on the number of objects to return, ranging between 1 and 100. Defaults to 100.",
  967. ),
  968. auth_user=Depends(self.providers.auth.auth_wrapper()),
  969. ) -> WrappedCollectionsResponse:
  970. """
  971. Get all collections associated with a specific user.
  972. Users can only access their own collections unless they are superusers.
  973. """
  974. if auth_user.id != id and not auth_user.is_superuser:
  975. raise R2RException(
  976. "The currently authenticated user does not have access to the specified collection.",
  977. 403,
  978. )
  979. user_collection_response = (
  980. await self.services.management.collections_overview(
  981. offset=offset,
  982. limit=limit,
  983. user_ids=[id],
  984. )
  985. )
  986. return user_collection_response["results"], { # type: ignore
  987. "total_entries": user_collection_response["total_entries"]
  988. }
  989. @self.router.post(
  990. "/users/{id}/collections/{collection_id}",
  991. dependencies=[Depends(self.rate_limit_dependency)],
  992. summary="Add User to Collection",
  993. response_model=WrappedBooleanResponse,
  994. openapi_extra={
  995. "x-codeSamples": [
  996. {
  997. "lang": "Python",
  998. "source": textwrap.dedent(
  999. """
  1000. from r2r import R2RClient
  1001. client = R2RClient("http://localhost:7272")
  1002. # client.login(...)
  1003. # Add user to collection
  1004. client.users.add_to_collection(
  1005. id="550e8400-e29b-41d4-a716-446655440000",
  1006. collection_id="750e8400-e29b-41d4-a716-446655440000"
  1007. )
  1008. """
  1009. ),
  1010. },
  1011. {
  1012. "lang": "JavaScript",
  1013. "source": textwrap.dedent(
  1014. """
  1015. const { r2rClient } = require("r2r-js");
  1016. const client = new r2rClient("http://localhost:7272");
  1017. function main() {
  1018. const response = await client.users.addToCollection({
  1019. id: "550e8400-e29b-41d4-a716-446655440000",
  1020. collectionId: "750e8400-e29b-41d4-a716-446655440000"
  1021. });
  1022. }
  1023. main();
  1024. """
  1025. ),
  1026. },
  1027. {
  1028. "lang": "CLI",
  1029. "source": textwrap.dedent(
  1030. """
  1031. r2r users add-to-collection 550e8400-e29b-41d4-a716-446655440000 750e8400-e29b-41d4-a716-446655440000
  1032. """
  1033. ),
  1034. },
  1035. {
  1036. "lang": "Shell",
  1037. "source": textwrap.dedent(
  1038. """
  1039. curl -X POST "https://api.example.com/users/550e8400-e29b-41d4-a716-446655440000/collections/750e8400-e29b-41d4-a716-446655440000" \\
  1040. -H "Authorization: Bearer YOUR_API_KEY"
  1041. """
  1042. ),
  1043. },
  1044. ]
  1045. },
  1046. )
  1047. @self.base_endpoint
  1048. async def add_user_to_collection(
  1049. id: UUID = Path(
  1050. ..., example="550e8400-e29b-41d4-a716-446655440000"
  1051. ),
  1052. collection_id: UUID = Path(
  1053. ..., example="750e8400-e29b-41d4-a716-446655440000"
  1054. ),
  1055. auth_user=Depends(self.providers.auth.auth_wrapper()),
  1056. ) -> WrappedBooleanResponse:
  1057. if auth_user.id != id and not auth_user.is_superuser:
  1058. raise R2RException(
  1059. "The currently authenticated user does not have access to the specified collection.",
  1060. 403,
  1061. )
  1062. # TODO - Do we need a check on user access to the collection?
  1063. await self.services.management.add_user_to_collection( # type: ignore
  1064. id, collection_id
  1065. )
  1066. return GenericBooleanResponse(success=True) # type: ignore
  1067. @self.router.delete(
  1068. "/users/{id}/collections/{collection_id}",
  1069. dependencies=[Depends(self.rate_limit_dependency)],
  1070. summary="Remove User from Collection",
  1071. openapi_extra={
  1072. "x-codeSamples": [
  1073. {
  1074. "lang": "Python",
  1075. "source": textwrap.dedent(
  1076. """
  1077. from r2r import R2RClient
  1078. client = R2RClient("http://localhost:7272")
  1079. # client.login(...)
  1080. # Remove user from collection
  1081. client.users.remove_from_collection(
  1082. id="550e8400-e29b-41d4-a716-446655440000",
  1083. collection_id="750e8400-e29b-41d4-a716-446655440000"
  1084. )
  1085. """
  1086. ),
  1087. },
  1088. {
  1089. "lang": "JavaScript",
  1090. "source": textwrap.dedent(
  1091. """
  1092. const { r2rClient } = require("r2r-js");
  1093. const client = new r2rClient("http://localhost:7272");
  1094. function main() {
  1095. const response = await client.users.removeFromCollection({
  1096. id: "550e8400-e29b-41d4-a716-446655440000",
  1097. collectionId: "750e8400-e29b-41d4-a716-446655440000"
  1098. });
  1099. }
  1100. main();
  1101. """
  1102. ),
  1103. },
  1104. {
  1105. "lang": "CLI",
  1106. "source": textwrap.dedent(
  1107. """
  1108. r2r users remove-from-collection 550e8400-e29b-41d4-a716-446655440000 750e8400-e29b-41d4-a716-446655440000
  1109. """
  1110. ),
  1111. },
  1112. {
  1113. "lang": "Shell",
  1114. "source": textwrap.dedent(
  1115. """
  1116. curl -X DELETE "https://api.example.com/users/550e8400-e29b-41d4-a716-446655440000/collections/750e8400-e29b-41d4-a716-446655440000" \\
  1117. -H "Authorization: Bearer YOUR_API_KEY"
  1118. """
  1119. ),
  1120. },
  1121. ]
  1122. },
  1123. )
  1124. @self.base_endpoint
  1125. async def remove_user_from_collection(
  1126. id: UUID = Path(
  1127. ..., example="550e8400-e29b-41d4-a716-446655440000"
  1128. ),
  1129. collection_id: UUID = Path(
  1130. ..., example="750e8400-e29b-41d4-a716-446655440000"
  1131. ),
  1132. auth_user=Depends(self.providers.auth.auth_wrapper()),
  1133. ) -> WrappedBooleanResponse:
  1134. """
  1135. Remove a user from a collection.
  1136. Requires either superuser status or access to the collection.
  1137. """
  1138. if auth_user.id != id and not auth_user.is_superuser:
  1139. raise R2RException(
  1140. "The currently authenticated user does not have access to the specified collection.",
  1141. 403,
  1142. )
  1143. # TODO - Do we need a check on user access to the collection?
  1144. await self.services.management.remove_user_from_collection( # type: ignore
  1145. id, collection_id
  1146. )
  1147. return GenericBooleanResponse(success=True) # type: ignore
  1148. @self.router.post(
  1149. "/users/{id}",
  1150. dependencies=[Depends(self.rate_limit_dependency)],
  1151. summary="Update User",
  1152. openapi_extra={
  1153. "x-codeSamples": [
  1154. {
  1155. "lang": "Python",
  1156. "source": textwrap.dedent(
  1157. """
  1158. from r2r import R2RClient
  1159. client = R2RClient("http://localhost:7272")
  1160. # client.login(...)
  1161. # Update user
  1162. updated_user = client.update_user(
  1163. "550e8400-e29b-41d4-a716-446655440000",
  1164. name="John Doe"
  1165. )
  1166. """
  1167. ),
  1168. },
  1169. {
  1170. "lang": "JavaScript",
  1171. "source": textwrap.dedent(
  1172. """
  1173. const { r2rClient } = require("r2r-js");
  1174. const client = new r2rClient("http://localhost:7272");
  1175. function main() {
  1176. const response = await client.users.update({
  1177. id: "550e8400-e29b-41d4-a716-446655440000",
  1178. name: "John Doe"
  1179. });
  1180. }
  1181. main();
  1182. """
  1183. ),
  1184. },
  1185. {
  1186. "lang": "Shell",
  1187. "source": textwrap.dedent(
  1188. """
  1189. curl -X POST "https://api.example.com/users/550e8400-e29b-41d4-a716-446655440000" \\
  1190. -H "Authorization: Bearer YOUR_API_KEY" \\
  1191. -H "Content-Type: application/json" \\
  1192. -d '{
  1193. "id": "550e8400-e29b-41d4-a716-446655440000",
  1194. "name": "John Doe",
  1195. }'
  1196. """
  1197. ),
  1198. },
  1199. ]
  1200. },
  1201. )
  1202. # TODO - Modify update user to have synced params with user object
  1203. @self.base_endpoint
  1204. async def update_user(
  1205. id: UUID = Path(..., description="ID of the user to update"),
  1206. email: EmailStr | None = Body(
  1207. None, description="Updated email address"
  1208. ),
  1209. is_superuser: bool | None = Body(
  1210. None, description="Updated superuser status"
  1211. ),
  1212. name: str | None = Body(None, description="Updated user name"),
  1213. bio: str | None = Body(None, description="Updated user bio"),
  1214. profile_picture: str | None = Body(
  1215. None, description="Updated profile picture URL"
  1216. ),
  1217. auth_user=Depends(self.providers.auth.auth_wrapper()),
  1218. ) -> WrappedUserResponse:
  1219. """
  1220. Update user information.
  1221. Users can only update their own information unless they are superusers.
  1222. Superuser status can only be modified by existing superusers.
  1223. """
  1224. if is_superuser is not None and not auth_user.is_superuser:
  1225. raise R2RException(
  1226. "Only superusers can update the superuser status of a user",
  1227. 403,
  1228. )
  1229. if not auth_user.is_superuser and auth_user.id != id:
  1230. raise R2RException(
  1231. "Only superusers can update other users' information",
  1232. 403,
  1233. )
  1234. return await self.services.auth.update_user(
  1235. user_id=id,
  1236. email=email,
  1237. is_superuser=is_superuser,
  1238. name=name,
  1239. bio=bio,
  1240. profile_picture=profile_picture,
  1241. )
  1242. @self.router.post(
  1243. "/users/{id}/api-keys",
  1244. dependencies=[Depends(self.rate_limit_dependency)],
  1245. summary="Create User API Key",
  1246. response_model=WrappedAPIKeyResponse,
  1247. openapi_extra={
  1248. "x-codeSamples": [
  1249. {
  1250. "lang": "Python",
  1251. "source": textwrap.dedent(
  1252. """
  1253. from r2r import R2RClient
  1254. client = R2RClient("http://localhost:7272")
  1255. # client.login(...)
  1256. result = client.users.create_api_key(
  1257. id="550e8400-e29b-41d4-a716-446655440000",
  1258. )
  1259. # result["api_key"] contains the newly created API key
  1260. """
  1261. ),
  1262. },
  1263. {
  1264. "lang": "cURL",
  1265. "source": textwrap.dedent(
  1266. """
  1267. curl -X POST "https://api.example.com/users/550e8400-e29b-41d4-a716-446655440000/api-keys" \\
  1268. -H "Authorization: Bearer YOUR_API_TOKEN"
  1269. """
  1270. ),
  1271. },
  1272. ]
  1273. },
  1274. )
  1275. @self.base_endpoint
  1276. async def create_user_api_key(
  1277. id: UUID = Path(
  1278. ..., description="ID of the user for whom to create an API key"
  1279. ),
  1280. auth_user=Depends(self.providers.auth.auth_wrapper()),
  1281. ) -> WrappedAPIKeyResponse:
  1282. """
  1283. Create a new API key for the specified user.
  1284. Only superusers or the user themselves may create an API key.
  1285. """
  1286. if auth_user.id != id and not auth_user.is_superuser:
  1287. raise R2RException(
  1288. "Only the user themselves or a superuser can create API keys for this user.",
  1289. 403,
  1290. )
  1291. api_key = await self.services.auth.create_user_api_key(id)
  1292. return api_key # type: ignore
  1293. @self.router.get(
  1294. "/users/{id}/api-keys",
  1295. dependencies=[Depends(self.rate_limit_dependency)],
  1296. summary="List User API Keys",
  1297. openapi_extra={
  1298. "x-codeSamples": [
  1299. {
  1300. "lang": "Python",
  1301. "source": textwrap.dedent(
  1302. """
  1303. from r2r import R2RClient
  1304. client = R2RClient("http://localhost:7272")
  1305. # client.login(...)
  1306. keys = client.users.list_api_keys(
  1307. id="550e8400-e29b-41d4-a716-446655440000"
  1308. )
  1309. """
  1310. ),
  1311. },
  1312. {
  1313. "lang": "cURL",
  1314. "source": textwrap.dedent(
  1315. """
  1316. curl -X GET "https://api.example.com/users/550e8400-e29b-41d4-a716-446655440000/api-keys" \\
  1317. -H "Authorization: Bearer YOUR_API_TOKEN"
  1318. """
  1319. ),
  1320. },
  1321. ]
  1322. },
  1323. )
  1324. @self.base_endpoint
  1325. async def list_user_api_keys(
  1326. id: UUID = Path(
  1327. ..., description="ID of the user whose API keys to list"
  1328. ),
  1329. auth_user=Depends(self.providers.auth.auth_wrapper()),
  1330. ) -> WrappedAPIKeysResponse:
  1331. """
  1332. List all API keys for the specified user.
  1333. Only superusers or the user themselves may list the API keys.
  1334. """
  1335. if auth_user.id != id and not auth_user.is_superuser:
  1336. raise R2RException(
  1337. "Only the user themselves or a superuser can list API keys for this user.",
  1338. 403,
  1339. )
  1340. keys = (
  1341. await self.providers.database.users_handler.get_user_api_keys(
  1342. id
  1343. )
  1344. )
  1345. return keys, {"total_entries": len(keys)} # type: ignore
  1346. @self.router.delete(
  1347. "/users/{id}/api-keys/{key_id}",
  1348. dependencies=[Depends(self.rate_limit_dependency)],
  1349. summary="Delete User API Key",
  1350. openapi_extra={
  1351. "x-codeSamples": [
  1352. {
  1353. "lang": "Python",
  1354. "source": textwrap.dedent(
  1355. """
  1356. from r2r import R2RClient
  1357. from uuid import UUID
  1358. client = R2RClient("http://localhost:7272")
  1359. # client.login(...)
  1360. response = client.users.delete_api_key(
  1361. id="550e8400-e29b-41d4-a716-446655440000",
  1362. key_id="d9c562d4-3aef-43e8-8f08-0cf7cd5e0a25"
  1363. )
  1364. """
  1365. ),
  1366. },
  1367. {
  1368. "lang": "cURL",
  1369. "source": textwrap.dedent(
  1370. """
  1371. curl -X DELETE "https://api.example.com/users/550e8400-e29b-41d4-a716-446655440000/api-keys/d9c562d4-3aef-43e8-8f08-0cf7cd5e0a25" \\
  1372. -H "Authorization: Bearer YOUR_API_TOKEN"
  1373. """
  1374. ),
  1375. },
  1376. ]
  1377. },
  1378. )
  1379. @self.base_endpoint
  1380. async def delete_user_api_key(
  1381. id: UUID = Path(..., description="ID of the user"),
  1382. key_id: UUID = Path(
  1383. ..., description="ID of the API key to delete"
  1384. ),
  1385. auth_user=Depends(self.providers.auth.auth_wrapper()),
  1386. ) -> WrappedBooleanResponse:
  1387. """
  1388. Delete a specific API key for the specified user.
  1389. Only superusers or the user themselves may delete the API key.
  1390. """
  1391. if auth_user.id != id and not auth_user.is_superuser:
  1392. raise R2RException(
  1393. "Only the user themselves or a superuser can delete this API key.",
  1394. 403,
  1395. )
  1396. success = (
  1397. await self.providers.database.users_handler.delete_api_key(
  1398. id, key_id
  1399. )
  1400. )
  1401. if not success:
  1402. raise R2RException(
  1403. "API key not found or could not be deleted", 400
  1404. )
  1405. return {"success": True} # type: ignore