User Auth

A comprehensive guide to user authentication and management features in R2R

Introduction

R2R provides a complete set of user authentication and management features, allowing developers to implement secure and feature-rich authentication systems, or to integrate directly with their authentication provider of choice.

Refer here for documentation on the available authentication provider options built into R2R, or refer here for available auth API reference.

When authentication is not required (require_authentication is set to false, which is the default in r2r.toml), unauthenticated requests will default to using the credentials of the default admin user.

This behavior ensures that operations can proceed smoothly in development or testing environments where authentication may not be enforced, but it should be used with caution in production settings.

Setup

Before diving into the authentication features, ensure you have R2R installed and configured as described in the installation guide. For this guide, we’ll use the default configuration. Further, r2r serve must be called to serve R2R in either your local environment or local Docker engine.

Basic Usage

User Registration and Login

Let’s start by registering a new user and logging in:

core/examples/scripts/run_auth_workflow.py
1from r2r import R2RClient
2
3client = R2RClient("http://localhost:7272") # Replace with your R2R deployment URL
4
5# Register a new user
6user_result = client.register("[email protected]", "password123")
7# {'results': {'email': '[email protected]', 'id': 'bf417057-f104-4e75-8579-c74d26fcbed3', 'hashed_password': '$2b$12$p6a9glpAQaq.4uzi4gXQru6PN7WBpky/xMeYK9LShEe4ygBf1L.pK', 'is_superuser': False, 'is_active': True, 'is_verified': False, 'verification_code_expiry': None, 'name': None, 'bio': None, 'profile_picture': None, 'created_at': '2024-07-16T22:53:47.524794Z', 'updated_at': '2024-07-16T22:53:47.524794Z'}}
8
9# Login immediately (assuming email verification is disabled)
10login_result = client.login("[email protected]", "password123")
11# {'results': {'access_token': {'token': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyMUB0ZXN0LmNvbSIsImV4cCI6MTcyMTE5OTI0Ni44Nzc2NTksInRva2VuX3R5cGUiOiJhY2Nlc3MifQ.P4RcCkCe0H5UHPHak7tRovIgyQcql4gB8NlqdDDk50Y', 'token_type': 'access'}, 'refresh_token': {'token': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyMUB0ZXN0LmNvbSIsImV4cCI6MTcyMTc3NTI0NiwidG9rZW5fdHlwZSI6InJlZnJlc2gifQ.VgfZ4Lhz0f2GW41NYv6KLrMCK3CdGmGVug7eTQp0xPU', 'token_type': 'refresh'}}}

This code snippet demonstrates the basic user registration and login process. The register method creates a new user account, while the login method authenticates the user and returns access and refresh tokens. In the example above, it was assumed that email verification was disabled.

Email Verification (Optional)

If email verification is enabled in your R2R configuration, you’ll need to verify the user’s email before they can log in:

1verify_result = client.verify_email("verification_code_here")
2# {"results": {"message": "Email verified successfully"}}

Token Refresh

After logging in, you gain immediate access to user information such as general account details, documents overview, and utility functions like token refresh:

1refresh_result = client.refresh_access_token()
2# {'results': {'access_token': {'token': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyMUB0ZXN0LmNvbSIsImV4cCI6MTcyMTIwMTk3Mi4zMzI4NTIsInRva2VuX3R5cGUiOiJhY2Nlc3MifQ.Ze9A50kefndAtu2tvcvMCiilFfAhrOV0l5A7RZgPvBY', 'token_type': 'access'}, 'refresh_token': {'token': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyMUB0ZXN0LmNvbSIsImV4cCI6MTcyMTc3Nzk3MiwidG9rZW5fdHlwZSI6InJlZnJlc2gifQ.NwzFH8e2tKO0bH1Hdm_eq39VqmGPf7xSNOOhDlKFQFQ', 'token_type': 'refresh'}}}

Document Management

R2R allows users to manage their documents securely. Here’s how to ingest and search a given users documents:

Ingesting Documents

1import os
2
3# Ingest a sample file for the logged-in user
4script_path = os.path.dirname(__file__)
5sample_file = os.path.join(script_path, "..", "data", "aristotle.txt")
6ingestion_result = client.ingest_files([sample_file])
7# {'results': {'processed_documents': ["Document 'aristotle.txt' processed successfully."], 'failed_documents': [], 'skipped_documents': []}}

User Document Overview

