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                let visible_len = (s.len() / 4).min(4);
91                if visible_len > 0 {
92                    format!("{}****", &s[..visible_len])
93                } else {
94                    "****".to_string()
95                }
96            });
97
98            let data = serde_json::json!({
99                "config_path": config_path.to_string_lossy(),
100                "api_key_set": config.api_key.is_some(),
101                "api_secret_set": config.api_secret.is_some(),
102                "masked_key": masked_key,
103                "callback_url": config.callback_url,
104            });
105
106            Ok(CommandOutput::new(data, headers, rows))
107        }
108
109        AuthCommand::Test => {
110            let test_params = std::collections::HashMap::new();
111            let result: serde_json::Value = client.private_post_v1("getInfo", &test_params).await?;
112
113            let balance = &result["balance"];
114            let bal_summary = if balance.is_object() {
115                balance
116                    .as_object()
117                    .map(|obj| {
118                        obj.iter()
119                            .filter(|(_, v)| v.as_f64().unwrap_or(0.0) > 0.0)
120                            .map(|(k, v)| format!("{}: {}", k, v))
121                            .collect::<Vec<_>>()
122                            .join(", ")
123                    })
124                    .unwrap_or_default()
125            } else {
126                "N/A".into()
127            };
128
129            let headers = vec!["Field".into(), "Value".into()];
130            let rows = vec![
131                vec!["Status".into(), "OK - Credentials valid".into()],
132                vec!["Name".into(), helpers::value_to_string(result.get("name").unwrap_or(&serde_json::Value::Null))],
133                vec!["Server Time".into(), helpers::value_to_string(result.get("server_time").unwrap_or(&serde_json::Value::Null))],
134                vec!["Balances (non-zero)".into(), bal_summary],
135            ];
136
137            Ok(CommandOutput::new(result, headers, rows))
138        }
139
140        AuthCommand::Reset => {
141            config.api_key = None;
142            config.api_secret = None;
143            config.callback_url = None;
144            config.save()?;
145
146            let data = serde_json::json!({
147                "status": "ok",
148                "message": "API credentials removed"
149            });
150                Ok(CommandOutput::json(data))
151        }
152    }
153}
154
155#[cfg(test)]
156mod tests {
157    use super::*;
158
159    #[test]
160    fn test_auth_command_set() {
161        let cmd = AuthCommand::Set {
162            api_key: Some("key123".into()),
163            api_secret: Some("secret456".into()),
164            api_secret_stdin: false,
165            callback_url: Some("http://callback.test".into()),
166        };
167        match cmd {
168            AuthCommand::Set { api_key, api_secret, api_secret_stdin, callback_url } => {
169                assert_eq!(api_key, Some("key123".into()));
170                assert_eq!(api_secret, Some("secret456".into()));
171                assert!(!api_secret_stdin);
172                assert_eq!(callback_url, Some("http://callback.test".into()));
173            }
174            _ => assert!(false, "Expected Set command, got {:?}", cmd),
175        }
176    }
177
178    #[test]
179    fn test_auth_command_show() {
180        let cmd = AuthCommand::Show;
181        match cmd {
182            AuthCommand::Show => (),
183            _ => assert!(false, "Expected Show command, got {:?}", cmd),
184        }
185    }
186
187    #[test]
188    fn test_auth_command_test() {
189        let cmd = AuthCommand::Test;
190        match cmd {
191            AuthCommand::Test => (),
192            _ => assert!(false, "Expected Test command, got {:?}", cmd),
193        }
194    }
195
196    #[test]
197    fn test_auth_command_reset() {
198        let cmd = AuthCommand::Reset;
199        match cmd {
200            AuthCommand::Reset => (),
201            _ => assert!(false, "Expected Reset command, got {:?}", cmd),
202        }
203    }
204
205    #[test]
206    fn test_auth_command_set_minimal() {
207        let cmd = AuthCommand::Set {
208            api_key: None,
209            api_secret: None,
210            api_secret_stdin: true,
211            callback_url: None,
212        };
213        match cmd {
214            AuthCommand::Set { api_key, api_secret, api_secret_stdin, callback_url } => {
215                assert!(api_key.is_none());
216                assert!(api_secret.is_none());
217                assert!(api_secret_stdin);
218                assert!(callback_url.is_none());
219            }
220            _ => assert!(false, "Expected Set command, got {:?}", cmd),
221        }
222    }
223
224    #[test]
225    fn test_auth_command_variants() {
226        let _cmd1 = AuthCommand::Set { 
227            api_key: None, 
228            api_secret: None, 
229            api_secret_stdin: false, 
230            callback_url: None 
231        };
232        let _cmd2 = AuthCommand::Show;
233        let _cmd3 = AuthCommand::Test;
234        let _cmd4 = AuthCommand::Reset;
235    }
236}