cipherstash-client 0.34.1-alpha.2

The official CipherStash SDK
Documentation
use crate::credentials::TokenExpiry;
use serde::{Deserialize, Serialize};

// FIXME: Don't Debug (or use opaque types) - this is a security risk
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UserToken {
    pub(crate) refresh_token: String,
    pub(crate) access_token: String,
    pub(crate) expiry: u64,
}

impl UserToken {
    pub fn access_token(&self) -> String {
        self.access_token.to_string()
    }

    pub fn as_header(&self) -> String {
        format!("Bearer {}", self.access_token)
    }

    /// Create a `UserToken` from a raw access token string.
    ///
    /// Token refresh is expected to be handled externally (e.g. by `OAuthStrategy`),
    /// so the expiry is set to `u64::MAX` and no refresh token is stored.
    pub fn from_access_token(access_token: impl Into<String>) -> Self {
        Self {
            access_token: access_token.into(),
            refresh_token: String::new(),
            expiry: u64::MAX,
        }
    }

    /// Create a new `UserToken` from the given `refresh_token`, `access_token`, and `expiry`.
    /// Available behind the `test-utils` feature and intended for testing purposes only.
    #[cfg(any(test, feature = "test-utils"))]
    pub fn new_from_raw(
        refresh_token: impl Into<String>,
        access_token: impl Into<String>,
        expiry: u64,
    ) -> Self {
        Self {
            refresh_token: refresh_token.into(),
            access_token: access_token.into(),
            expiry,
        }
    }
}

impl TokenExpiry<'_> for UserToken {
    fn expires_at_secs(&self) -> u64 {
        self.expiry
    }
}