pub struct ParseUserHandle<'a> { /* private fields */ }Expand description
Provides methods for managing user authentication and user-specific operations.
An instance of ParseUserHandle is obtained by calling the user()
method on a Parse instance. It allows for operations such as signing up new users,
logging in existing users, fetching the current user’s details, logging out, and requesting password resets.
The handle maintains a mutable reference to the Parse to update its session state (e.g., session_token)
upon successful login or signup, and to clear it on logout.
Implementations§
Source§impl ParseUserHandle<'_>
impl ParseUserHandle<'_>
Sourcepub fn new(client: &mut Parse) -> ParseUserHandle<'_>
pub fn new(client: &mut Parse) -> ParseUserHandle<'_>
Creates a new ParseUserHandle.
This constructor is typically called by Parse::user().
§Arguments
client: A mutable reference to theParseinstance that this handle will operate upon.
Sourcepub async fn signup<T: Serialize + Send + Sync>(
&mut self,
user_data: &T,
) -> Result<SignupResponse, ParseError>
pub async fn signup<T: Serialize + Send + Sync>( &mut self, user_data: &T, ) -> Result<SignupResponse, ParseError>
Signs up a new user with the Parse Server.
This method sends the provided user data to the /users endpoint. Upon successful signup,
the Parse Server returns the new user’s objectId, a sessionToken, and createdAt timestamp.
The sessionToken is automatically stored in the Parse instance, making the new user
the current authenticated user for subsequent requests.
§Type Parameters
T: The type of theuser_dataargument. This type must implementSerialize,Send, andSync. Commonly, this will beSignupRequestfor standard username/password/email signups, but can also be aParseObjector aHashMap<String, Value>if you need to include additional custom fields during signup (assuming your Parse Server is configured to allow this).
§Arguments
user_data: A reference to the data for the new user. This typically includesusernameandpassword, and can optionally includeemailand other custom fields.
§Returns
A Result containing a SignupResponse if the signup is successful,
or a ParseError if the signup fails (e.g., username taken, invalid data, network issue).
§Examples
use parse_rs::{Parse, ParseError, user::SignupRequest};
use serde_json::Value;
use std::collections::HashMap;
// Example 1: Using SignupRequest for standard fields
let signup_details = SignupRequest {
username: "new_user_1",
password: "securePassword123",
email: Some("user1@example.com"),
};
match client.user().signup(&signup_details).await {
Ok(response) => {
println!("User '{}' signed up successfully! ObjectId: {}, Session Token: {}",
signup_details.username, response.object_id, response.session_token);
assert_eq!(client.session_token(), Some(response.session_token.as_str()));
}
Err(e) => eprintln!("Signup failed for user '{}': {}", signup_details.username, e),
}
// Example 2: Using HashMap for additional custom fields (if server allows)
let mut custom_signup_data = HashMap::new();
custom_signup_data.insert("username".to_string(), Value::String("new_user_2".to_string()));
custom_signup_data.insert("password".to_string(), Value::String("anotherSecurePass456".to_string()));
custom_signup_data.insert("email".to_string(), Value::String("user2@example.com".to_string()));
custom_signup_data.insert("customField".to_string(), Value::String("customValue".to_string()));
custom_signup_data.insert("age".to_string(), Value::Number(30.into()));
// match client.user().signup(&custom_signup_data).await {
// Ok(response) => {
// println!("User with custom data signed up! ObjectId: {}, Session: {}",
// response.object_id, response.session_token);
// }
// Err(e) => eprintln!("Custom signup failed: {}", e),
// }Sourcepub async fn login<T: Serialize + Send + Sync>(
&mut self,
user_data: &T,
) -> Result<ParseUser, ParseError>
pub async fn login<T: Serialize + Send + Sync>( &mut self, user_data: &T, ) -> Result<ParseUser, ParseError>
Logs in an existing user with the Parse Server.
This method sends the provided user credentials (typically username and password) to the /login endpoint.
Upon successful login, the Parse Server returns the full user object, including a sessionToken.
This sessionToken is automatically stored in the Parse instance, making the user
the current authenticated user for subsequent requests.
§Type Parameters
T: The type of theuser_dataargument. This type must implementSerialize,Send, andSync. Commonly, this will beLoginRequestfor standard username/password logins. It could also be aHashMap<String, Value>if the server supports other login mechanisms via the same endpoint, though this is less common for the standard/loginroute.
§Arguments
user_data: A reference to the credentials for the user to log in. This typically includesusernameandpassword.
§Returns
A Result containing the full ParseUser object if the login is successful,
or a ParseError if the login fails (e.g., invalid credentials, user not found, network issue).
§Examples
use parse_rs::{Parse, ParseError, user::LoginRequest};
// Assume "test_user" was previously signed up
let login_details = LoginRequest {
username: "test_user",
password: "password123",
};
match client.user().login(&login_details).await {
Ok(logged_in_user) => {
println!("User '{}' logged in successfully! Session Token: {}",
logged_in_user.username,
logged_in_user.session_token.as_deref().unwrap_or("N/A"));
assert_eq!(client.session_token(), logged_in_user.session_token.as_deref());
assert_eq!(logged_in_user.username, "test_user");
}
Err(e) => eprintln!("Login failed for user '{}': {}", login_details.username, e),
}Sourcepub async fn me(&self) -> Result<ParseUser, ParseError>
pub async fn me(&self) -> Result<ParseUser, ParseError>
Fetches the details of the currently authenticated user.
This method makes a GET request to the /users/me endpoint, which requires a valid
session token to be present in the Parse (set automatically after a successful
login or signup).
If no session token is available in the client, this method will return a
ParseError::SessionTokenMissing error without making a network request.
§Returns
A Result containing the ParseUser object for the currently
authenticated user if successful, or a ParseError if the request fails (e.g., session token
is invalid or expired, network issue, or no session token is present).
§Examples
use parse_rs::{Parse, ParseError, user::LoginRequest};
// First, log in a user (or sign them up)
// let login_details = LoginRequest { username: "test_user", password: "password123" };
// client.user().login(&login_details).await?;
if client.is_authenticated() {
match client.user().me().await {
Ok(current_user) => {
println!("Current user: {}, Email: {:?}",
current_user.username, current_user.email.as_deref().unwrap_or("N/A"));
// The sessionToken field in the returned ParseUser object from /users/me
// might be the same or a new one depending on server configuration.
// The client's session token remains the one used for the request.
}
Err(e) => eprintln!("Failed to fetch current user: {}", e),
}
} else {
println!("No user is currently authenticated.");
}Sourcepub async fn logout(&mut self) -> Result<(), ParseError>
pub async fn logout(&mut self) -> Result<(), ParseError>
Logs out the currently authenticated user.
This method sends a POST request to the /logout endpoint using the current session token
stored in the Parse. If successful, the Parse Server invalidates the session token.
This method also clears the session_token from the Parse instance, effectively
ending the current user’s session on the client-side as well.
If no session token is available in the client, this method will return a
ParseError::SessionTokenMissing error without making a network request.
§Returns
A Result containing () (an empty tuple) if the logout is successful, or a ParseError
if the request fails (e.g., session token already invalid, network issue, or no session token
is present).
§Examples
use parse_rs::{Parse, ParseError, user::LoginRequest};
// First, ensure a user is logged in
// let login_details = LoginRequest { username: "test_user", password: "password123" };
// client.user().login(&login_details).await?;
if client.is_authenticated() {
println!("User is authenticated with token: {:?}", client.session_token());
match client.user().logout().await {
Ok(_) => {
println!("User logged out successfully.");
assert!(!client.is_authenticated(), "Client should not be authenticated after logout.");
assert!(client.session_token().is_none(), "Session token should be cleared after logout.");
}
Err(e) => eprintln!("Logout failed: {}", e),
}
} else {
println!("No user was logged in to log out.");
}
// Attempting logout again when not authenticated should fail (or do nothing gracefully)
// match client.user().logout().await {
// Err(ParseError::SessionTokenMissing) => println!("Correctly failed: Session token missing for logout."),
// _ => eprintln!("Logout behavior when not authenticated is unexpected."),
// }Sourcepub async fn request_password_reset<T: Serialize + Send + Sync>(
&self,
email_data: &T,
) -> Result<(), ParseError>
pub async fn request_password_reset<T: Serialize + Send + Sync>( &self, email_data: &T, ) -> Result<(), ParseError>
Requests a password reset email to be sent to the user associated with the given email address.
This method sends a POST request to the /requestPasswordReset endpoint with the user’s email.
The Parse Server then handles sending the password reset email if a user with that email exists.
This operation does not require a session token and can be called publicly.
§Type Parameters
T: The type of theemail_dataargument. This type must implementSerialize,Send, andSync. Commonly, this will bePasswordResetRequest.
§Arguments
email_data: A reference to the data containing the email address for the password reset request.
§Returns
A Result containing () (an empty tuple) if the request is successfully sent to the server,
or a ParseError if the request fails (e.g., invalid email format, network issue).
Note: A successful response means the request was accepted by the server, not necessarily that
a user with that email exists or that an email was actually sent (to prevent leaking user information).
§Examples
use parse_rs::{Parse, ParseError, user::PasswordResetRequest};
let email_for_reset = "user_to_reset@example.com";
let reset_request_data = PasswordResetRequest { email: email_for_reset };
match client.user().request_password_reset(&reset_request_data).await {
Ok(_) => println!("Password reset request sent for email: {}", email_for_reset),
Err(e) => eprintln!("Failed to send password reset request for email '{}': {}", email_for_reset, e),
}Sourcepub async fn become_user(
&mut self,
session_token_to_become: &str,
) -> Result<ParseUser, ParseError>
pub async fn become_user( &mut self, session_token_to_become: &str, ) -> Result<ParseUser, ParseError>
Allows the current client to “become” another user by using that user’s session token.
This method makes a GET request to /users/me, but authenticates it using the
session_token_to_become provided as an argument, instead of the client’s current session token.
If the provided session token is valid, the server responds with the details of the user
associated with that token. Crucially, upon a successful response, this method replaces
the Parse’s current session_token with session_token_to_become.
This is a powerful operation and should be used with caution, typically in administrative contexts or when implementing features like “Log in as user” for support purposes. The client performing this operation must have access to the target user’s session token.
§Arguments
session_token_to_become: A string slice representing the session token of the user to become.
§Returns
A Result containing the ParseUser object for the user
whose session token was provided, if the operation is successful. Returns a ParseError
if the provided session token is invalid, expired, or if any other error occurs during
the request.
§Examples
use parse_rs::{Parse, ParseError};
// Assume `target_user_session_token` is a valid session token for another user, obtained securely.
let target_user_session_token = "r:someValidSessionTokenForAnotherUser";
println!("Client's current session token before 'become': {:?}", client.session_token());
match client.user().become_user(target_user_session_token).await {
Ok(newly_become_user) => {
println!("Successfully became user '{}' (ID: {}).",
newly_become_user.username,
newly_become_user.object_id.as_deref().unwrap_or("N/A"));
println!("Client's session token is now: {:?}", client.session_token());
assert_eq!(client.session_token(), Some(target_user_session_token));
}
Err(e) => {
eprintln!("Failed to become user with token '{}': {}", target_user_session_token, e);
// Client's original session token should be restored if 'become' failed.
println!("Client's session token after failed 'become': {:?}", client.session_token());
}
}