Skip to main content

Session

Struct Session 

Source
pub struct Session {
    pub id: String,
    pub shop: ShopDomain,
    pub access_token: String,
    pub scopes: AuthScopes,
    pub is_online: bool,
    pub expires: Option<DateTime<Utc>>,
    pub state: Option<String>,
    pub shopify_session_id: Option<String>,
    pub associated_user: Option<AssociatedUser>,
    pub associated_user_scopes: Option<AuthScopes>,
    pub refresh_token: Option<String>,
    pub refresh_token_expires_at: Option<DateTime<Utc>>,
}
Expand description

Represents an authenticated session for Shopify API calls.

Sessions hold the authentication state needed to make API requests on behalf of a shop. They can be either online (user-specific) or offline (app-level).

§Thread Safety

Session is Send + Sync, making it safe to share across threads.

§Serialization

Sessions can be serialized to JSON for storage and deserialized when needed:

use shopify_sdk::{Session, ShopDomain, AuthScopes};

let session = Session::new(
    "session-id".to_string(),
    ShopDomain::new("my-store").unwrap(),
    "access-token".to_string(),
    "read_products".parse().unwrap(),
    false,
    None,
);

// Serialize to JSON
let json = serde_json::to_string(&session).unwrap();

// Deserialize from JSON
let restored: Session = serde_json::from_str(&json).unwrap();
assert_eq!(session, restored);

§Example

use shopify_sdk::{Session, ShopDomain, AuthScopes};

let session = Session::new(
    "session-id".to_string(),
    ShopDomain::new("my-store").unwrap(),
    "access-token".to_string(),
    "read_products".parse().unwrap(),
    false, // offline session
    None,  // no expiration
);

assert!(session.is_active());
assert!(!session.expired());

Fields§

§id: String

Unique identifier for this session.

For offline sessions: "offline_{shop}" (e.g., "offline_my-store.myshopify.com") For online sessions: "{shop}_{user_id}" (e.g., "my-store.myshopify.com_12345")

§shop: ShopDomain

The shop this session is for.

§access_token: String

The access token for API authentication.

§scopes: AuthScopes

The OAuth scopes granted to this session.

§is_online: bool

Whether this is an online (user-specific) session.

§expires: Option<DateTime<Utc>>

When this session expires, if applicable.

Offline sessions have None (they don’t expire) unless using expiring tokens. Online sessions have a specific expiration time.

§state: Option<String>

OAuth state parameter, if applicable.

Used during the OAuth flow for CSRF protection.

§shopify_session_id: Option<String>

Shopify-provided session ID, if applicable.

§associated_user: Option<AssociatedUser>

User information for online sessions.

Only present for online sessions (when is_online is true).

§associated_user_scopes: Option<AuthScopes>

User-specific scopes for online sessions.

These may be different from the app’s granted scopes, representing what the specific user is allowed to do.

§refresh_token: Option<String>

The refresh token for obtaining new access tokens.

Only present for expiring offline tokens. Use with refresh_access_token to obtain a new access token before the current one expires.

§refresh_token_expires_at: Option<DateTime<Utc>>

When the refresh token expires, if applicable.

None indicates the refresh token does not expire or is not present. Use refresh_token_expired to check if the refresh token needs to be renewed.

Implementations§

Source§

impl Session

Source

pub const fn new( id: String, shop: ShopDomain, access_token: String, scopes: AuthScopes, is_online: bool, expires: Option<DateTime<Utc>>, ) -> Self

Creates a new session with the specified parameters.

This constructor maintains backward compatibility with existing code. New fields (associated_user, associated_user_scopes, refresh_token, and refresh_token_expires_at) default to None.

For online sessions with user information, use Session::with_user instead.

§Arguments
  • id - Unique session identifier
  • shop - The shop domain
  • access_token - The access token for API calls
  • scopes - OAuth scopes granted to this session
  • is_online - Whether this is a user-specific session
  • expires - When this session expires (None for offline sessions)
§Example
use shopify_sdk::{Session, ShopDomain, AuthScopes};

let session = Session::new(
    "offline_my-store.myshopify.com".to_string(),
    ShopDomain::new("my-store").unwrap(),
    "access-token".to_string(),
    "read_products".parse().unwrap(),
    false,
    None,
);
Source

pub const fn with_user( id: String, shop: ShopDomain, access_token: String, scopes: AuthScopes, expires: Option<DateTime<Utc>>, associated_user: AssociatedUser, associated_user_scopes: Option<AuthScopes>, ) -> Self

