workos 1.0.0

Official Rust SDK for the WorkOS API
Documentation
// Code generated by oagen. DO NOT EDIT.

use crate::client::Client;
#[allow(unused_imports)]
use crate::enums::*;
use crate::error::Error;
#[allow(unused_imports)]
use crate::models::*;
use serde::Serialize;

pub struct SSOApi<'a> {
    pub(crate) client: &'a Client,
}

#[derive(Debug, Clone, Default, Serialize)]
pub struct ListConnectionsParams {
    /// An object ID that defines your place in the list. When the ID is not present, you are at the end of the list.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub before: Option<String>,
    /// An object ID that defines your place in the list. When the ID is not present, you are at the end of the list.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub after: Option<String>,
    /// Upper limit on the number of objects to return, between `1` and `100`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<i64>,
    /// Order the results by the creation time.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub order: Option<PaginationOrder>,
    /// Filter Connections by their type.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub connection_type: Option<ConnectionsConnectionType>,
    /// Filter Connections by their associated domain.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub domain: Option<String>,
    /// Filter Connections by their associated organization.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub organization_id: Option<String>,
    /// Searchable text to match against Connection names.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub search: Option<String>,
}

#[derive(Debug, Clone, Serialize)]
pub struct GetAuthorizationUrlParams {
    /// Additional scopes to request from the identity provider. Applicable when using OAuth or OpenID Connect connections.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub provider_scopes: Option<Vec<String>>,
    /// Key/value pairs of query parameters to pass to the OAuth provider. Only applicable when using OAuth connections.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub provider_query_params: Option<std::collections::HashMap<String, String>>,
    /// Deprecated. Use `connection` or `organization` instead. Used to initiate SSO for a connection by domain. The domain must be associated with a connection in your WorkOS environment.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[deprecated]
    pub domain: Option<String>,
    /// Used to initiate OAuth authentication with various providers.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub provider: Option<SSOProvider>,
    /// Where to redirect the user after they complete the authentication process. You must use one of the redirect URIs configured via the [Redirects](https://dashboard.workos.com/redirects) page on the dashboard.
    ///
    /// Required.
    pub redirect_uri: String,
    /// An optional parameter that can be used to encode arbitrary information to help restore application state between redirects. If included, the redirect URI received from WorkOS will contain the exact `state` that was passed.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub state: Option<String>,
    /// Used to initiate SSO for a connection. The value should be a WorkOS connection ID.
    /// You can persist the WorkOS connection ID with application user or team identifiers. WorkOS will use the connection indicated by the connection parameter to direct the user to the corresponding IdP for authentication.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub connection: Option<String>,
    /// Used to initiate SSO for an organization. The value should be a WorkOS organization ID.
    /// You can persist the WorkOS organization ID with application user or team identifiers. WorkOS will use the organization ID to determine the appropriate connection and the IdP to direct the user to for authentication.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub organization: Option<String>,
    /// Can be used to pre-fill the domain field when initiating authentication with Microsoft OAuth or with a Google SAML connection type.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub domain_hint: Option<String>,
    /// Can be used to pre-fill the username/email address field of the IdP sign-in page for the user, if you know their username ahead of time. Currently supported for OAuth, OpenID Connect, Okta, and Entra ID connections.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub login_hint: Option<String>,
    /// A random string generated by the client that is used to mitigate replay attacks.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub nonce: Option<String>,
}

