users_router.py 59 KB

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