fauna-api 1.0.807

The Fauna SDK for Rust: accounts, Drive, groups, calendar, chats, payments, Parrot and live rooms.
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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};

use crate::billing::PageQuery;
use crate::error::{Error, Result};
use crate::groups::Group;
use crate::http::{client, encode, ok};
use crate::integrations::Platform;
use crate::tickets::parse_date;

// Authorization Types
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct Credentials {
    pub token: Token,

    pub email_verified: bool,
    pub phone_verified: bool,
    pub permissions: Vec<String>,
    pub integrations: Vec<Platform>,

    pub email: String,
    pub phone: String,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub display_name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub icon: Option<String>,

    pub api_keys: Vec<ApiKey>,

    pub balance: f64,
}

/// `'EMAIL' | 'PHONE'` in the TypeScript SDK.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum VerificationChannel {
    Email,
    Phone,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct ApiKey {
    pub id: String,

    pub balance: f64,
    pub services: Vec<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
}

pub type Token = String;

#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct Profile {
    pub email: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub display_name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub icon: Option<String>,
}

impl Profile {
    pub fn from_json(json: &Value) -> Option<Profile> {
        let email = json["email"].as_str().filter(|email| !email.is_empty())?;
        Some(Profile {
            email: email.to_string(),
            display_name: json["displayName"].as_str().map(str::to_string),
            icon: json["icon"].as_str().map(str::to_string),
        })
    }
}

/// One place you're signed in. `id` names the session; it is not its token.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Session {
    pub id: String,
    /// The session this call came from.
    pub current: bool,
    /// The browser or client that signed in, as its User-Agent named it.
    pub agent: String,
    pub created: DateTime<Utc>,
    pub expires: DateTime<Utc>,
}

impl Session {
    pub fn from_json(json: &Value) -> Session {
        Session {
            id: match &json["id"] {
                Value::String(id) => id.clone(),
                id => id.to_string(),
            },
            current: json["current"].as_bool() == Some(true),
            agent: json["agent"].as_str().unwrap_or_default().to_string(),
            created: parse_date(&json["created"]).unwrap_or_default(),
            expires: parse_date(&json["expires"]).unwrap_or_default(),
        }
    }
}

/// `Credentials | ApiKey` in the TypeScript SDK.
#[derive(Debug, Clone)]
pub enum CredentialsOrApiKey {
    Credentials(Credentials),
    ApiKey(ApiKey),
}

/// `ApiKey | Group` in the TypeScript SDK.
#[derive(Debug, Clone)]
pub enum ApiKeyOrGroup {
    ApiKey(ApiKey),
    Group(Group),
}

/// `Partial<Pick<Credentials, 'displayName' | 'icon' | 'email' | 'phone'>>` in the
/// TypeScript SDK. Email and phone are only accepted while that one isn't verified
/// yet; a change sends a new link and code.
#[derive(Debug, Clone, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PartialCredentials {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub display_name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub icon: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub email: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub phone: Option<String>,
}

/// `Partial<ApiKey>` in the TypeScript SDK.
#[derive(Debug, Clone, Default, PartialEq, Serialize)]
pub struct PartialApiKey {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub balance: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub services: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
}

/// `Partial<Profile>` in the TypeScript SDK.
#[derive(Debug, Clone, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PartialProfile {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub email: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub display_name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub icon: Option<String>,
}

// Authorization
pub async fn authorize(email: &str, password: &str) -> Result<Token> {
    let response = client()
        .post(format!("{}/authentification/authorize", crate::get_url()))
        .json(&json!({ "email": email, "password": password }))
        .send()
        .await?;
    Ok(ok(response).await?.text().await?)
}

pub async fn authorize_token(token: &str) -> Result<Credentials> {
    let response = client()
        .post(format!("{}/authentification/authorize", crate::get_url()))
        .header("Authorization", format!("Token {token}"))
        .send()
        .await?;
    let mut credentials: Credentials = ok(response).await?.json().await?;
    credentials.token = token.to_string();
    Ok(credentials)
}

pub async fn authorize_api_key(api_key: &str) -> Result<ApiKey> {
    let response = client()
        .post(format!("{}/authentification/authorize", crate::get_url()))
        .header("Authorization", format!("ApiKey {api_key}"))
        .send()
        .await?;
    Ok(ok(response).await?.json().await?)
}