Creates a new online session with associated user information.

This is a convenience constructor for online sessions that includes user details and user-specific scopes.

§Arguments
  • id - Unique session identifier (typically "{shop}_{user_id}")
  • shop - The shop domain
  • access_token - The access token for API calls
  • scopes - OAuth scopes granted to this session
  • expires - When this session expires
  • associated_user - The user who authorized this session
  • associated_user_scopes - User-specific scopes (if different from app scopes)
§Example
use shopify_sdk::{Session, ShopDomain, AuthScopes, AssociatedUser};
use chrono::{Utc, Duration};

let shop = ShopDomain::new("my-store").unwrap();
let user = AssociatedUser::new(
    12345,
    "Jane".to_string(),
    "Doe".to_string(),
    "jane@example.com".to_string(),
    true, true, "en".to_string(), false,
);

let session = Session::with_user(
    Session::generate_online_id(&shop, 12345),
    shop,
    "access-token".to_string(),
    "read_products".parse().unwrap(),
    Some(Utc::now() + Duration::hours(1)),
    user,
    Some("read_products".parse().unwrap()),
);

assert!(session.is_online);
assert!(session.associated_user.is_some());
Source

pub fn generate_offline_id(shop: &ShopDomain) -> String

Generates a session ID for an offline session.

The ID format is "offline_{shop}" where {shop} is the full shop domain.

§Example
use shopify_sdk::{Session, ShopDomain};

let shop = ShopDomain::new("my-store").unwrap();
let id = Session::generate_offline_id(&shop);
assert_eq!(id, "offline_my-store.myshopify.com");
Source

pub fn generate_online_id(shop: &ShopDomain, user_id: u64) -> String

Generates a session ID for an online session.

The ID format is "{shop}_{user_id}" where {shop} is the full shop domain and {user_id} is the Shopify user ID.

§Example
use shopify_sdk::{Session, ShopDomain};

let shop = ShopDomain::new("my-store").unwrap();
let id = Session::generate_online_id(&shop, 12345);
assert_eq!(id, "my-store.myshopify.com_12345");
Source

pub fn from_access_token_response( shop: ShopDomain, response: &AccessTokenResponse, ) -> Self

Creates a session from an OAuth access token response.

This factory method automatically:

  • Generates the appropriate session ID based on session type
  • Parses scopes from the response
  • Calculates expiration time from expires_in seconds
  • Sets is_online based on presence of associated user
  • Populates refresh token fields if present in the response
§Arguments
  • shop - The shop domain
  • response - The OAuth access token response from Shopify
§Example
use shopify_sdk::{Session, ShopDomain};
use shopify_sdk::auth::session::AccessTokenResponse;

let shop = ShopDomain::new("my-store").unwrap();
let response = AccessTokenResponse {
    access_token: "access-token".to_string(),
    scope: "read_products,write_orders".to_string(),
    expires_in: None,
    associated_user_scope: None,
    associated_user: None,
    session: None,
    refresh_token: None,
    refresh_token_expires_in: None,
};

let session = Session::from_access_token_response(shop, &response);
assert!(!session.is_online);
assert_eq!(session.id, "offline_my-store.myshopify.com");
Source

pub fn expired(&self) -> bool

Returns true if this session has expired.

Sessions without an expiration time are considered never expired.

Source

pub fn is_active(&self) -> bool

Returns true if this session is active (not expired and has access token).

Source

pub fn refresh_token_expired(&self) -> bool

Returns true if the refresh token has expired or will expire within 60 seconds.

This method uses a 60-second buffer (matching the Ruby SDK) to ensure you have time to refresh the token before it actually expires.

Returns false if:

  • No refresh_token_expires_at is set (token doesn’t expire)
  • The refresh token has more than 60 seconds before expiration
§Example
use shopify_sdk::{Session, ShopDomain, AuthScopes};
use chrono::{Utc, Duration};

// Session without refresh token expiration
let session = Session::new(
    "session-id".to_string(),
    ShopDomain::new("my-store").unwrap(),
    "access-token".to_string(),
    AuthScopes::new(),
    false,
    None,
);
assert!(!session.refresh_token_expired());

Trait Implementations§

Source§

impl Clone for Session

Source§

fn clone(&self) -> Session

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Session

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for Session

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl PartialEq for Session

Source§

fn eq(&self, other: &Session) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Serialize for Session

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl Eq for Session

Source§

impl StructuralPartialEq for Session

Auto Trait Implementations§

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
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> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. 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<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

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> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,