Skip to main content

fauna_api/
authentification.rs

1use chrono::{DateTime, Utc};
2use serde::{Deserialize, Serialize};
3use serde_json::{Value, json};
4
5use crate::billing::PageQuery;
6use crate::error::{Error, Result};
7use crate::groups::Group;
8use crate::http::{client, encode, ok};
9use crate::integrations::Platform;
10use crate::tickets::parse_date;
11
12// Authorization Types
13#[derive(Debug, Clone, Default, Serialize, Deserialize)]
14#[serde(default, rename_all = "camelCase")]
15pub struct Credentials {
16    pub token: Token,
17
18    pub email_verified: bool,
19    pub phone_verified: bool,
20    pub permissions: Vec<String>,
21    pub integrations: Vec<Platform>,
22
23    pub email: String,
24    pub phone: String,
25
26    #[serde(skip_serializing_if = "Option::is_none")]
27    pub display_name: Option<String>,
28    #[serde(skip_serializing_if = "Option::is_none")]
29    pub icon: Option<String>,
30
31    pub api_keys: Vec<ApiKey>,
32
33    pub balance: f64,
34}
35
36/// `'EMAIL' | 'PHONE'` in the TypeScript SDK.
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
38#[serde(rename_all = "UPPERCASE")]
39pub enum VerificationChannel {
40    Email,
41    Phone,
42}
43
44#[derive(Debug, Clone, Default, Serialize, Deserialize)]
45#[serde(default, rename_all = "camelCase")]
46pub struct ApiKey {
47    pub id: String,
48
49    pub balance: f64,
50    pub services: Vec<String>,
51
52    #[serde(skip_serializing_if = "Option::is_none")]
53    pub name: Option<String>,
54}
55
56pub type Token = String;
57
58#[derive(Debug, Clone, Default, Serialize, Deserialize)]
59#[serde(default, rename_all = "camelCase")]
60pub struct Profile {
61    pub email: String,
62    #[serde(skip_serializing_if = "Option::is_none")]
63    pub display_name: Option<String>,
64    #[serde(skip_serializing_if = "Option::is_none")]
65    pub icon: Option<String>,
66}
67
68impl Profile {
69    pub fn from_json(json: &Value) -> Option<Profile> {
70        let email = json["email"].as_str().filter(|email| !email.is_empty())?;
71        Some(Profile {
72            email: email.to_string(),
73            display_name: json["displayName"].as_str().map(str::to_string),
74            icon: json["icon"].as_str().map(str::to_string),
75        })
76    }
77}
78
79/// One place you're signed in. `id` names the session; it is not its token.
80#[derive(Debug, Clone, Serialize, Deserialize)]
81pub struct Session {
82    pub id: String,
83    /// The session this call came from.
84    pub current: bool,
85    /// The browser or client that signed in, as its User-Agent named it.
86    pub agent: String,
87    pub created: DateTime<Utc>,
88    pub expires: DateTime<Utc>,
89}
90
91impl Session {
92    pub fn from_json(json: &Value) -> Session {
93        Session {
94            id: match &json["id"] {
95                Value::String(id) => id.clone(),
96                id => id.to_string(),
97            },
98            current: json["current"].as_bool() == Some(true),
99            agent: json["agent"].as_str().unwrap_or_default().to_string(),
100            created: parse_date(&json["created"]).unwrap_or_default(),
101            expires: parse_date(&json["expires"]).unwrap_or_default(),
102        }
103    }
104}
105
106/// `Credentials | ApiKey` in the TypeScript SDK.
107#[derive(Debug, Clone)]
108pub enum CredentialsOrApiKey {
109    Credentials(Credentials),
110    ApiKey(ApiKey),
111}
112
113/// `ApiKey | Group` in the TypeScript SDK.
114#[derive(Debug, Clone)]
115pub enum ApiKeyOrGroup {
116    ApiKey(ApiKey),
117    Group(Group),
118}
119
120/// `Partial<Pick<Credentials, 'displayName' | 'icon' | 'email' | 'phone'>>` in the
121/// TypeScript SDK. Email and phone are only accepted while that one isn't verified
122/// yet; a change sends a new link and code.
123#[derive(Debug, Clone, Default, Serialize)]
124#[serde(rename_all = "camelCase")]
125pub struct PartialCredentials {
126    #[serde(skip_serializing_if = "Option::is_none")]
127    pub display_name: Option<String>,
128    #[serde(skip_serializing_if = "Option::is_none")]
129    pub icon: Option<String>,
130    #[serde(skip_serializing_if = "Option::is_none")]
131    pub email: Option<String>,
132    #[serde(skip_serializing_if = "Option::is_none")]
133    pub phone: Option<String>,
134}
135
136/// `Partial<ApiKey>` in the TypeScript SDK.
137#[derive(Debug, Clone, Default, Serialize)]
138pub struct PartialApiKey {
139    #[serde(skip_serializing_if = "Option::is_none")]
140    pub id: Option<String>,
141    #[serde(skip_serializing_if = "Option::is_none")]
142    pub balance: Option<f64>,
143    #[serde(skip_serializing_if = "Option::is_none")]
144    pub services: Option<Vec<String>>,
145    #[serde(skip_serializing_if = "Option::is_none")]
146    pub name: Option<String>,
147}
148
149/// `Partial<Profile>` in the TypeScript SDK.
150#[derive(Debug, Clone, Default, Serialize)]
151#[serde(rename_all = "camelCase")]
152pub struct PartialProfile {
153    #[serde(skip_serializing_if = "Option::is_none")]
154    pub email: Option<String>,
155    #[serde(skip_serializing_if = "Option::is_none")]
156    pub display_name: Option<String>,
157    #[serde(skip_serializing_if = "Option::is_none")]
158    pub icon: Option<String>,
159}
160
161// Authorization
162pub async fn authorize(email: &str, password: &str) -> Result<Token> {
163    let response = client()
164        .post(format!("{}/authentification/authorize", crate::get_url()))
165        .json(&json!({ "email": email, "password": password }))
166        .send()
167        .await?;
168    Ok(ok(response).await?.text().await?)
169}
170
171pub async fn authorize_token(token: &str) -> Result<Credentials> {
172    let response = client()
173        .post(format!("{}/authentification/authorize", crate::get_url()))
174        .header("Authorization", format!("Token {token}"))
175        .send()
176        .await?;
177    let mut credentials: Credentials = ok(response).await?.json().await?;
178    credentials.token = token.to_string();
179    Ok(credentials)
180}
181
182pub async fn authorize_api_key(api_key: &str) -> Result<ApiKey> {
183    let response = client()
184        .post(format!("{}/authentification/authorize", crate::get_url()))
185        .header("Authorization", format!("ApiKey {api_key}"))
186        .send()
187        .await?;
188    Ok(ok(response).await?.json().await?)
189}
190
191// Credentials Management
192pub async fn create(
193    email: &str,
194    password: &str,
195    phone: &str,
196    display_name: Option<&str>,
197) -> Result<bool> {
198    let response = client()
199        .post(format!("{}/authentification/create", crate::get_url()))
200        .json(&json!({
201            "email": email,
202            "password": password,
203            "phone": phone,
204            "displayName": display_name,
205        }))
206        .send()
207        .await?;
208    ok(response).await?;
209    Ok(true)
210}
211
212pub async fn edit(credentials: &Credentials, update: &PartialCredentials) -> Result<bool> {
213    let response = client()
214        .patch(format!("{}/authentification", crate::get_url()))
215        .header("Authorization", format!("Token {}", credentials.token))
216        .json(update)
217        .send()
218        .await?;
219    ok(response).await?;
220    Ok(true)
221}
222
223pub async fn verify(channel: VerificationChannel, target: &str, code: &str) -> Result<bool> {
224    let response = client()
225        .post(format!("{}/authentification/verify", crate::get_url()))
226        .json(&json!({ "channel": channel, "target": target, "code": code }))
227        .send()
228        .await?;
229    ok(response).await?;
230    Ok(true)
231}
232
233pub async fn send_verification(
234    credentials: &Credentials,
235    channel: VerificationChannel,
236) -> Result<bool> {
237    let response = client()
238        .post(format!(
239            "{}/authentification/send-verification",
240            crate::get_url()
241        ))
242        .header("Authorization", format!("Token {}", credentials.token))
243        .json(&json!({ "channel": channel }))
244        .send()
245        .await?;
246    ok(response).await?;
247    Ok(true)
248}
249
250// Passwords and sessions
251/// Emails a link and code for choosing a new password, when an account has that
252/// email. Answers the same either way.
253pub async fn forgot_password(email: &str) -> Result<bool> {
254    let response = client()
255        .post(format!(
256            "{}/authentification/password/forgot",
257            crate::get_url()
258        ))
259        .json(&json!({ "email": email }))
260        .send()
261        .await?;
262    ok(response).await?;
263    Ok(true)
264}
265
266/// A new password, with the code from a reset email. The email counts as
267/// verified, and every session ends.
268pub async fn reset_password(email: &str, code: &str, password: &str) -> Result<bool> {
269    let response = client()
270        .post(format!(
271            "{}/authentification/password/reset",
272            crate::get_url()
273        ))
274        .json(&json!({ "email": email, "code": code, "password": password }))
275        .send()
276        .await?;
277    ok(response).await?;
278    Ok(true)
279}
280
281/// A new password, given the current one. Every other session ends; this one stays.
282pub async fn change_password(
283    credentials: &Credentials,
284    current: &str,
285    password: &str,
286) -> Result<bool> {
287    let response = client()
288        .post(format!("{}/authentification/password", crate::get_url()))
289        .header("Authorization", format!("Token {}", credentials.token))
290        .json(&json!({ "current": current, "password": password }))
291        .send()
292        .await?;
293    ok(response).await?;
294    Ok(true)
295}
296
297/// Your live sessions, newest first.
298pub async fn sessions(credentials: &Credentials, query: PageQuery) -> Result<Vec<Session>> {
299    let response = client()
300        .get(format!(
301            "{}/authentification/sessions?cursor={}&max={}",
302            crate::get_url(),
303            query.cursor,
304            query.max
305        ))
306        .header("Authorization", format!("Token {}", credentials.token))
307        .send()
308        .await?;
309    let rows: Vec<Value> = ok(response).await?.json().await?;
310    Ok(rows.iter().map(Session::from_json).collect())
311}
312
313/// Ends one of your sessions.
314pub async fn revoke_session(credentials: &Credentials, session: &Session) -> Result<bool> {
315    let response = client()
316        .delete(format!(
317            "{}/authentification/sessions/{}",
318            crate::get_url(),
319            encode(&session.id)
320        ))
321        .header("Authorization", format!("Token {}", credentials.token))
322        .send()
323        .await?;
324    ok(response).await?;
325    Ok(true)
326}
327
328/// Ends the session `credentials` signed in with.
329pub async fn sign_out(credentials: &Credentials) -> Result<bool> {
330    let response = client()
331        .post(format!("{}/authentification/sign-out", crate::get_url()))
332        .header("Authorization", format!("Token {}", credentials.token))
333        .send()
334        .await?;
335    ok(response).await?;
336    Ok(true)
337}
338
339/// Ends every one of your sessions, this one too.
340pub async fn sign_out_everywhere(credentials: &Credentials) -> Result<bool> {
341    let response = client()
342        .delete(format!("{}/authentification/sessions", crate::get_url()))
343        .header("Authorization", format!("Token {}", credentials.token))
344        .send()
345        .await?;
346    ok(response).await?;
347    Ok(true)
348}
349
350/// A single use code, good for a minute, that gives another page or app a new
351/// session of the same person, so no token rides in a URL.
352pub async fn handoff(credentials: &Credentials) -> Result<String> {
353    let response = client()
354        .post(format!("{}/authentification/handoff", crate::get_url()))
355        .header("Authorization", format!("Token {}", credentials.token))
356        .send()
357        .await?;
358    let json: Value = ok(response).await?.json().await?;
359    Ok(json["code"].as_str().unwrap_or_default().to_string())
360}
361
362/// Uses up a handoff code for the new session token it carries.
363pub async fn redeem_handoff(code: &str) -> Result<Token> {
364    let response = client()
365        .post(format!(
366            "{}/authentification/handoff/redeem",
367            crate::get_url()
368        ))
369        .json(&json!({ "code": code }))
370        .send()
371        .await?;
372    Ok(ok(response).await?.text().await?)
373}
374
375pub async fn allocate_balance(
376    credentials: &Credentials,
377    target: &ApiKeyOrGroup,
378    delta: f64,
379) -> Result<bool> {
380    let delta_micros = (delta * 1_000_000.0).round();
381    if !delta_micros.is_finite() || delta_micros.abs() > 9_007_199_254_740_991.0 {
382        return Err(Error::Message("Invalid balance delta.".to_string()));
383    }
384
385    let request = client()
386        .post(format!(
387            "{}/authentification/allocate-balance",
388            crate::get_url()
389        ))
390        .header("Authorization", format!("Token {}", credentials.token));
391    let request = match target {
392        ApiKeyOrGroup::ApiKey(key) => request.header("Api-Key", &key.id),
393        ApiKeyOrGroup::Group(group) => request.header("Group", &group.id),
394    };
395    let response = request
396        .json(&json!({ "deltaMicros": delta_micros as i64 }))
397        .send()
398        .await?;
399    ok(response).await?;
400    Ok(true)
401}
402
403pub async fn generate_api_key(credentials: &Credentials) -> Result<ApiKey> {
404    let response = client()
405        .post(format!("{}/authentification/api-keys", crate::get_url()))
406        .header("Content-Type", "application/json")
407        .header("Authorization", format!("Token {}", credentials.token))
408        .send()
409        .await?;
410    Ok(ok(response).await?.json().await?)
411}
412
413pub async fn remove_api_key(credentials: &Credentials, api_key: &ApiKey) -> Result<bool> {
414    let response = client()
415        .delete(format!(
416            "{}/authentification/api-keys/{}",
417            crate::get_url(),
418            encode(&api_key.id)
419        ))
420        .header("Authorization", format!("Token {}", credentials.token))
421        .send()
422        .await?;
423    ok(response).await?;
424    Ok(true)
425}
426
427pub async fn profile(credentials: &Credentials, email: &str) -> Result<Profile> {
428    let response = client()
429        .get(format!(
430            "{}/authentification/profile/{}",
431            crate::get_url(),
432            encode(email)
433        ))
434        .header("Authorization", format!("Token {}", credentials.token))
435        .send()
436        .await?;
437    Ok(ok(response).await?.json().await?)
438}
439
440/// Profiles matching a partial email or name, best first, at most 20. An admin's
441/// answer carries more; this keeps the profiles.
442pub async fn query(credentials: &Credentials, profile: &PartialProfile) -> Result<Vec<Profile>> {
443    let response = client()
444        .post(format!("{}/credentials/query", crate::get_url()))
445        .header("Authorization", format!("Token {}", credentials.token))
446        .json(&json!({ "email": profile.email, "displayName": profile.display_name }))
447        .send()
448        .await?;
449    let json: Value = ok(response).await?.json().await?;
450    Ok(serde_json::from_value(
451        json.get("accounts").cloned().unwrap_or(json),
452    )?)
453}
454
455pub async fn edit_api_key(
456    credentials: &Credentials,
457    api_key: &ApiKey,
458    update: &PartialApiKey,
459) -> Result<bool> {
460    let response = client()
461        .patch(format!(
462            "{}/authentification/api-keys/{}",
463            crate::get_url(),
464            encode(&api_key.id)
465        ))
466        .header("Authorization", format!("Token {}", credentials.token))
467        .json(&json!({ "name": update.name }))
468        .send()
469        .await?;
470    ok(response).await?;
471    Ok(true)
472}