1documents_overview = client.documents_overview()
2# {'results': [{'document_id': '6ab698c6-e494-5441-a740-49395f2b1881', 'version': 'v0', 'size_in_bytes': 73353, 'metadata': {}, 'status': 'success', 'user_id': 'ba0c75eb-0b21-4eb1-a902-082476e5e972', 'title': 'aristotle.txt', 'created_at': '2024-07-16T16:25:27.634411Z', 'updated_at': '2024-07-16T16:25:27.634411Z'}]}

Search & RAG

1search_result = client.search(query="Sample search query")
2# {'results': {'vector_search_results': [{ ... 'metadata': {'text': 'Aristotle[A] (Greek: Ἀριστοτέλης Aristotélēs, pronounced [aristotélɛːs]; 384–322 BC) was an Ancient Greek philosopher and polymath. His writings cover a broad range of subjects spanning the natural sciences, philosophy, linguistics, economics, politics, psychology, and the arts. As the founder of the Peripatetic school of philosophy in the Lyceum in Athens, he began the wider Aristotelian tradition that followed, which set the groundwork for the development of modern science.', 'title': 'aristotle.txt', 'user_id': 'bf417057-f104-4e75-8579-c74d26fcbed3', 'version': 'v0', 'chunk_order': 0, 'document_id': 'a2645197-d07f-558d-ba55-f7a60eb29621', 'extraction_id': 'b7bbd497-311a-5dc8-8a51-79e2208739e0', 'associatedQuery': 'Who was Aristotle'}}, {'id': '781ce9e6-9e73-5012-8445-35b7d84f161c', 'score': 0.670799394202279, 'metadata': {'text': "Aristotle was born in 384 BC[C] in Stagira, Chalcidice,[2] about 55 km (34 miles) east of modern-day Thessaloniki.[3][4] His father, Nicomachus, was the personal physician to King Amyntas of Macedon. While he was young, Aristotle learned about biology and medical information, which was taught by his father.[5] Both of Aristotle's parents died when he was about thirteen, and Proxenus of Atarneus became his guardian.[6] Although little information about Aristotle's childhood has survived, he probably spent", 'title': 'aristotle.txt', 'user_id': 'bf417057-f104-4e75-8579-c74d26fcbed3', 'version': 'v0', 'chunk_order': 8, 'document_id': 'a2645197-d07f-558d-ba55-f7a60eb29621', 'extraction_id': 'b7bbd497-311a-5dc8-8a51-79e2208739e0', 'associatedQuery': 'Who was Aristotle'}}, {'id': 'f32cda7c-2538-5248-b0b6-4d0d45cc4d60', 'score': 0.667974928858889, 'metadata': {'text': 'Aristotle was revered among medieval Muslim scholars as "The First Teacher", and among medieval Christians like Thomas Aquinas as simply "The Philosopher", while the poet Dante called him "the master of those who know". His works contain the earliest known formal study of logic, and were studied by medieval scholars such as Peter Abelard and Jean Buridan. Aristotle\'s influence on logic continued well into the 19th century. In addition, his ethics, although always influential, gained renewed interest with', 'title': 'aristotle.txt', 'user_id': 'bf417057-f104-4e75-8579-c74d26fcbed3', 'version': 'v0', 'chunk_order': 5, 'document_id': 'a2645197-d07f-558d-ba55-f7a60eb29621', 'extraction_id': 'b7bbd497-311a-5dc8-8a51-79e2208739e0', 'associatedQuery': 'Who was Aristotle'}}, {'id': 'e6592fd5-e02e-5847-b158-79bbdd8710a2', 'score': 0.6647597950983339, 'metadata': {'text': "Little is known about Aristotle's life. He was born in the city of Stagira in northern Greece during the Classical period. His father, Nicomachus, died when Aristotle was a child, and he was brought up by a guardian. At 17 or 18, he joined Plato's Academy in Athens and remained there until the age of 37 (c.\u2009347 BC). Shortly after Plato died, Aristotle left Athens and, at the request of Philip II of Macedon, tutored his son Alexander the Great beginning in 343 BC. He established a library in the Lyceum,", 'title': 'aristotle.txt', 'user_id': 'bf417057-f104-4e75-8579-c74d26fcbed3', 'version': 'v0', 'chunk_order': 1, 'document_id': 'a2645197-d07f-558d-ba55-f7a60eb29621', 'extraction_id': 'b7bbd497-311a-5dc8-8a51-79e2208739e0', 'associatedQuery': 'Who was Aristotle'}}, {'id': '8c72faca-6d98-5129-b9ee-70769272e361', 'score': 0.6476034942146001, 'metadata': {'text': 'Among countless other achievements, Aristotle was the founder of formal logic,[146] pioneered the study of zoology, and left every future scientist and philosopher in his debt through his contributions to the scientific method.[2][147][148] Taneli Kukkonen, observes that his achievement in founding two sciences is unmatched, and his reach in influencing "every branch of intellectual enterprise" including Western ethical and political theory, theology, rhetoric, and literary analysis is equally long. As a', 'title': 'aristotle.txt', 'user_id': 'bf417057-f104-4e75-8579-c74d26fcbed3', 'version': 'v0', 'chunk_order': 175, 'document_id': 'a2645197-d07f-558d-ba55-f7a60eb29621', 'extraction_id': 'b7bbd497-311a-5dc8-8a51-79e2208739e0', 'associatedQuery': 'Who was Aristotle'}}, {'id': '3ce904cc-5835-551a-a85c-f00be1a5e8dc', 'score': 0.626156434278918, 'metadata': {'text': 'Aristotle has been called the father of logic, biology, political science, zoology, embryology, natural law, scientific method, rhetoric, psychology, realism, criticism, individualism, teleology, and meteorology.[151]', 'title': 'aristotle.txt', 'user_id': 'bf417057-f104-4e75-8579-c74d26fcbed3', 'version': 'v0', 'chunk_order': 177, 'document_id': 'a2645197-d07f-558d-ba55-f7a60eb29621', 'extraction_id': 'b7bbd497-311a-5dc8-8a51-79e2208739e0', 'associatedQuery': 'Who was Aristotle'}}, {'id': '6a15b09b-4bf1-5c1f-af24-fe659c8a011d', 'score': 0.624521989361129, 'metadata': {'text': 'after friends and relatives, and to deal with the latter as with beasts or plants".[13] By 335 BC, Aristotle had returned to Athens, establishing his own school there known as the Lyceum. Aristotle conducted courses at the school for the next twelve years. While in Athens, his wife Pythias died and Aristotle became involved with Herpyllis of Stagira. They had a son whom Aristotle named after his father, Nicomachus. If the Suda – an uncritical compilation from the Middle Ages – is accurate, he may also have', 'title': 'aristotle.txt', 'user_id': 'bf417057-f104-4e75-8579-c74d26fcbed3', 'version': 'v0', 'chunk_order': 16, 'document_id': 'a2645197-d07f-558d-ba55-f7a60eb29621', 'extraction_id': 'b7bbd497-311a-5dc8-8a51-79e2208739e0', 'associatedQuery': 'Who was Aristotle'}}, {'id': '19a755d0-770f-5c6f-991e-ca191a40c8d6', 'score': 0.614493374720815, 'metadata': {'text': "passed to Plato's nephew Speusippus, although it is possible that he feared the anti-Macedonian sentiments in Athens at that time and left before Plato died.[10] Aristotle then accompanied Xenocrates to the court of his friend Hermias of Atarneus in Asia Minor. After the death of Hermias, Aristotle travelled with his pupil Theophrastus to the island of Lesbos, where together they researched the botany and zoology of the island and its sheltered lagoon. While in Lesbos, Aristotle married Pythias, either", 'title': 'aristotle.txt', 'user_id': 'bf417057-f104-4e75-8579-c74d26fcbed3', 'version': 'v0', 'chunk_order': 12, 'document_id': 'a2645197-d07f-558d-ba55-f7a60eb29621', 'extraction_id': 'b7bbd497-311a-5dc8-8a51-79e2208739e0', 'associatedQuery': 'Who was Aristotle'}}, {'id': '33b2dbd7-2f3a-5450-9618-976a996bde2a', 'score': 0.6117302824500019, 'metadata': {'text': 'Transmission\nFurther information: List of writers influenced by Aristotle\nMore than 2300 years after his death, Aristotle remains one of the most influential people who ever lived.[142][143][144] He contributed to almost every field of human knowledge then in existence, and he was the founder of many new fields. According to the philosopher Bryan Magee, "it is doubtful whether any human being has ever known as much as he did".[145]', 'title': 'aristotle.txt', 'user_id': 'bf417057-f104-4e75-8579-c74d26fcbed3', 'version': 'v0', 'chunk_order': 174, 'document_id': 'a2645197-d07f-558d-ba55-f7a60eb29621', 'extraction_id': 'b7bbd497-311a-5dc8-8a51-79e2208739e0', 'associatedQuery': 'Who was Aristotle'}}, {'id': '2d101d42-6317-5d8c-85c3-fb9b6d947c68', 'score': 0.610827455968717, 'metadata': {'text': "The immediate influence of Aristotle's work was felt as the Lyceum grew into the Peripatetic school. Aristotle's students included Aristoxenus, Dicaearchus, Demetrius of Phalerum, Eudemos of Rhodes, Harpalus, Hephaestion, Mnason of Phocis, Nicomachus, and Theophrastus. Aristotle's influence over Alexander the Great is seen in the latter's bringing with him on his expedition a host of zoologists, botanists, and researchers. He had also learned a great deal about Persian customs and traditions from his", 'title': 'aristotle.txt', 'user_id': 'bf417057-f104-4e75-8579-c74d26fcbed3', 'version': 'v0', 'chunk_order': 181, 'document_id': 'a2645197-d07f-558d-ba55-f7a60eb29621', 'extraction_id': 'b7bbd497-311a-5dc8-8a51-79e2208739e0', 'associatedQuery': 'Who was Aristotle'}}], 'kg_search_results': []}}
3
4rag_result = client.rag(query="Sample search query")
5# {'results': {'completion': {'id': 'chatcmpl-9llkGYsrG1YZaWkqYvzXr1eQNl0gA', 'choices': [{'finish_reason': 'stop', 'index': 0, 'message': {'content': 'The search results for the query "Sample search query" include various topics and excerpts related to Aristotle\'s works and other subjects. Here are the relevant references:\n\n1. **Categories of Aristotle\'s Works**:\n - On Interpretation [1], [2]\n - Prior Analytics [1], [2]\n - Posterior Analytics [1], [2]\n - Topics [1], [2]\n - On Sophistical Refutations [1], [2]\n\n2. **Aristotle\'s Theory on Sense Perceptions and Memory**:\n - Aristotle\'s belief that people receive sense perceptions and perceive them as impressions, leading to the weaving together of new experiences. The search for these impressions involves searching the memory itself, where recollection occurs when one retrieved experience naturally follows another [3], [4].\n\n3. **Medieval Judaism**:\n - References to Medieval Judaism [5], [6].\n\n4. **Scientific Style**:\n - References to Scientific Style [7], [8].\n\n5. **Recovery of Texts by Apellicon**:\n - Apellicon\'s efforts to recover degraded texts by copying them into new manuscripts and using guesswork to fill in unreadable gaps [9], [10].\n\nThese references provide a broad overview of the topics related to the query, including Aristotle\'s works, his theories on memory, Medieval Judaism, scientific style, and the recovery of ancient texts.', 'role': 'assistant'}}], 'created': 1721171976, 'model': 'gpt-4o-2024-05-13', 'object': 'chat.completion', 'system_fingerprint': 'fp_5e997b69d8', 'usage': {'completion_tokens': 286, 'prompt_tokens': 513, 'total_tokens': 799}}, 'search_results': {'vector_search_results': [{'id': 'd70e2776-befa-5b67-9da7-b76aedb7c101', 'score': 0.270276627830369, 'metadata': {'text': 'Categories\nOn Interpretation\nPrior Analytics\nPosterior Analytics\nTopics\nOn Sophistical Refutations', 'title': 'aristotle.txt', 'user_id': '76eea168-9f98-4672-af3b-2c26ec92d7f8', 'version': 'v0', 'chunk_order': 26, 'document_id': '4bb1e5e0-3bb3-54e0-bc71-69e68bce30c7', 'extraction_id': '9401dfe6-10dd-5eb1-8b88-de1927a6c556', 'associatedQuery': 'Sample search query'}}, {'id': 'f54c9cda-0053-5ea2-a22b-aaba6437518c', 'score': 0.270276627830369, 'metadata': {'text': 'Categories\nOn Interpretation\nPrior Analytics\nPosterior Analytics\nTopics\nOn Sophistical Refutations', 'title': 'aristotle.txt', 'user_id': '2acb499e-8428-543b-bd85-0d9098718220', 'version': 'v0', 'chunk_order': 26, 'document_id': '9fbe403b-c11c-5aae-8ade-ef22980c3ad1', 'extraction_id': 'bc497a0c-4b17-5e86-97d4-aa06474e0e5b', 'associatedQuery': 'Sample search query'}}, {'id': 'd0675bcd-23d1-5982-8114-1a6459faec3f', 'score': 0.242980153623792, 'metadata': {'text': 'Because Aristotle believes people receive all kinds of sense perceptions and perceive them as impressions, people are continually weaving together new impressions of experiences. To search for these impressions, people search the memory itself.[105] Within the memory, if one experience is offered instead of a specific memory, that person will reject this experience until they find what they are looking for. Recollection occurs when one retrieved experience naturally follows another. If the chain of', 'title': 'aristotle.txt', 'user_id': '76eea168-9f98-4672-af3b-2c26ec92d7f8', 'version': 'v0', 'chunk_order': 119, 'document_id': '4bb1e5e0-3bb3-54e0-bc71-69e68bce30c7', 'extraction_id': '9401dfe6-10dd-5eb1-8b88-de1927a6c556', 'associatedQuery': 'Sample search query'}}, {'id': '69aed771-061f-5360-90f1-0ce395601b98', 'score': 0.242980153623792, 'metadata': {'text': 'Because Aristotle believes people receive all kinds of sense perceptions and perceive them as impressions, people are continually weaving together new impressions of experiences. To search for these impressions, people search the memory itself.[105] Within the memory, if one experience is offered instead of a specific memory, that person will reject this experience until they find what they are looking for. Recollection occurs when one retrieved experience naturally follows another. If the chain of', 'title': 'aristotle.txt', 'user_id': '2acb499e-8428-543b-bd85-0d9098718220', 'version': 'v0', 'chunk_order': 119, 'document_id': '9fbe403b-c11c-5aae-8ade-ef22980c3ad1', 'extraction_id': 'bc497a0c-4b17-5e86-97d4-aa06474e0e5b', 'associatedQuery': 'Sample search query'}}, {'id': 'dadd2d48-a2b7-5e55-9a8c-1030712c5ca0', 'score': 0.20218510005651702, 'metadata': {'text': 'Medieval Judaism', 'title': 'aristotle.txt', 'user_id': '76eea168-9f98-4672-af3b-2c26ec92d7f8', 'version': 'v0', 'chunk_order': 202, 'document_id': '4bb1e5e0-3bb3-54e0-bc71-69e68bce30c7', 'extraction_id': '9401dfe6-10dd-5eb1-8b88-de1927a6c556', 'associatedQuery': 'Sample search query'}}, {'id': 'da81f692-40d9-599b-a69b-25b6a5179b47', 'score': 0.20218510005651702, 'metadata': {'text': 'Medieval Judaism', 'title': 'aristotle.txt', 'user_id': '2acb499e-8428-543b-bd85-0d9098718220', 'version': 'v0', 'chunk_order': 202, 'document_id': '9fbe403b-c11c-5aae-8ade-ef22980c3ad1', 'extraction_id': 'bc497a0c-4b17-5e86-97d4-aa06474e0e5b', 'associatedQuery': 'Sample search query'}}, {'id': '0c4fea20-f7ee-520f-ae1f-155ecb398e1f', 'score': 0.19056136124594703, 'metadata': {'text': 'Scientific style', 'title': 'aristotle.txt', 'user_id': '2acb499e-8428-543b-bd85-0d9098718220', 'version': 'v0', 'chunk_order': 92, 'document_id': '9fbe403b-c11c-5aae-8ade-ef22980c3ad1', 'extraction_id': 'bc497a0c-4b17-5e86-97d4-aa06474e0e5b', 'associatedQuery': 'Sample search query'}}, {'id': 'c3c3145a-5d9d-5362-9629-f9159a027a9d', 'score': 0.19051768949311598, 'metadata': {'text': 'Scientific style', 'title': 'aristotle.txt', 'user_id': '76eea168-9f98-4672-af3b-2c26ec92d7f8', 'version': 'v0', 'chunk_order': 92, 'document_id': '4bb1e5e0-3bb3-54e0-bc71-69e68bce30c7', 'extraction_id': '9401dfe6-10dd-5eb1-8b88-de1927a6c556', 'associatedQuery': 'Sample search query'}}, {'id': '63e3a252-90bd-5494-9f9f-aee772f4db54', 'score': 0.18900877964391904, 'metadata': {'text': 'Apellicon sought to recover the texts, many of which were seriously degraded at this point due to the conditions in which they were stored. He had them copied out into new manuscripts, and used his best guesswork to fill in the gaps where the originals were unreadable.[216]:\u200a5–6', 'title': 'aristotle.txt', 'user_id': '76eea168-9f98-4672-af3b-2c26ec92d7f8', 'version': 'v0', 'chunk_order': 228, 'document_id': '4bb1e5e0-3bb3-54e0-bc71-69e68bce30c7', 'extraction_id': '9401dfe6-10dd-5eb1-8b88-de1927a6c556', 'associatedQuery': 'Sample search query'}}, {'id': '2c1183a8-e130-5432-a311-ee1f0f194562', 'score': 0.18894388145542895, 'metadata': {'text': 'Apellicon sought to recover the texts, many of which were seriously degraded at this point due to the conditions in which they were stored. He had them copied out into new manuscripts, and used his best guesswork to fill in the gaps where the originals were unreadable.[216]:\u200a5–6', 'title': 'aristotle.txt', 'user_id': '2acb499e-8428-543b-bd85-0d9098718220', 'version': 'v0', 'chunk_order': 228, 'document_id': '9fbe403b-c11c-5aae-8ade-ef22980c3ad1', 'extraction_id': 'bc497a0c-4b17-5e86-97d4-aa06474e0e5b', 'associatedQuery': 'Sample search query'}}], 'kg_search_results': None}}}

