clerk_fapi_rs/apis/
active_sessions_api.rs

1/*
2 * Clerk Frontend API
3 *
4 * The Clerk REST Frontend API, meant to be accessed from a browser or native environment.  This is a Form Based API and all the data must be sent and formatted according to the `application/x-www-form-urlencoded` content type.  ### Versions  When the API changes in a way that isn't compatible with older versions, a new version is released. Each version is identified by its release date, e.g. `2021-02-05`. For more information, please see [Clerk API Versions](https://clerk.com/docs/backend-requests/versioning/overview).  ### Using the Try It Console  The `Try It` feature of the docs only works for **Development Instances** when using the `DevBrowser` security scheme. To use it, first generate a dev instance token from the `/v1/dev_browser` endpoint.  Please see https://clerk.com/docs for more information.
5 *
6 * The version of the OpenAPI document: v1
7 * Contact: support@clerk.com
8 * Generated by: https://openapi-generator.tech
9 */
10
11use super::{configuration, ContentType, Error};
12use crate::{apis::ResponseContent, models};
13use reqwest;
14use serde::{de::Error as _, Deserialize, Serialize};
15
16/// struct for typed errors of method [`get_sessions`]
17#[derive(Debug, Clone, Serialize, Deserialize)]
18#[serde(untagged)]
19pub enum GetSessionsError {
20    Status401(models::ClerkErrors),
21    UnknownValue(serde_json::Value),
22}
23
24/// struct for typed errors of method [`get_users_sessions`]
25#[derive(Debug, Clone, Serialize, Deserialize)]
26#[serde(untagged)]
27pub enum GetUsersSessionsError {
28    Status401(models::ClerkErrors),
29    Status403(models::ClerkErrors),
30    Status404(models::ClerkErrors),
31    UnknownValue(serde_json::Value),
32}
33
34/// struct for typed errors of method [`revoke_session`]
35#[derive(Debug, Clone, Serialize, Deserialize)]
36#[serde(untagged)]
37pub enum RevokeSessionError {
38    Status400(models::ClerkErrors),
39    Status401(models::ClerkErrors),
40    Status403(models::ClerkErrors),
41    Status404(models::ClerkErrors),
42    UnknownValue(serde_json::Value),
43}
44
45/// Returns all active session for user, including activity information.
46pub async fn get_sessions(
47    configuration: &configuration::Configuration,
48    _clerk_session_id: Option<&str>,
49) -> Result<Vec<models::ClientActiveSession>, Error<GetSessionsError>> {
50    // add a prefix to parameters to efficiently prevent name collisions
51    let p_query_clerk_session_id = _clerk_session_id;
52
53    let uri_str = format!("{}/v1/me/sessions/active", configuration.base_path);
54    let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);
55
56    if let Some(ref param_value) = p_query_clerk_session_id {
57        req_builder = req_builder.query(&[("_clerk_session_id", &param_value.to_string())]);
58    }
59    if let Some(ref apikey) = configuration.api_key {
60        let key = apikey.key.clone();
61        let value = match apikey.prefix {
62            Some(ref prefix) => format!("{prefix} {key}"),
63            None => key,
64        };
65        req_builder = req_builder.query(&[("__dev_session", value)]);
66    }
67    if let Some(ref user_agent) = configuration.user_agent {
68        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
69    }
70    if let Some(ref apikey) = configuration.api_key {
71        let key = apikey.key.clone();
72        let value = match apikey.prefix {
73            Some(ref prefix) => format!("{prefix} {key}"),
74            None => key,
75        };
76        req_builder = req_builder.header("__session", value);
77    };
78
79    let req = req_builder.build()?;
80    let resp = configuration.client.execute(req).await?;
81
82    let status = resp.status();
83    let content_type = resp
84        .headers()
85        .get("content-type")
86        .and_then(|v| v.to_str().ok())
87        .unwrap_or("application/octet-stream");
88    let content_type = super::ContentType::from(content_type);
89
90    if !status.is_client_error() && !status.is_server_error() {
91        let content = resp.text().await?;
92        match content_type {
93            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
94            ContentType::Text => Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec&lt;models::ClientActiveSession&gt;`"))),
95            ContentType::Unsupported(unknown_type) => Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec&lt;models::ClientActiveSession&gt;`")))),
96        }
97    } else {
98        let content = resp.text().await?;
99        let entity: Option<GetSessionsError> = serde_json::from_str(&content).ok();
100        Err(Error::ResponseError(ResponseContent {
101            status,
102            content,
103            entity,
104        }))
105    }
106}
107
108/// Get all the sessions of the current user.
109pub async fn get_users_sessions(
110    configuration: &configuration::Configuration,
111    _clerk_session_id: Option<&str>,
112) -> Result<Vec<models::ClientSession>, Error<GetUsersSessionsError>> {
113    // add a prefix to parameters to efficiently prevent name collisions
114    let p_query_clerk_session_id = _clerk_session_id;
115
116    let uri_str = format!("{}/v1/me/sessions", configuration.base_path);
117    let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);
118
119    if let Some(ref param_value) = p_query_clerk_session_id {
120        req_builder = req_builder.query(&[("_clerk_session_id", &param_value.to_string())]);
121    }
122    if let Some(ref apikey) = configuration.api_key {
123        let key = apikey.key.clone();
124        let value = match apikey.prefix {
125            Some(ref prefix) => format!("{prefix} {key}"),
126            None => key,
127        };
128        req_builder = req_builder.query(&[("__dev_session", value)]);
129    }
130    if let Some(ref user_agent) = configuration.user_agent {
131        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
132    }
133    if let Some(ref apikey) = configuration.api_key {
134        let key = apikey.key.clone();
135        let value = match apikey.prefix {
136            Some(ref prefix) => format!("{prefix} {key}"),
137            None => key,
138        };
139        req_builder = req_builder.header("__session", value);
140    };
141
142    let req = req_builder.build()?;
143    let resp = configuration.client.execute(req).await?;
144
145    let status = resp.status();
146    let content_type = resp
147        .headers()
148        .get("content-type")
149        .and_then(|v| v.to_str().ok())
150        .unwrap_or("application/octet-stream");
151    let content_type = super::ContentType::from(content_type);
152
153    if !status.is_client_error() && !status.is_server_error() {
154        let content = resp.text().await?;
155        match content_type {
156            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
157            ContentType::Text => Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec&lt;models::ClientSession&gt;`"))),
158            ContentType::Unsupported(unknown_type) => Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec&lt;models::ClientSession&gt;`")))),
159        }
160    } else {
161        let content = resp.text().await?;
162        let entity: Option<GetUsersSessionsError> = serde_json::from_str(&content).ok();
163        Err(Error::ResponseError(ResponseContent {
164            status,
165            content,
166            entity,
167        }))
168    }
169}
170
171/// Revokes given session.
172pub async fn revoke_session(
173    configuration: &configuration::Configuration,
174    session_id: &str,
175    _clerk_session_id: Option<&str>,
176) -> Result<models::ClientClientWrappedSession, Error<RevokeSessionError>> {
177    // add a prefix to parameters to efficiently prevent name collisions
178    let p_path_session_id = session_id;
179    let p_query_clerk_session_id = _clerk_session_id;
180
181    let uri_str = format!(
182        "{}/v1/me/sessions/{session_id}/revoke",
183        configuration.base_path,
184        session_id = crate::apis::urlencode(p_path_session_id)
185    );
186    let mut req_builder = configuration
187        .client
188        .request(reqwest::Method::POST, &uri_str);
189
190    if let Some(ref param_value) = p_query_clerk_session_id {
191        req_builder = req_builder.query(&[("_clerk_session_id", &param_value.to_string())]);
192    }
193    if let Some(ref apikey) = configuration.api_key {
194        let key = apikey.key.clone();
195        let value = match apikey.prefix {
196            Some(ref prefix) => format!("{prefix} {key}"),
197            None => key,
198        };
199        req_builder = req_builder.query(&[("__dev_session", value)]);
200    }
201    if let Some(ref user_agent) = configuration.user_agent {
202        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
203    }
204    if let Some(ref apikey) = configuration.api_key {
205        let key = apikey.key.clone();
206        let value = match apikey.prefix {
207            Some(ref prefix) => format!("{prefix} {key}"),
208            None => key,
209        };
210        req_builder = req_builder.header("__session", value);
211    };
212
213    let req = req_builder.build()?;
214    let resp = configuration.client.execute(req).await?;
215
216    let status = resp.status();
217    let content_type = resp
218        .headers()
219        .get("content-type")
220        .and_then(|v| v.to_str().ok())
221        .unwrap_or("application/octet-stream");
222    let content_type = super::ContentType::from(content_type);
223
224    if !status.is_client_error() && !status.is_server_error() {
225        let content = resp.text().await?;
226        match content_type {
227            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
228            ContentType::Text => Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ClientClientWrappedSession`"))),
229            ContentType::Unsupported(unknown_type) => Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ClientClientWrappedSession`")))),
230        }
231    } else {
232        let content = resp.text().await?;
233        let entity: Option<RevokeSessionError> = serde_json::from_str(&content).ok();
234        Err(Error::ResponseError(ResponseContent {
235            status,
236            content,
237            entity,
238        }))
239    }
240}