Struct ParseSessionHandle

Source
pub struct ParseSessionHandle<'a> { /* private fields */ }
Expand description

Provides methods for interacting with Parse Server sessions.

An instance of ParseSessionHandle is obtained by calling the session() method on a Parse instance. It allows for operations such as retrieving the current session’s details, fetching specific sessions by ID (Master Key required), deleting sessions (Master Key required), updating sessions (Master Key required), and listing all sessions (Master Key required).

This handle operates in the context of the Parse it was created from, using its configuration (server URL, app ID, keys) for API requests.

Implementations§

Source§

impl<'a> ParseSessionHandle<'a>

Source

pub fn new(client: &'a Parse) -> Self

Creates a new ParseSessionHandle.

This constructor is typically called by Parse::session().

§Arguments
  • client: A reference to the Parse instance that this handle will operate upon.
Source

pub async fn me(&self) -> Result<ParseSession, ParseError>

Retrieves the current user’s session details.

This method makes a GET request to the /sessions/me endpoint. It requires an active session token to be configured in the Parse (typically set after a successful login or signup). The server then returns the full details of the session associated with that token.

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 ParseSession object for the current session if successful, or a ParseError if the request fails (e.g., session token invalid/expired, network issue, or no session token present).

§Examples
use parse_rs::{Parse, ParseError, user::LoginRequest};


// Assume a user has logged in, so client.session_token() is Some(...)
// let login_details = LoginRequest { username: "test_user", password: "password123" };
// client.user().login(&login_details).await?;

if client.is_authenticated() {
    match client.session().me().await {
        Ok(current_session) => {
            println!("Current session details retrieved for user: {:?}", current_session.user);
            println!("Session token: {}", current_session.session_token);
            println!("Expires at: {:?}", current_session.expires_at);
            // The session token in current_session should match client.session_token()
            assert_eq!(Some(current_session.session_token.as_str()), client.session_token());
        }
        Err(e) => eprintln!("Failed to get current session details: {}", e),
    }
} else {
    println!("No user is currently authenticated to get session details.");
}
Source

pub async fn get_by_object_id( &self, object_id: &str, ) -> Result<ParseSession, ParseError>

Retrieves a specific session by its objectId.

This method makes a GET request to the /sessions/:objectId endpoint. It requires the Master Key to be configured in the Parse for authorization, as accessing arbitrary session objects is a privileged operation.

§Arguments
  • object_id: A string slice representing the objectId of the session to retrieve.
§Returns

A Result containing the ParseSession object if found and the Master Key is valid, or a ParseError if the session is not found, the Master Key is missing or invalid, or any other error occurs (e.g., network issue).

§Examples
use parse_rs::{Parse, ParseError};

// Ensure the client is initialized with the Master Key for this operation
let client = Parse::new(&server_url, &app_id, None, None, Some(&master_key))?;

let session_object_id_to_fetch = "someValidSessionObjectId"; // Replace with an actual session objectId

match client.session().get_by_object_id(session_object_id_to_fetch).await {
    Ok(session) => {
        println!("Successfully fetched session with objectId: {}", session.object_id);
        println!("Associated user: {:?}", session.user);
        println!("Session token: {}", session.session_token);
    }
    Err(e) => {
        eprintln!("Failed to get session by objectId '{}': {}", session_object_id_to_fetch, e);
        // This could be due to various reasons: session not found, master key invalid, network error, etc.
        // e.g., if master key is missing or wrong, ParseError::MasterKeyMissingOrInvalid might be returned by the server (as unauthorized).
        // e.g., if session_object_id_to_fetch does not exist, ParseError::ObjectNotFound might be returned.
    }
}
Source

pub async fn delete_by_object_id( &self, object_id: &str, ) -> Result<(), ParseError>

Deletes a specific session by its objectId.

This method makes a DELETE request to the /sessions/:objectId endpoint. It requires the Master Key to be configured in the Parse for authorization, as deleting arbitrary session objects is a privileged operation. Successfully deleting a session effectively invalidates that session token, forcing the user to log in again.

§Arguments
  • object_id: A string slice representing the objectId of the session to delete.
§Returns

A Result containing () (an empty tuple) if the session is successfully deleted. Returns a ParseError if the session is not found, the Master Key is missing or invalid, or any other error occurs (e.g., network issue).

§Examples
use parse_rs::{Parse, ParseError};

// Ensure the client is initialized with the Master Key for this operation
let client = Parse::new(&server_url, &app_id, None, None, Some(&master_key))?;

let session_object_id_to_delete = "someSessionObjectIdToDelete"; // Replace with an actual session objectId

match client.session().delete_by_object_id(session_object_id_to_delete).await {
    Ok(_) => {
        println!("Successfully deleted session with objectId: {}", session_object_id_to_delete);
    }
    Err(e) => {
        eprintln!("Failed to delete session by objectId '{}': {}", session_object_id_to_delete, e);
        // Common errors: ParseError::ObjectNotFound if the session doesn't exist,
        // ParseError::MasterKeyMissingOrInvalid (or generic unauthorized) if master key is wrong.
    }
}
Source

pub async fn update_by_object_id<T: Serialize + Send + Sync>( &self, object_id: &str, session_data: &T, ) -> Result<SessionUpdateResponse, ParseError>

Updates a specific session by its objectId.

This method makes a PUT request to the /sessions/:objectId endpoint, allowing modifications to the specified session object. It requires the Master Key to be configured in the Parse for authorization. The session_data argument should be a serializable struct or map containing the fields to be updated on the session object.

Note: Not all fields on a session object are typically mutable. Consult the Parse Server documentation for details on which fields can be updated.

§Type Parameters
  • T: The type of the session_data argument. This type must implement Serialize, Send, and Sync. It can be a custom struct representing the updatable fields or a serde_json::Value for dynamic updates.
§Arguments
  • object_id: A string slice representing the objectId of the session to update.
  • session_data: A reference to the data containing the fields to update.
§Returns

A Result containing a SessionUpdateResponse (which typically includes the updatedAt timestamp) if the session is successfully updated. Returns a ParseError if the session is not found, the Master Key is missing or invalid, the update data is invalid, or any other error occurs.

§Examples
use parse_rs::{Parse, ParseError, session::SessionUpdateResponse};
use serde_json::json; // For creating a JSON value to update

// Client must be initialized with the Master Key
let client = Parse::new(&server_url, &app_id, None, None, Some(&master_key))?;

let session_object_id_to_update = "someSessionObjectIdToUpdate"; // Replace with an actual session objectId

// Example: Update a custom field on the session. Parse Server must be configured to allow this.
// Let's assume we want to add/update a field `customData: { "notes": "privileged update" }`
let update_payload = json!({
    "customData": {
        "notes": "privileged update by master key"
    }
});

match client.session().update_by_object_id(session_object_id_to_update, &update_payload).await {
    Ok(response) => {
        println!(
            "Successfully updated session '{}'. New updatedAt: {}",
            session_object_id_to_update,
            response.updated_at
        );
    }
    Err(e) => {
        eprintln!(
            "Failed to update session by objectId '{}': {}",
            session_object_id_to_update, e
        );
        // Common errors: ParseError::ObjectNotFound, ParseError::MasterKeyMissingOrInvalid, or invalid update payload.
    }
}
Source

pub async fn get_all_sessions( &self, query_string: Option<&str>, ) -> Result<Vec<ParseSession>, ParseError>

Retrieves multiple sessions, optionally filtered and paginated using a query string.

This method makes a GET request to the /sessions endpoint. It requires the Master Key to be configured in the Parse for authorization, as listing all sessions is a highly privileged operation.

The query_string argument allows for server-side filtering, pagination, ordering, and inclusion of related data (like the user object via include=user).

§Arguments
  • query_string: An optional string slice representing the URL-encoded query parameters. For example: "limit=10&skip=20&include=user&where={\"user\":{\"$inQuery\":{\"where\":{\"username\":\"test_user\"},\"className\":\"_User\"}}}" If None, all sessions (up to the server’s default limit) are requested.
§Returns

A Result containing a Vec<ParseSession> if the request is successful. The vector will contain the session objects matching the query. Returns a ParseError if the Master Key is missing or invalid, the query string is malformed, or any other error occurs.

§Examples
use parse_rs::{Parse, ParseError};

// Client must be initialized with the Master Key
let client = Parse::new(&server_url, &app_id, None, None, Some(&master_key))?;

// Example 1: Get all sessions (respecting server default limit) and include user data
match client.session().get_all_sessions(Some("include=user")).await {
    Ok(sessions) => {
        println!("Successfully retrieved {} sessions (with user data):", sessions.len());
        for session in sessions {
            println!("  Session ID: {}, User: {:?}", session.object_id, session.user);
        }
    }
    Err(e) => eprintln!("Failed to get all sessions with user data: {}", e),
}

// Example 2: Get the first 5 sessions, ordered by creation date descending
let query_params = "limit=5&order=-createdAt";
match client.session().get_all_sessions(Some(query_params)).await {
    Ok(sessions) => {
        println!("\nSuccessfully retrieved {} sessions (first 5, newest first):", sessions.len());
        for session in sessions {
            println!("  Session ID: {}, Created At: {:?}", session.object_id, session.created_at);
        }
    }
    Err(e) => eprintln!("Failed to get paginated/ordered sessions: {}", e),
}

// Example 3: Get sessions without any query parameters (server defaults apply)
match client.session().get_all_sessions(None).await {
    Ok(sessions) => {
        println!("\nSuccessfully retrieved {} sessions (server defaults):", sessions.len());
    }
    Err(e) => eprintln!("Failed to get sessions with no query: {}", e),
}

Auto Trait Implementations§

§

impl<'a> Freeze for ParseSessionHandle<'a>

§

impl<'a> !RefUnwindSafe for ParseSessionHandle<'a>

§

impl<'a> Send for ParseSessionHandle<'a>

§

impl<'a> Sync for ParseSessionHandle<'a>

§

impl<'a> Unpin for ParseSessionHandle<'a>

§

impl<'a> !UnwindSafe for ParseSessionHandle<'a>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,