Advanced Authentication Features

R2R offers several advanced authentication features to enhance security and user experience:

Password Management

Users can change their passwords and request password resets:

1# Change password
2change_password_result = client.change_password("password123", "new_password")
3# {"result": {"message": "Password changed successfully"}}
4
5# Request password reset
6reset_request_result = client.request_password_reset("[email protected]")
7# {"result": {"message": "If the email exists, a reset link has been sent"}}
8
9# Confirm password reset (after user receives reset token)
10reset_confirm_result = client.confirm_password_reset("reset_token_here", "new_password")
11# {"result": {"message": "Password reset successfully"}}

User Profile Management

Users can view and update their profiles:

1# Get user profile
2profile = client.user()
3# {'results': {'email': '[email protected]', 'id': '76eea168-9f98-4672-af3b-2c26ec92d7f8', 'hashed_password': 'null', 'is_superuser': False, 'is_active': True, 'is_verified': True, 'verification_code_expiry': None, 'name': None, 'bio': None, 'profile_picture': None, 'created_at': '2024-07-16T23:06:42.123303Z', 'updated_at': '2024-07-16T23:22:48.256239Z'}}
4
5# Update user profile
6update_result = client.update_user(name="John Doe", bio="R2R enthusiast")
7# {'results': {'email': '[email protected]', 'id': '76eea168-9f98-4672-af3b-2c26ec92d7f8', 'hashed_password': 'null', 'is_superuser': False, 'is_active': True, 'is_verified': True, 'verification_code_expiry': None, 'name': 'John Doe', 'bio': 'R2R enthusiast', 'profile_picture': None, 'created_at': '2024-07-16T23:06:42.123303Z', 'updated_at': '2024-07-16T23:22:48.256239Z'}}