// Credentials Management
pub async fn create(
    email: &str,
    password: &str,
    phone: &str,
    display_name: Option<&str>,
) -> Result<bool> {
    let response = client()
        .post(format!("{}/authentification/create", crate::get_url()))
        .json(&json!({
            "email": email,
            "password": password,
            "phone": phone,
            "displayName": display_name,
        }))
        .send()
        .await?;
    ok(response).await?;
    Ok(true)
}

pub async fn edit(credentials: &Credentials, update: &PartialCredentials) -> Result<bool> {
    let response = client()
        .patch(format!("{}/authentification", crate::get_url()))
        .header("Authorization", format!("Token {}", credentials.token))
        .json(update)
        .send()
        .await?;
    ok(response).await?;
    Ok(true)
}

pub async fn verify(channel: VerificationChannel, target: &str, code: &str) -> Result<bool> {
    let response = client()
        .post(format!("{}/authentification/verify", crate::get_url()))
        .json(&json!({ "channel": channel, "target": target, "code": code }))
        .send()
        .await?;
    ok(response).await?;
    Ok(true)
}

pub async fn send_verification(
    credentials: &Credentials,
    channel: VerificationChannel,
) -> Result<bool> {
    let response = client()
        .post(format!(
            "{}/authentification/send-verification",
            crate::get_url()
        ))
        .header("Authorization", format!("Token {}", credentials.token))
        .json(&json!({ "channel": channel }))
        .send()
        .await?;
    ok(response).await?;
    Ok(true)
}

// Passwords and sessions
/// Emails a link and code for choosing a new password, when an account has that
/// email. Answers the same either way.
pub async fn forgot_password(email: &str) -> Result<bool> {
    let response = client()
        .post(format!(
            "{}/authentification/password/forgot",
            crate::get_url()
        ))
        .json(&json!({ "email": email }))
        .send()
        .await?;
    ok(response).await?;
    Ok(true)
}

/// A new password, with the code from a reset email. The email counts as
/// verified, and every session ends.
pub async fn reset_password(email: &str, code: &str, password: &str) -> Result<bool> {
    let response = client()
        .post(format!(
            "{}/authentification/password/reset",
            crate::get_url()
        ))
        .json(&json!({ "email": email, "code": code, "password": password }))
        .send()
        .await?;
    ok(response).await?;
    Ok(true)
}

/// A new password, given the current one. Every other session ends; this one stays.
pub async fn change_password(
    credentials: &Credentials,
    current: &str,
    password: &str,
) -> Result<bool> {
    let response = client()
        .post(format!("{}/authentification/password", crate::get_url()))
        .header("Authorization", format!("Token {}", credentials.token))
        .json(&json!({ "current": current, "password": password }))
        .send()
        .await?;
    ok(response).await?;
    Ok(true)
}

/// Your live sessions, newest first.
pub async fn sessions(credentials: &Credentials, query: PageQuery) -> Result<Vec<Session>> {
    let response = client()
        .get(format!(
            "{}/authentification/sessions?cursor={}&max={}",
            crate::get_url(),
            query.cursor,
            query.max
        ))
        .header("Authorization", format!("Token {}", credentials.token))
        .send()
        .await?;
    let rows: Vec<Value> = ok(response).await?.json().await?;
    Ok(rows.iter().map(Session::from_json).collect())
}

/// Ends one of your sessions.
pub async fn revoke_session(credentials: &Credentials, session: &Session) -> Result<bool> {
    let response = client()
        .delete(format!(
            "{}/authentification/sessions/{}",
            crate::get_url(),
            encode(&session.id)
        ))
        .header("Authorization", format!("Token {}", credentials.token))
        .send()
        .await?;
    ok(response).await?;
    Ok(true)
}

/// Ends the session `credentials` signed in with.
pub async fn sign_out(credentials: &Credentials) -> Result<bool> {
    let response = client()
        .post(format!("{}/authentification/sign-out", crate::get_url()))
        .header("Authorization", format!("Token {}", credentials.token))
        .send()
        .await?;
    ok(response).await?;
    Ok(true)
}

