fauna-api 1.0.682

The Fauna SDK for Rust: accounts, Drive, groups, calendar, chats, payments, Parrot and live rooms.
Documentation
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};

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

// 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, 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),
        })
    }
}

/// `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, 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)
}

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?)
}

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

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)
}