Account Deletion

Users can delete their accounts:

1# Delete account (requires password confirmation)
2user_id = register_response["results"]["id"] # input unique id here
3delete_result = client.delete_user(user_id, "password123")
4# {'results': {'message': 'User account deleted successfully'}}

Logout

To end a user session:

1logout_result = client.logout()
2print(f"Logout Result:\n{logout_result}")
3# {'results': {'message': 'Logged out successfully'}}

Superuser Capabilities and Default Admin Creation

R2R includes powerful superuser capabilities and a mechanism for default admin creation, which are crucial for system management and initial setup. Let’s explore these features:

Superuser Capabilities

Superusers in R2R have elevated privileges that allow them to perform system-wide operations and access sensitive information. Some key superuser capabilities include:

  1. User Management: Superusers can view, modify, and delete user accounts.
  2. System-wide Document Access: They can access and manage documents across all users.
  3. Analytics and Observability: Superusers have access to system-wide analytics and logs.
  4. Configuration Management: They can modify system configurations and settings.

To use superuser capabilities, you need to authenticate as a superuser. The methods for accessing these features are the same as regular user methods, but with expanded scope and permissions.

Default Admin Creation

R2R automatically creates a default admin user during initialization. This process is handled by the R2RAuthProvider class. Here’s how it works:

  1. During system initialization, R2R attempts to create a default admin user.
  2. The admin email and password are typically set through environment variables or configuration files.
  3. If the admin user already exists, R2R logs this information and continues without creating a duplicate.