/// Ends every one of your sessions, this one too.
pub async fn sign_out_everywhere(credentials: &Credentials) -> Result<bool> {
    let response = client()
        .delete(format!("{}/authentification/sessions", crate::get_url()))
        .header("Authorization", format!("Token {}", credentials.token))
        .send()
        .await?;
    ok(response).await?;
    Ok(true)
}

/// A single use code, good for a minute, that gives another page or app a new
/// session of the same person, so no token rides in a URL.
pub async fn handoff(credentials: &Credentials) -> Result<String> {
    let response = client()
        .post(format!("{}/authentification/handoff", crate::get_url()))
        .header("Authorization", format!("Token {}", credentials.token))
        .send()
        .await?;
    let json: Value = ok(response).await?.json().await?;
    Ok(json["code"].as_str().unwrap_or_default().to_string())
}

/// Uses up a handoff code for the new session token it carries.
pub async fn redeem_handoff(code: &str) -> Result<Token> {
    let response = client()
        .post(format!(
            "{}/authentification/handoff/redeem",
            crate::get_url()
        ))
        .json(&json!({ "code": code }))
        .send()
        .await?;
    Ok(ok(response).await?.text().await?)
}

pub async fn allocate_balance(
    credentials: &Credentials,
    target: &ApiKeyOrGroup,
    delta: f64,
) -> Result<bool> {
    let delta_micros = (delta * 1_000_000.0).round();
    if !delta_micros.is_finite() || delta_micros.abs() > 9_007_199_254_740_991.0 {
        return Err(Error::Message("Invalid balance delta.".to_string()));
    }

    let request = client()
        .post(format!(
            "{}/authentification/allocate-balance",
            crate::get_url()
        ))
        .header("Authorization", format!("Token {}", credentials.token));
    let request = match target {
        ApiKeyOrGroup::ApiKey(key) => request.header("Api-Key", &key.id),
        ApiKeyOrGroup::Group(group) => request.header("Group", &group.id),
    };
    let response = request
        .json(&json!({ "deltaMicros": delta_micros as i64 }))
        .send()
        .await?;
    ok(response).await?;
    Ok(true)
}

pub async fn generate_api_key(credentials: &Credentials) -> Result<ApiKey> {
    let response = client()
        .post(format!("{}/authentification/api-keys", crate::get_url()))
        .header("Content-Type", "application/json")
        .header("Authorization", format!("Token {}", credentials.token))
        .send()
        .await?;
    Ok(ok(response).await?.json().await?)
}

pub async fn remove_api_key(credentials: &Credentials, api_key: &ApiKey) -> Result<bool> {
    let response = client()
        .delete(format!(
            "{}/authentification/api-keys/{}",
            crate::get_url(),
            encode(&api_key.id)
        ))
        .header("Authorization", format!("Token {}", credentials.token))
        .send()
        .await?;
    ok(response).await?;
    Ok(true)
}

pub async fn profile(credentials: &Credentials, email: &str) -> Result<Profile> {
    let response = client()
        .get(format!(
            "{}/authentification/profile/{}",
            crate::get_url(),
            encode(email)
        ))
        .header("Authorization", format!("Token {}", credentials.token))
        .send()
        .await?;
    Ok(ok(response).await?.json().await?)
}

/// Profiles matching a partial email or name, best first, at most 20. An admin's
/// answer carries more; this keeps the profiles.
pub async fn query(credentials: &Credentials, profile: &PartialProfile) -> Result<Vec<Profile>> {
    let response = client()
        .post(format!("{}/credentials/query", crate::get_url()))
        .header("Authorization", format!("Token {}", credentials.token))
        .json(&json!({ "email": profile.email, "displayName": profile.display_name }))
        .send()
        .await?;
    let json: Value = ok(response).await?.json().await?;
    Ok(serde_json::from_value(
        json.get("accounts").cloned().unwrap_or(json),
    )?)
}

pub async fn edit_api_key(
    credentials: &Credentials,
    api_key: &ApiKey,
    update: &PartialApiKey,
) -> Result<bool> {
    let response = client()
        .patch(format!(
            "{}/authentification/api-keys/{}",
            crate::get_url(),
            encode(&api_key.id)
        ))
        .header("Authorization", format!("Token {}", credentials.token))
        .json(&json!({ "name": update.name }))
        .send()
        .await?;
    ok(response).await?;
    Ok(true)
}