getlocksmith 1.2.4

Official async Rust client for the Locksmith public authentication API (JWT, OAuth, magic links).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

const DEFAULT_BASE: &str = "https://getlocksmith.dev";
const ISSUER: &str = "https://getlocksmith.dev";

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Environment {
    Production,
    Sandbox,
}

#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error("locksmith: {code} ({status}): {message}")]
    Api {
        code: String,
        message: String,
        status: u16,
    },
    #[error("http error: {0}")]
    Http(#[from] reqwest::Error),
    #[error("invalid API key: must start with lsm_live_ or lsm_sbx_")]
    InvalidApiKey,
    #[error("invalid response: {0}")]
    InvalidResponse(String),
    #[error("jwt: {0}")]
    Jwt(#[from] jsonwebtoken::errors::Error),
}

pub type Result<T> = std::result::Result<T, Error>;

pub fn environment_from_api_key(api_key: &str) -> Result<Environment> {
    if api_key.starts_with("lsm_live_") {
        Ok(Environment::Production)
    } else if api_key.starts_with("lsm_sbx_") {
        Ok(Environment::Sandbox)
    } else {
        Err(Error::InvalidApiKey)
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UserBase {
    pub id: String,
    pub email: String,
    pub role: String,
    pub meta: HashMap<String, serde_json::Value>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UserSignup {
    #[serde(flatten)]
    pub base: UserBase,
    pub created_at: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UserLogin {
    #[serde(flatten)]
    pub base: UserBase,
    pub last_login_at: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UserMe {
    #[serde(flatten)]
    pub base: UserBase,
    pub email_verified: bool,
    pub created_at: String,
    pub last_login_at: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthTokens {
    pub access_token: String,
    pub refresh_token: String,
    pub expires_in: i64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SignUpResult {
    pub user: UserSignup,
    #[serde(flatten)]
    pub tokens: AuthTokens,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SignInResult {
    pub user: UserLogin,
    #[serde(flatten)]
    pub tokens: AuthTokens,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MagicLinkVerifyResult {
    pub user: UserSignup,
    #[serde(flatten)]
    pub tokens: AuthTokens,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OAuthInitiateResult {
    pub provider: String,
    pub authorization_url: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OAuthExchangeUser {
    pub id: String,
    pub email: String,
    pub role: String,
    pub meta: HashMap<String, serde_json::Value>,
    pub created_at: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OAuthTokenExchangeResult {
    pub user: OAuthExchangeUser,
    #[serde(flatten)]
    pub tokens: AuthTokens,
    pub provider: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OidcGrantResult {
    pub redirect_url: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TokenPayload {
    pub sub: String,
    pub email: String,
    pub role: String,
    pub environment: Environment,
    pub meta: HashMap<String, serde_json::Value>,
    pub aud: String,
    pub iss: String,
    pub iat: i64,
    pub exp: i64,
}

#[derive(Deserialize)]
struct Envelope<T> {
    data: T,
}

#[derive(Deserialize)]
struct ApiErrBody {
    error: Option<String>,
    message: Option<String>,
}

/// Async HTTP client for the Locksmith `/api/auth/*` API.
pub struct LocksmithClient {
    api_key: String,
    base_url: String,
    http: reqwest::Client,
    pub environment: Environment,
}

impl LocksmithClient {
    pub fn new(api_key: impl Into<String>, base_url: Option<&str>) -> Result<Self> {
        let api_key = api_key.into();
        let environment = environment_from_api_key(&api_key)?;
        let base = base_url
            .unwrap_or(DEFAULT_BASE)
            .trim_end_matches('/')
            .to_string();
        Ok(Self {
            api_key,
            base_url: base,
            http: reqwest::Client::builder()
                .use_rustls_tls()
                .build()?,
            environment,
        })
    }

    fn url(&self, path: &str) -> String {
        let p = if path.starts_with('/') {
            path.to_string()
        } else {
            format!("/{path}")
        };
        format!("{}{p}", self.base_url)
    }

    async fn request_json<T: DeserializeOwned>(
        &self,
        method: reqwest::Method,
        path: &str,
        body: Option<serde_json::Value>,
        extra_headers: Option<Vec<(&str, String)>>,
    ) -> Result<T> {
        let mut req = self
            .http
            .request(method, self.url(path))
            .header("X-API-Key", &self.api_key);
        if let Some(h) = extra_headers {
            for (k, v) in h {
                req = req.header(k, v);
            }
        }
        if let Some(b) = body {
            req = req
                .header("Content-Type", "application/json")
                .json(&b);
        }
        let res = req.send().await?;
        self.parse_envelope(res).await
    }

    async fn parse_envelope<T: DeserializeOwned>(&self, res: reqwest::Response) -> Result<T> {
        let status = res.status();
        let text = res.text().await.unwrap_or_default();
        let v: serde_json::Value = serde_json::from_str(&text).unwrap_or(serde_json::json!({}));
        if !status.is_success() {
            let err: ApiErrBody = serde_json::from_value(v.clone()).unwrap_or(ApiErrBody {
                error: None,
                message: None,
            });
            return Err(Error::Api {
                code: err.error.unwrap_or_else(|| "unknown_error".into()),
                message: err
                    .message
                    .unwrap_or_else(|| status.canonical_reason().unwrap_or("error").into()),
                status: status.as_u16(),
            });
        }
        let envelope: Envelope<T> =
            serde_json::from_value(v).map_err(|e| Error::InvalidResponse(e.to_string()))?;
        Ok(envelope.data)
    }

    pub async fn sign_up(
        &self,
        email: &str,
        password: &str,
        meta: Option<serde_json::Value>,
    ) -> Result<SignUpResult> {
        let mut body = serde_json::json!({ "email": email, "password": password });
        if let Some(m) = meta {
            body["meta"] = m;
        }
        self.request_json(reqwest::Method::POST, "/api/auth/signup", Some(body), None)
            .await
    }

    pub async fn sign_in(&self, email: &str, password: &str) -> Result<SignInResult> {
        let body = serde_json::json!({ "email": email, "password": password });
        self.request_json(reqwest::Method::POST, "/api/auth/login", Some(body), None)
            .await
    }

    pub async fn sign_out(&self, refresh_token: &str) -> Result<()> {
        let body = serde_json::json!({ "refreshToken": refresh_token });
        let _v: serde_json::Value = self
            .request_json(reqwest::Method::POST, "/api/auth/logout", Some(body), None)
            .await?;
        Ok(())
    }

    pub async fn refresh(&self, refresh_token: &str) -> Result<AuthTokens> {
        let body = serde_json::json!({ "refreshToken": refresh_token });
        self.request_json(reqwest::Method::POST, "/api/auth/refresh", Some(body), None)
            .await
    }

    pub async fn get_user(&self, access_token: &str) -> Result<UserMe> {
        #[derive(Deserialize)]
        #[serde(rename_all = "camelCase")]
        struct Me {
            user: UserMe,
        }
        let me: Me = self
            .request_json(
                reqwest::Method::GET,
                "/api/auth/me",
                None,
                Some(vec![(
                    "Authorization",
                    format!("Bearer {access_token}"),
                )]),
            )
            .await?;
        Ok(me.user)
    }

    pub fn verify_token(access_token: &str, public_key_pem: &str) -> Result<TokenPayload> {
        let key = DecodingKey::from_rsa_pem(public_key_pem.as_bytes())?;
        let mut val = Validation::new(Algorithm::RS256);
        val.set_issuer(&[ISSUER]);
        let t = decode::<TokenPayload>(access_token, &key, &val)?;
        Ok(t.claims)
    }

    pub async fn send_magic_link(
        &self,
        email: &str,
        create_if_not_exists: Option<bool>,
    ) -> Result<()> {
        let mut body = serde_json::json!({ "email": email });
        if let Some(b) = create_if_not_exists {
            body["createIfNotExists"] = serde_json::json!(b);
        }
        let _v: serde_json::Value = self
            .request_json(
                reqwest::Method::POST,
                "/api/auth/magic-link",
                Some(body),
                None,
            )
            .await?;
        Ok(())
    }

    pub async fn verify_magic_link(
        &self,
        token: &str,
        project_id: &str,
    ) -> Result<MagicLinkVerifyResult> {
        let res = self
            .http
            .get(self.url("/api/auth/magic-link/verify"))
            .query(&[("token", token), ("project", project_id)])
            .send()
            .await?;
        self.parse_envelope(res).await
    }

    pub async fn send_password_reset(&self, email: &str) -> Result<()> {
        let body = serde_json::json!({ "email": email });
        let _v: serde_json::Value = self
            .request_json(
                reqwest::Method::POST,
                "/api/auth/password/reset",
                Some(body),
                None,
            )
            .await?;
        Ok(())
    }

    pub async fn update_password(&self, token: &str, new_password: &str) -> Result<()> {
        let body = serde_json::json!({ "token": token, "newPassword": new_password });
        let _v: serde_json::Value = self
            .request_json(
                reqwest::Method::POST,
                "/api/auth/password/update",
                Some(body),
                None,
            )
            .await?;
        Ok(())
    }

    pub async fn initiate_oauth(
        &self,
        provider: &str,
        redirect_url: Option<&str>,
    ) -> Result<OAuthInitiateResult> {
        let path = format!(
            "/api/auth/oauth/{}",
            urlencoding::encode(provider)
        );
        let mut body = serde_json::Value::Object(serde_json::Map::new());
        if let Some(u) = redirect_url.filter(|s| !s.is_empty()) {
            body["redirectUrl"] = serde_json::Value::String(u.to_string());
        }
        self.request_json(
            reqwest::Method::POST,
            &path,
            Some(body),
            None,
        )
        .await
    }

    pub async fn exchange_oauth_code(&self, code: &str) -> Result<OAuthTokenExchangeResult> {
        let body = serde_json::json!({ "code": code });
        self.request_json(reqwest::Method::POST, "/api/auth/oauth/token", Some(body), None)
            .await
    }

    pub async fn complete_oidc_grant(
        &self,
        request_token: &str,
        approved: bool,
        user_id: Option<&str>,
        scopes: Option<&[String]>,
    ) -> Result<OidcGrantResult> {
        let mut body = serde_json::json!({
            "requestToken": request_token,
            "approved": approved,
        });
        if let Some(uid) = user_id {
            body["userId"] = serde_json::Value::String(uid.to_string());
        }
        if let Some(s) = scopes {
            if !s.is_empty() {
                body["scopes"] = serde_json::to_value(s).unwrap_or(serde_json::json!([]));
            }
        }
        self.request_json(
            reqwest::Method::POST,
            "/api/auth/oidc/grant",
            Some(body),
            None,
        )
        .await
    }
}