The relevant part of the configuration that affects this process is:

1[auth]
2provider = "r2r"
3access_token_lifetime_in_minutes = 60
4refresh_token_lifetime_in_days = 7
5require_authentication = true
6require_email_verification = false
7default_admin_email = "[email protected]"
8default_admin_password = "change_me_immediately"
  • With "require_authentication": false, the system allows unauthenticated access for testing and development. In a production environment, this should be set to true.
  • "require_email_verification": false means that email verification is not required for new users, including the default admin. For increased security in production, consider enabling this.

Accessing Superuser Features

To access superuser features, you need to authenticate as the default admin or another user with superuser privileges. Here’s an example of how to do this:

1from r2r import R2RClient
2
3client = R2RClient("http://localhost:7272")
4
5# Login as admin
6login_result = client.login("[email protected]", "change_me_immediately")
7
8# Now you can access superuser features, for example:
9users_overview = client.users_overview()
10# {'results': [{'user_id': '2acb499e-8428-543b-bd85-0d9098718220', 'num_files': 2, 'total_size_in_bytes': 73672, 'document_ids': ['c4967f03-1780-5161-8e1d-57b55aa65076', '9fbe403b-c11c-5aae-8ade-ef22980c3ad1']}, {'user_id': 'ac730ec3-7d3d-451a-a166-e7ac7c57b198', 'num_files': 1, 'total_size_in_bytes': 73353, 'document_ids': ['d4861e78-cf02-5184-9b6a-d5bdbddd39b2']}, {'user_id': 'e0514342-e51a-43e5-8aaa-665468102dce', 'num_files': 1, 'total_size_in_bytes': 73353, 'document_ids': ['f4fbe534-b7d6-5fec-9d41-9093b2112732']}]}
11
12# Access system-wide logs
13logs = client.logs()
14# {'results': [{'run_id': '645cb90f-c281-4188-b93b-94fb383170f6', 'run_type': 'search', 'entries': [{'key': 'search_latency', 'value': '0.43'}, { ...
15
16# Perform analytics
17analytics_result = client.analytics(
18 {"all_latencies": "search_latency"},
19 {"search_latencies": ["basic_statistics", "search_latency"]}
20)
21# {'results': {'filtered_logs': {'search_latencies': [{'timestamp': '2024-07-18 18:10:26', 'log_id': '645cb90f-c281-4188-b93b-94fb383170f6', 'key': 'search_latency', 'value': '0.43', 'rn': 3}, {'timestamp': '2024-07-18 18:04:54', 'log_id': 'a22d6a4c-3e68-4f01-b129-c9cbb5ae0b86', 'key': 'search_latency', 'value': '0.76', 'rn': 3}, {'timestamp': '2024-07-18 17:45:04', 'log_id': '253aa7b2-5abc-46d4-9bc3-f1ee47598bc5', 'key': 'search_latency', 'value': '0.43', 'rn': 3}, {'timestamp': '2024-07-18 17:44:47', 'log_id': 'add3d166-392c-44e0-aec2-d00d97a584f9', 'key': 'search_latency', 'value': '0.71', 'rn': 3}, {'timestamp': '2024-07-18 17:43:40', 'log_id': '9b64d038-aa56-44c9-af5e-96091fff62f2', 'key': 'search_latency', 'value': '0.44', 'rn': 3}, {'timestamp': '2024-07-18 17:43:20', 'log_id': '2a433a26-dc5b-4460-823a-58f01070e44d', 'key': 'search_latency', 'value': '0.37', 'rn': 3}, {'timestamp': '2024-07-18 17:43:16', 'log_id': '71a05fb2-5993-45c3-af3d-5019a745a33d', 'key': 'search_latency', 'value': '0.72', 'rn': 3}, {'timestamp': '2024-07-16 23:19:35', 'log_id': 'fada5559-ccd1-42f3-81a1-c96dcbc2ff08', 'key': 'search_latency', 'value': '0.34', 'rn': 3}, {'timestamp': '2024-07-16 23:07:32', 'log_id': '530bc25c-efc9-4b10-b46f-529c64c89fdf', 'key': 'search_latency', 'value': '0.62', 'rn': 3}, {'timestamp': '2024-07-16 23:07:14', 'log_id': '5c977046-bd71-4d95-80ba-dcf16e33cfd5', 'key': 'search_latency', 'value': '0.72', 'rn': 3}, {'timestamp': '2024-07-16 23:06:44', 'log_id': 'a2bef456-7370-4977-83cf-a60de5abd0cf', 'key': 'search_latency', 'value': '0.44', 'rn': 3}, {'timestamp': '2024-07-16 23:02:10', 'log_id': 'ee8d8bb4-7bc5-4c92-a9a2-c3ddd9f6bcd9', 'key': 'search_latency', 'value': '0.53', 'rn': 3}, {'timestamp': '2024-07-16 22:00:48', 'log_id': '13701f93-a2ab-4182-abd0-a401aa8e720a', 'key': 'search_latency', 'value': '0.52', 'rn': 3}, {'timestamp': '2024-07-16 21:59:17', 'log_id': '17bd24d7-37e2-4838-9830-c92110f492c7', 'key': 'search_latency', 'value': '0.30', 'rn': 3}, {'timestamp': '2024-07-16 21:59:16', 'log_id': 'd1d1551b-80cc-4f93-878a-7d7579aa3b9e', 'key': 'search_latency', 'value': '0.43', 'rn': 3}, {'timestamp': '2024-07-16 21:55:46', 'log_id': '0291254e-262f-4d9d-ace2-b98c2eaae547', 'key': 'search_latency', 'value': '0.42', 'rn': 3}, {'timestamp': '2024-07-16 21:55:45', 'log_id': '74df032f-e9d6-4ba9-ae0e-1be58927c2b1', 'key': 'search_latency', 'value': '0.57', 'rn': 3}, {'timestamp': '2024-07-16 21:54:36', 'log_id': '413982fd-3588-42cc-8009-8c686a85f27e', 'key': 'search_latency', 'value': '0.55', 'rn': 3}, {'timestamp': '2024-07-16 03:35:48', 'log_id': 'ae79062e-f4f0-4fb1-90f4-4ddcb8ae0cc4', 'key': 'search_latency', 'value': '0.50', 'rn': 3}, {'timestamp': '2024-07-16 03:26:10', 'log_id': '9fd51a36-9fdf-4a70-89cb-cb0d43dd0b63', 'key': 'search_latency', 'value': '0.41', 'rn': 3}, {'timestamp': '2024-07-16 03:01:18', 'log_id': '6cb79d2e-c431-447e-bbbb-99f96d56784e', 'key': 'search_latency', 'value': '0.67', 'rn': 3}, {'timestamp': '2024-07-16 01:29:44', 'log_id': '34eea2d3-dd98-47fb-ae3b-05e1001850a5', 'key': 'search_latency', 'value': '0.42', 'rn': 3}, {'timestamp': '2024-07-16 01:29:25', 'log_id': '5204d260-4ad3-49ce-9b38-1043ceae65ac', 'key': 'search_latency', 'value': '0.58', 'rn': 3}]}, 'search_latencies': {'Mean': 0.517, 'Median': 0.5, 'Mode': 0.43, 'Standard Deviation': 0.132, 'Variance': 0.018}}}

