workos_sdk/user_management/operations/
create_magic_auth.rs

1use async_trait::async_trait;
2use serde::Serialize;
3use thiserror::Error;
4
5use crate::user_management::{MagicAuth, UserManagement};
6use crate::{ResponseExt, WorkOsError, WorkOsResult};
7
8/// The parameters for [`CreateMagicAuth`].
9#[derive(Debug, Serialize)]
10pub struct CreateMagicAuthParams<'a> {
11    /// The email address of the user.
12    pub email: &'a str,
13
14    /// The token of an invitation.
15    pub invitation_token: Option<&'a str>,
16}
17
18/// An error returned from [`CreateMagicAuth`].
19#[derive(Debug, Error)]
20pub enum CreateMagicAuthError {}
21
22impl From<CreateMagicAuthError> for WorkOsError<CreateMagicAuthError> {
23    fn from(err: CreateMagicAuthError) -> Self {
24        Self::Operation(err)
25    }
26}
27
28/// [WorkOS Docs: Create a Magic Auth code](https://workos.com/docs/reference/user-management/magic-auth/create)
29#[async_trait]
30pub trait CreateMagicAuth {
31    /// Creates a one-time authentication code that can be sent to the user's email address.
32    ///
33    /// [WorkOS Docs: Create a Magic Auth code](https://workos.com/docs/reference/user-management/magic-auth/create)
34    ///
35    /// # Examples
36    ///
37    /// ```
38    /// use std::collections::HashSet;
39    ///
40    /// # use workos_sdk::WorkOsResult;
41    /// # use workos_sdk::user_management::*;
42    /// use workos_sdk::{ApiKey, WorkOs};
43    ///
44    /// # async fn run() -> WorkOsResult<(), CreateMagicAuthError> {
45    /// let workos = WorkOs::new(&ApiKey::from("sk_example_123456789"));
46    ///
47    /// let magic_auth = workos
48    ///     .user_management()
49    ///     .create_magic_auth(&CreateMagicAuthParams {
50    ///          email: "marcelina@example.com",
51    ///          invitation_token: None,
52    ///     })
53    ///     .await?;
54    /// # Ok(())
55    /// # }
56    /// ```
57    async fn create_magic_auth(
58        &self,
59        params: &CreateMagicAuthParams<'_>,
60    ) -> WorkOsResult<MagicAuth, CreateMagicAuthError>;
61}
62
63#[async_trait]
64impl CreateMagicAuth for UserManagement<'_> {
65    async fn create_magic_auth(
66        &self,
67        params: &CreateMagicAuthParams<'_>,
68    ) -> WorkOsResult<MagicAuth, CreateMagicAuthError> {
69        let url = self.workos.base_url().join("/user_management/magic_auth")?;
70        let user = self
71            .workos
72            .client()
73            .post(url)
74            .bearer_auth(self.workos.key())
75            .json(&params)
76            .send()
77            .await?
78            .handle_unauthorized_or_generic_error()?
79            .json::<MagicAuth>()
80            .await?;
81
82        Ok(user)
83    }
84}
85
86#[cfg(test)]
87mod test {
88    use serde_json::json;
89    use tokio;
90
91    use crate::user_management::MagicAuthId;
92    use crate::{ApiKey, WorkOs};
93
94    use super::*;
95
96    #[tokio::test]
97    async fn it_calls_the_create_magic_auth_endpoint() {
98        let mut server = mockito::Server::new_async().await;
99
100        let workos = WorkOs::builder(&ApiKey::from("sk_example_123456789"))
101            .base_url(&server.url())
102            .unwrap()
103            .build();
104
105        server
106            .mock("POST", "/user_management/magic_auth")
107            .match_header("Authorization", "Bearer sk_example_123456789")
108            .with_status(201)
109            .with_body(
110                json!({
111                    "id": "magic_auth_01E4ZCR3C56J083X43JQXF3JK5",
112                    "user_id": "user_01HWWYEH2NPT48X82ZT23K5AX4",
113                    "email": "marcelina.davis@example.com",
114                    "expires_at": "2021-07-01T19:07:33.155Z",
115                    "code": "123456",
116                    "created_at": "2021-06-25T19:07:33.155Z",
117                    "updated_at": "2021-06-25T19:07:33.155Z"
118                })
119                .to_string(),
120            )
121            .create_async()
122            .await;
123
124        let magic_auth = workos
125            .user_management()
126            .create_magic_auth(&CreateMagicAuthParams {
127                email: "marcelina@example.com",
128                invitation_token: None,
129            })
130            .await
131            .unwrap();
132
133        assert_eq!(
134            magic_auth.id,
135            MagicAuthId::from("magic_auth_01E4ZCR3C56J083X43JQXF3JK5")
136        )
137    }
138}