Skip to main content

fauna_api/
authentification.rs

1use serde::{Deserialize, Serialize};
2use serde_json::{Value, json};
3
4use crate::error::{Error, Result};
5use crate::groups::Group;
6use crate::http::{client, encode, ok};
7use crate::integrations::Platform;
8
9// Authorization Types
10#[derive(Debug, Clone, Default, Serialize, Deserialize)]
11#[serde(default, rename_all = "camelCase")]
12pub struct Credentials {
13    pub token: Token,
14
15    pub email_verified: bool,
16    pub phone_verified: bool,
17    pub permissions: Vec<String>,
18    pub integrations: Vec<Platform>,
19
20    pub email: String,
21    pub phone: String,
22
23    #[serde(skip_serializing_if = "Option::is_none")]
24    pub display_name: Option<String>,
25    #[serde(skip_serializing_if = "Option::is_none")]
26    pub icon: Option<String>,
27
28    pub api_keys: Vec<ApiKey>,
29
30    pub balance: f64,
31}
32
33/// `'EMAIL' | 'PHONE'` in the TypeScript SDK.
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
35#[serde(rename_all = "UPPERCASE")]
36pub enum VerificationChannel {
37    Email,
38    Phone,
39}
40
41#[derive(Debug, Clone, Default, Serialize, Deserialize)]
42#[serde(default, rename_all = "camelCase")]
43pub struct ApiKey {
44    pub id: String,
45
46    pub balance: f64,
47    pub services: Vec<String>,
48
49    #[serde(skip_serializing_if = "Option::is_none")]
50    pub name: Option<String>,
51}
52
53pub type Token = String;
54
55#[derive(Debug, Clone, Default, Serialize, Deserialize)]
56#[serde(default, rename_all = "camelCase")]
57pub struct Profile {
58    pub email: String,
59    #[serde(skip_serializing_if = "Option::is_none")]
60    pub display_name: Option<String>,
61    #[serde(skip_serializing_if = "Option::is_none")]
62    pub icon: Option<String>,
63}
64
65impl Profile {
66    pub fn from_json(json: &Value) -> Option<Profile> {
67        let email = json["email"].as_str().filter(|email| !email.is_empty())?;
68        Some(Profile {
69            email: email.to_string(),
70            display_name: json["displayName"].as_str().map(str::to_string),
71            icon: json["icon"].as_str().map(str::to_string),
72        })
73    }
74}
75
76/// `Credentials | ApiKey` in the TypeScript SDK.
77#[derive(Debug, Clone)]
78pub enum CredentialsOrApiKey {
79    Credentials(Credentials),
80    ApiKey(ApiKey),
81}
82
83/// `ApiKey | Group` in the TypeScript SDK.
84#[derive(Debug, Clone)]
85pub enum ApiKeyOrGroup {
86    ApiKey(ApiKey),
87    Group(Group),
88}
89
90/// `Partial<Pick<Credentials, 'displayName' | 'icon' | 'email' | 'phone'>>` in the
91/// TypeScript SDK. Email and phone are only accepted while that one isn't verified
92/// yet; a change sends a new link and code.
93#[derive(Debug, Clone, Default, Serialize)]
94#[serde(rename_all = "camelCase")]
95pub struct PartialCredentials {
96    #[serde(skip_serializing_if = "Option::is_none")]
97    pub display_name: Option<String>,
98    #[serde(skip_serializing_if = "Option::is_none")]
99    pub icon: Option<String>,
100    #[serde(skip_serializing_if = "Option::is_none")]
101    pub email: Option<String>,
102    #[serde(skip_serializing_if = "Option::is_none")]
103    pub phone: Option<String>,
104}
105
106/// `Partial<ApiKey>` in the TypeScript SDK.
107#[derive(Debug, Clone, Default, Serialize)]
108pub struct PartialApiKey {
109    #[serde(skip_serializing_if = "Option::is_none")]
110    pub id: Option<String>,
111    #[serde(skip_serializing_if = "Option::is_none")]
112    pub balance: Option<f64>,
113    #[serde(skip_serializing_if = "Option::is_none")]
114    pub services: Option<Vec<String>>,
115    #[serde(skip_serializing_if = "Option::is_none")]
116    pub name: Option<String>,
117}
118
119/// `Partial<Profile>` in the TypeScript SDK.
120#[derive(Debug, Clone, Default, Serialize)]
121#[serde(rename_all = "camelCase")]
122pub struct PartialProfile {
123    #[serde(skip_serializing_if = "Option::is_none")]
124    pub email: Option<String>,
125    #[serde(skip_serializing_if = "Option::is_none")]
126    pub display_name: Option<String>,
127    #[serde(skip_serializing_if = "Option::is_none")]
128    pub icon: Option<String>,
129}
130
131// Authorization
132pub async fn authorize(email: &str, password: &str) -> Result<Token> {
133    let response = client()
134        .post(format!("{}/authentification/authorize", crate::get_url()))
135        .json(&json!({ "email": email, "password": password }))
136        .send()
137        .await?;
138    Ok(ok(response).await?.text().await?)
139}
140
141pub async fn authorize_token(token: &str) -> Result<Credentials> {
142    let response = client()
143        .post(format!("{}/authentification/authorize", crate::get_url()))
144        .header("Authorization", format!("Token {token}"))
145        .send()
146        .await?;
147    let mut credentials: Credentials = ok(response).await?.json().await?;
148    credentials.token = token.to_string();
149    Ok(credentials)
150}
151
152pub async fn authorize_api_key(api_key: &str) -> Result<ApiKey> {
153    let response = client()
154        .post(format!("{}/authentification/authorize", crate::get_url()))
155        .header("Authorization", format!("ApiKey {api_key}"))
156        .send()
157        .await?;
158    Ok(ok(response).await?.json().await?)
159}
160
161// Credentials Management
162pub async fn create(
163    email: &str,
164    password: &str,
165    phone: &str,
166    display_name: Option<&str>,
167) -> Result<bool> {
168    let response = client()
169        .post(format!("{}/authentification/create", crate::get_url()))
170        .json(&json!({
171            "email": email,
172            "password": password,
173            "phone": phone,
174            "displayName": display_name,
175        }))
176        .send()
177        .await?;
178    ok(response).await?;
179    Ok(true)
180}
181
182pub async fn edit(credentials: &Credentials, update: &PartialCredentials) -> Result<bool> {
183    let response = client()
184        .patch(format!("{}/authentification", crate::get_url()))
185        .header("Authorization", format!("Token {}", credentials.token))
186        .json(update)
187        .send()
188        .await?;
189    ok(response).await?;
190    Ok(true)
191}
192
193pub async fn verify(channel: VerificationChannel, target: &str, code: &str) -> Result<bool> {
194    let response = client()
195        .post(format!("{}/authentification/verify", crate::get_url()))
196        .json(&json!({ "channel": channel, "target": target, "code": code }))
197        .send()
198        .await?;
199    ok(response).await?;
200    Ok(true)
201}
202
203pub async fn send_verification(
204    credentials: &Credentials,
205    channel: VerificationChannel,
206) -> Result<bool> {
207    let response = client()
208        .post(format!(
209            "{}/authentification/send-verification",
210            crate::get_url()
211        ))
212        .header("Authorization", format!("Token {}", credentials.token))
213        .json(&json!({ "channel": channel }))
214        .send()
215        .await?;
216    ok(response).await?;
217    Ok(true)
218}
219
220pub async fn allocate_balance(
221    credentials: &Credentials,
222    target: &ApiKeyOrGroup,
223    delta: f64,
224) -> Result<bool> {
225    let delta_micros = (delta * 1_000_000.0).round();
226    if !delta_micros.is_finite() || delta_micros.abs() > 9_007_199_254_740_991.0 {
227        return Err(Error::Message("Invalid balance delta.".to_string()));
228    }
229
230    let request = client()
231        .post(format!(
232            "{}/authentification/allocate-balance",
233            crate::get_url()
234        ))
235        .header("Authorization", format!("Token {}", credentials.token));
236    let request = match target {
237        ApiKeyOrGroup::ApiKey(key) => request.header("Api-Key", &key.id),
238        ApiKeyOrGroup::Group(group) => request.header("Group", &group.id),
239    };
240    let response = request
241        .json(&json!({ "deltaMicros": delta_micros as i64 }))
242        .send()
243        .await?;
244    ok(response).await?;
245    Ok(true)
246}
247
248pub async fn generate_api_key(credentials: &Credentials) -> Result<ApiKey> {
249    let response = client()
250        .post(format!("{}/authentification/api-keys", crate::get_url()))
251        .header("Content-Type", "application/json")
252        .header("Authorization", format!("Token {}", credentials.token))
253        .send()
254        .await?;
255    Ok(ok(response).await?.json().await?)
256}
257
258pub async fn remove_api_key(credentials: &Credentials, api_key: &ApiKey) -> Result<bool> {
259    let response = client()
260        .delete(format!(
261            "{}/authentification/api-keys/{}",
262            crate::get_url(),
263            encode(&api_key.id)
264        ))
265        .header("Authorization", format!("Token {}", credentials.token))
266        .send()
267        .await?;
268    ok(response).await?;
269    Ok(true)
270}
271
272pub async fn profile(credentials: &Credentials, email: &str) -> Result<Profile> {
273    let response = client()
274        .get(format!(
275            "{}/authentification/profile/{}",
276            crate::get_url(),
277            encode(email)
278        ))
279        .header("Authorization", format!("Token {}", credentials.token))
280        .send()
281        .await?;
282    Ok(ok(response).await?.json().await?)
283}
284
285pub async fn query(credentials: &Credentials, profile: &PartialProfile) -> Result<Vec<Profile>> {
286    let response = client()
287        .post(format!("{}/authentification/query", crate::get_url()))
288        .header("Authorization", format!("Token {}", credentials.token))
289        .json(&json!({ "email": profile.email, "displayName": profile.display_name }))
290        .send()
291        .await?;
292    Ok(ok(response).await?.json().await?)
293}
294
295pub async fn edit_api_key(
296    credentials: &Credentials,
297    api_key: &ApiKey,
298    update: &PartialApiKey,
299) -> Result<bool> {
300    let response = client()
301        .patch(format!(
302            "{}/authentification/api-keys/{}",
303            crate::get_url(),
304            encode(&api_key.id)
305        ))
306        .header("Authorization", format!("Token {}", credentials.token))
307        .json(&json!({ "name": update.name }))
308        .send()
309        .await?;
310    ok(response).await?;
311    Ok(true)
312}