impl GetAuthorizationUrlParams {
    /// Construct a new `GetAuthorizationUrlParams` with the required fields set.
    #[allow(deprecated)]
    pub fn new(redirect_uri: impl Into<String>) -> Self {
        Self {
            provider_scopes: Default::default(),
            provider_query_params: Default::default(),
            domain: Default::default(),
            provider: Default::default(),
            redirect_uri: redirect_uri.into(),
            state: Default::default(),
            connection: Default::default(),
            organization: Default::default(),
            domain_hint: Default::default(),
            login_hint: Default::default(),
            nonce: Default::default(),
        }
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct GetLogoutUrlParams {
    /// The logout token returned from the [Logout Authorize](https://workos.com/docs/reference/sso/logout/authorize) endpoint.
    ///
    /// Required.
    pub token: crate::SecretString,
}

impl GetLogoutUrlParams {
    /// Construct a new `GetLogoutUrlParams` with the required fields set.
    #[allow(deprecated)]
    pub fn new(token: impl Into<crate::SecretString>) -> Self {
        Self {
            token: token.into(),
        }
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct AuthorizeLogoutParams {
    /// Request body sent with this call.
    ///
    /// Required.
    #[serde(skip)]
    pub body: SSOLogoutAuthorizeRequest,
}

impl AuthorizeLogoutParams {
    /// Construct a new `AuthorizeLogoutParams` with the required fields set.
    #[allow(deprecated)]
    pub fn new(body: SSOLogoutAuthorizeRequest) -> Self {
        Self { body }
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct GetProfileAndTokenParams {
    /// The authorization code received from the authorization callback.
    ///
    /// Required.
    pub code: String,
    /// Request body sent with this call.
    ///
    /// Required.
    #[serde(skip)]
    pub body: TokenQuery,
}

impl GetProfileAndTokenParams {
    /// Construct a new `GetProfileAndTokenParams` with the required fields set.
    #[allow(deprecated)]
    pub fn new(code: impl Into<String>, body: TokenQuery) -> Self {
        Self {
            code: code.into(),
            body,
        }
    }
}

impl<'a> SSOApi<'a> {
    /// List Connections
    ///
    /// Get a list of all of your existing connections matching the criteria specified.
    pub async fn list_connections(
        &self,
        params: ListConnectionsParams,
    ) -> Result<ConnectionList, Error> {
        self.list_connections_with_options(params, None).await
    }

    /// Variant of [`Self::list_connections`] that accepts per-request [`crate::RequestOptions`].
    pub async fn list_connections_with_options(
        &self,
        params: ListConnectionsParams,
        options: Option<&crate::RequestOptions>,
    ) -> Result<ConnectionList, Error> {
        let path = "/connections".to_string();
        let method = http::Method::GET;
        self.client
            .request_with_query_opts(method, &path, &params, options)
            .await
    }

    /// Returns an async [`futures_util::Stream`] that yields every `Connection`
    /// across all pages, advancing the `after` cursor under the hood.
    ///
    /// ```ignore
    /// use futures_util::TryStreamExt;
    /// let all: Vec<Connection> = self
    ///     .list_connections_auto_paging(params)
    ///     .try_collect()
    ///     .await?;
    /// ```
    pub fn list_connections_auto_paging(
        &self,
        params: ListConnectionsParams,
    ) -> impl futures_util::Stream<Item = Result<Connection, Error>> + '_ {
        crate::pagination::auto_paginate_pages(move |after| {
            let mut params = params.clone();
            params.after = after;
            async move {
                let page = self.list_connections(params).await?;
                Ok((page.data, page.list_metadata.after))
            }
        })
    }

    /// Get a Connection
    ///
    /// Get the details of an existing connection.
    pub async fn get_connection(&self, id: &str) -> Result<Connection, Error> {
        self.get_connection_with_options(id, None).await
    }

    /// Variant of [`Self::get_connection`] that accepts per-request [`crate::RequestOptions`].
    pub async fn get_connection_with_options(
        &self,
        id: &str,
        options: Option<&crate::RequestOptions>,
    ) -> Result<Connection, Error> {
        let id = crate::client::path_segment(id);
        let path = format!("/connections/{id}");
        let method = http::Method::GET;
        self.client
            .request_with_query_opts(method, &path, &(), options)
            .await
    }

    /// Delete a Connection
    ///
    /// Permanently deletes an existing connection. It cannot be undone.
    pub async fn delete_connection(&self, id: &str) -> Result<(), Error> {
        self.delete_connection_with_options(id, None).await
    }

    /// Variant of [`Self::delete_connection`] that accepts per-request [`crate::RequestOptions`].
    pub async fn delete_connection_with_options(
        &self,
        id: &str,
        options: Option<&crate::RequestOptions>,
    ) -> Result<(), Error> {
        let id = crate::client::path_segment(id);
        let path = format!("/connections/{id}");
        let method = http::Method::DELETE;
        self.client
            .request_with_query_opts_empty(method, &path, &(), options)
            .await
    }

    /// Initiate SSO
    ///
    /// Initiates the single sign-on flow.
    pub async fn get_authorization_url(
        &self,
        params: GetAuthorizationUrlParams,
    ) -> Result<SSOAuthorizeUrlResponse, Error> {
        self.get_authorization_url_with_options(params, None).await
    }

    /// Variant of [`Self::get_authorization_url`] that accepts per-request [`crate::RequestOptions`].
    pub async fn get_authorization_url_with_options(
        &self,
        params: GetAuthorizationUrlParams,
        options: Option<&crate::RequestOptions>,
    ) -> Result<SSOAuthorizeUrlResponse, Error> {
        let path = "/sso/authorize".to_string();
        let method = http::Method::GET;
        self.client
            .request_with_query_opts(method, &path, &params, options)
            .await
    }

    /// Logout Redirect
    ///
    /// Logout allows to sign out a user from your application by triggering the identity provider sign out flow. This `GET` endpoint should be a redirection, since the identity provider user will be identified in the browser session.
    ///
    /// Before redirecting to this endpoint, you need to generate a short-lived logout token using the [Logout Authorize](https://workos.com/docs/reference/sso/logout/authorize) endpoint.
    pub async fn get_logout_url(&self, params: GetLogoutUrlParams) -> Result<(), Error> {
        self.get_logout_url_with_options(params, None).await
    }

    /// Variant of [`Self::get_logout_url`] that accepts per-request [`crate::RequestOptions`].
    pub async fn get_logout_url_with_options(
        &self,
        params: GetLogoutUrlParams,
        options: Option<&crate::RequestOptions>,
    ) -> Result<(), Error> {
        let path = "/sso/logout".to_string();
        let method = http::Method::GET;
        self.client
            .request_with_query_opts_empty(method, &path, &params, options)
            .await
    }

    /// Logout Authorize
    ///
    /// You should call this endpoint from your server to generate a logout token which is required for the [Logout Redirect](https://workos.com/docs/reference/sso/logout) endpoint.
    pub async fn authorize_logout(
        &self,
        params: AuthorizeLogoutParams,
    ) -> Result<SSOLogoutAuthorizeResponse, Error> {
        self.authorize_logout_with_options(params, None).await
    }

    /// Variant of [`Self::authorize_logout`] that accepts per-request [`crate::RequestOptions`].
    pub async fn authorize_logout_with_options(
        &self,
        params: AuthorizeLogoutParams,
        options: Option<&crate::RequestOptions>,
    ) -> Result<SSOLogoutAuthorizeResponse, Error> {
        let path = "/sso/logout/authorize".to_string();
        let method = http::Method::POST;
        self.client
            .request_with_body_opts(method, &path, &params, Some(&params.body), options)
            .await
    }

    /// Get a User Profile
    ///
    /// Exchange an access token for a user's [Profile](https://workos.com/docs/reference/sso/profile). Because this profile is returned in the [Get a Profile and Token endpoint](https://workos.com/docs/reference/sso/profile/get-profile-and-token) your application usually does not need to call this endpoint. It is available for any authentication flows that require an additional endpoint to retrieve a user's profile.
    pub async fn get_profile(&self) -> Result<Profile, Error> {
        self.get_profile_with_options(None).await
    }

    /// Variant of [`Self::get_profile`] that accepts per-request [`crate::RequestOptions`].
    pub async fn get_profile_with_options(
        &self,
        options: Option<&crate::RequestOptions>,
    ) -> Result<Profile, Error> {
        let path = "/sso/profile".to_string();
        let method = http::Method::GET;
        self.client
            .request_with_query_opts(method, &path, &(), options)
            .await
    }

    /// Get a Profile and Token
    ///
    /// Get an access token along with the user [Profile](https://workos.com/docs/reference/sso/profile) using the code passed to your [Redirect URI](https://workos.com/docs/reference/sso/get-authorization-url/redirect-uri).
    pub async fn get_profile_and_token(
        &self,
        params: GetProfileAndTokenParams,
    ) -> Result<SSOTokenResponse, Error> {
        self.get_profile_and_token_with_options(params, None).await
    }

    /// Variant of [`Self::get_profile_and_token`] that accepts per-request [`crate::RequestOptions`].
    pub async fn get_profile_and_token_with_options(
        &self,
        params: GetProfileAndTokenParams,
        options: Option<&crate::RequestOptions>,
    ) -> Result<SSOTokenResponse, Error> {
        let path = "/sso/token".to_string();
        let method = http::Method::POST;
        self.client
            .request_with_body_opts(method, &path, &params, Some(&params.body), options)
            .await
    }
}