Security Considerations for Superusers

When using superuser capabilities, keep the following security considerations in mind:

  1. Limit Superuser Access: Only grant superuser privileges to trusted individuals who require full system access.
  2. Use Strong Passwords: Ensure that superuser accounts, especially the default admin, use strong, unique passwords.
  3. Enable Authentication and Verification: In production, set "require_authentication": true and "require_email_verification": true for enhanced security.
  4. Audit Superuser Actions: Regularly review logs of superuser activities to detect any unusual or unauthorized actions.
  5. Rotate Credentials: Periodically update superuser credentials, including the default admin password.

By understanding and properly managing superuser capabilities and default admin creation, you can ensure secure and effective administration of your R2R deployment.

Security Considerations

When implementing user authentication, consider the following security best practices:

  1. Use HTTPS: Always use HTTPS in production to encrypt data in transit.
  2. Implement rate limiting: Protect against brute-force attacks by limiting login attempts.
  3. Use secure password hashing: R2R uses bcrypt for password hashing by default, which is a secure choice.
  4. Implement multi-factor authentication (MFA): Consider adding MFA for an extra layer of security.
  5. Regular security audits: Conduct regular security audits of your authentication system.

Customizing Authentication

R2R’s authentication system is flexible and can be customized to fit your specific needs:

  1. Custom user fields: Extend the User model to include additional fields.
  2. OAuth integration: Integrate with third-party OAuth providers for social login.
  3. Custom password policies: Implement custom password strength requirements.
  4. User roles and permissions: Implement a role-based access control system.

Troubleshooting

Here are some common issues and their solutions:

  1. Login fails after registration: Ensure email verification is completed if enabled.
  2. Token refresh fails: Check if the refresh token has expired; the user may need to log in again.
  3. Unable to change password: Verify that the current password is correct.

Conclusion

R2R provides a comprehensive set of user authentication and management features, allowing developers to create secure and user-friendly applications. By leveraging these capabilities, you can implement robust user authentication, document management, and access control in your R2R-based projects.

For more advanced use cases or custom implementations, refer to the R2R documentation or reach out to the community for support.