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
pub mod cli;
pub mod handler;

use anyhow::{anyhow, Result};
use log::debug;
use reqwest::Client;
use smbpndk_model::{AuthApp, AuthAppCreate};
use smbpndk_networking::{constants::BASE_URL, get_token};

async fn get_auth_apps() -> Result<Vec<AuthApp>> {
    // Get current token
    let token = get_token().await?;

    let response = Client::new()
        .get([BASE_URL, "v1/auth_apps"].join(""))
        .header("Authorization", token)
        .send()
        .await?;

    match response.status() {
        reqwest::StatusCode::OK => {
            let auth_apps: Vec<AuthApp> = response.json().await?;
            Ok(auth_apps)
        }
        _ => Err(anyhow!("Failed to fetch auth apps.")),
    }
}

async fn get_auth_app(id: &str) -> Result<AuthApp> {
    // Get current token
    let token = get_token().await?;

    let response = Client::new()
        .get([BASE_URL, "v1/auth_apps/", id].join(""))
        .header("Authorization", token)
        .send()
        .await?;

    match response.status() {
        reqwest::StatusCode::OK => {
            let auth_app: AuthApp = response.json().await?;
            println!("Auth app requested: {auth_app:#?}");
            Ok(auth_app)
        }
        _ => Err(anyhow!(format!(
            "Failed to find an auth app with id: {id}."
        ))),
    }
}

async fn delete_auth_app(id: String) -> Result<()> {
    // Get current token
    let token = get_token().await?;

    let response = Client::new()
        .delete([BASE_URL, "v1/auth_apps/", &id].join(""))
        .header("Authorization", token)
        .send()
        .await?;

    match response.status() {
        reqwest::StatusCode::OK => {
            debug!("Project deleted.");
            Ok(())
        }
        _ => Err(anyhow!("Failed to delete an auth app.")),
    }
}

async fn create_auth_app(auth_app: AuthAppCreate) -> Result<AuthApp> {
    // Get current token
    let token = get_token().await?;

    let response = Client::new()
        .post([BASE_URL, "v1/auth_apps"].join(""))
        .json(&auth_app)
        .header("Authorization", token)
        .send()
        .await?;

    match response.status() {
        reqwest::StatusCode::CREATED => {
            let auth_app: AuthApp = response.json().await?;
            println!("Project created: {auth_app:#?}");
            Ok(auth_app)
        }
        _ => Err(anyhow!("Failed to create an auth app.")),
    }
}