Skip to main content

indodax_cli/commands/
auth.rs

1use crate::client::IndodaxClient;
2use crate::commands::helpers;
3use crate::config::{IndodaxConfig, SecretValue};
4use crate::output::CommandOutput;
5use anyhow::Result;
6
7#[derive(Debug, clap::Subcommand)]
8pub enum AuthCommand {
9    #[command(name = "set", about = "Set API key, secret and callback URL")]
10    Set {
11        #[arg(short = 'k', long = "api-key", help = "Your Indodax API key")]
12        api_key: Option<String>,
13        #[arg(short = 's', long = "api-secret", help = "Your Indodax API secret")]
14        api_secret: Option<String>,
15        #[arg(long = "api-secret-stdin", help = "Read API secret from stdin")]
16        api_secret_stdin: bool,
17        #[arg(long = "callback-url", help = "Your Indodax Callback URL")]
18        callback_url: Option<String>,
19    },
20
21    #[command(name = "show", about = "Show current API configuration")]
22    Show,
23
24    #[command(name = "test", about = "Test API credentials")]
25    Test,
26
27    #[command(name = "reset", about = "Remove stored API credentials")]
28    Reset,
29}
30
31pub async fn execute(
32    client: &IndodaxClient,
33    config: &mut IndodaxConfig,
34    cmd: &AuthCommand,
35) -> Result<CommandOutput> {
36    match cmd {
37        AuthCommand::Set { api_key, api_secret, api_secret_stdin, callback_url } => {
38            if let Some(key) = api_key {
39                config.api_key = Some(SecretValue::new(key));
40            }
41
42            if *api_secret_stdin {
43                let mut buf = String::new();
44                let mut stdin = tokio::io::BufReader::new(tokio::io::stdin());
45                use tokio::io::AsyncBufReadExt;
46                stdin.read_line(&mut buf).await?;
47                config.api_secret = Some(SecretValue::new(buf.trim().to_string()));
48            } else if let Some(s) = api_secret {
49                config.api_secret = Some(SecretValue::new(s.clone()));
50            }
51
52            if let Some(url) = callback_url {
53                config.callback_url = Some(url.clone());
54            }
55
56            config.save()?;
57
58            let data = serde_json::json!({
59                "status": "ok",
60                "message": "API configuration updated"
61            });
62            Ok(CommandOutput::json(data))
63        }
64
65        AuthCommand::Show => {
66            let key_status = config
67                .api_key
68                .as_ref()
69                .map_or("not set", |_| "set");
70            let secret_status = config
71                .api_secret
72                .as_ref()
73                .map_or("not set", |_| "set");
74            let callback_url = config
75                .callback_url
76                .as_deref()
77                .unwrap_or("not set");
78            let config_path = IndodaxConfig::config_path();
79
80            let headers = vec!["Field".into(), "Value".into()];
81            let rows = vec![
82                vec!["Config path".into(), config_path.display().to_string()],
83                vec!["API Key".into(), key_status.into()],
84                vec!["API Secret".into(), secret_status.into()],
85                vec!["Callback URL".into(), callback_url.into()],
86            ];
87
88            let masked_key = config.api_key.as_ref().map(|k| {
89                let s = k.as_str();
90                if s.len() > 4 {
91                    format!("{}****", &s[..4])
92                } else {
93                    "****".to_string()
94                }
95            });
96
97            let data = serde_json::json!({
98                "config_path": config_path.to_string_lossy(),
99                "api_key_set": config.api_key.is_some(),
100                "api_secret_set": config.api_secret.is_some(),
101                "masked_key": masked_key,
102                "callback_url": config.callback_url,
103            });
104
105            Ok(CommandOutput::new(data, headers, rows))
106        }
107
108        AuthCommand::Test => {
109            if config.api_key.is_none() || config.api_secret.is_none() {
110                return Err(anyhow::anyhow!(
111                    "No API credentials configured. Use 'indodax auth set' first."
112                ));
113            }
114
115            let test_params = std::collections::HashMap::new();
116            let result: serde_json::Value = client.private_post_v1("getInfo", &test_params).await?;
117
118            let balance = &result["balance"];
119            let bal_summary = if balance.is_object() {
120                balance
121                    .as_object()
122                    .map(|obj| {
123                        obj.iter()
124                            .filter(|(_, v)| v.as_f64().unwrap_or(0.0) > 0.0)
125                            .map(|(k, v)| format!("{}: {}", k, v))
126                            .collect::<Vec<_>>()
127                            .join(", ")
128                    })
129                    .unwrap_or_default()
130            } else {
131                "N/A".into()
132            };
133
134            let headers = vec!["Field".into(), "Value".into()];
135            let rows = vec![
136                vec!["Status".into(), "OK - Credentials valid".into()],
137                vec!["Name".into(), helpers::value_to_string(result.get("name").unwrap_or(&serde_json::Value::Null))],
138                vec!["Server Time".into(), helpers::value_to_string(result.get("server_time").unwrap_or(&serde_json::Value::Null))],
139                vec!["Balances (non-zero)".into(), bal_summary],
140            ];
141
142            Ok(CommandOutput::new(result, headers, rows))
143        }
144
145        AuthCommand::Reset => {
146            config.api_key = None;
147            config.api_secret = None;
148            config.callback_url = None;
149            config.save()?;
150
151            let data = serde_json::json!({
152                "status": "ok",
153                "message": "API credentials removed"
154            });
155                Ok(CommandOutput::json(data))
156        }
157    }
158}
159
160#[cfg(test)]
161mod tests {
162    use super::*;
163
164    #[test]
165    fn test_auth_command_set() {
166        let cmd = AuthCommand::Set {
167            api_key: Some("key123".into()),
168            api_secret: Some("secret456".into()),
169            api_secret_stdin: false,
170            callback_url: Some("http://callback.test".into()),
171        };
172        match cmd {
173            AuthCommand::Set { api_key, api_secret, api_secret_stdin, callback_url } => {
174                assert_eq!(api_key, Some("key123".into()));
175                assert_eq!(api_secret, Some("secret456".into()));
176                assert!(!api_secret_stdin);
177                assert_eq!(callback_url, Some("http://callback.test".into()));
178            }
179            _ => assert!(false, "Expected Set command, got {:?}", cmd),
180        }
181    }
182
183    #[test]
184    fn test_auth_command_show() {
185        let cmd = AuthCommand::Show;
186        match cmd {
187            AuthCommand::Show => (),
188            _ => assert!(false, "Expected Show command, got {:?}", cmd),
189        }
190    }
191
192    #[test]
193    fn test_auth_command_test() {
194        let cmd = AuthCommand::Test;
195        match cmd {
196            AuthCommand::Test => (),
197            _ => assert!(false, "Expected Test command, got {:?}", cmd),
198        }
199    }
200
201    #[test]
202    fn test_auth_command_reset() {
203        let cmd = AuthCommand::Reset;
204        match cmd {
205            AuthCommand::Reset => (),
206            _ => assert!(false, "Expected Reset command, got {:?}", cmd),
207        }
208    }
209
210    #[test]
211    fn test_auth_command_set_minimal() {
212        let cmd = AuthCommand::Set {
213            api_key: None,
214            api_secret: None,
215            api_secret_stdin: true,
216            callback_url: None,
217        };
218        match cmd {
219            AuthCommand::Set { api_key, api_secret, api_secret_stdin, callback_url } => {
220                assert!(api_key.is_none());
221                assert!(api_secret.is_none());
222                assert!(api_secret_stdin);
223                assert!(callback_url.is_none());
224            }
225            _ => assert!(false, "Expected Set command, got {:?}", cmd),
226        }
227    }
228
229    #[test]
230    fn test_auth_command_variants() {
231        let _cmd1 = AuthCommand::Set { 
232            api_key: None, 
233            api_secret: None, 
234            api_secret_stdin: false, 
235            callback_url: None 
236        };
237        let _cmd2 = AuthCommand::Show;
238        let _cmd3 = AuthCommand::Test;
239        let _cmd4 = AuthCommand::Reset;
240    }
241}