|
| 1 | +use anyhow::{anyhow, Result}; |
| 2 | +use base64_url; |
| 3 | +use dirs; |
| 4 | +use serde::{Deserialize, Serialize}; |
| 5 | +use serde_yaml; |
| 6 | +use std::fs::{File, OpenOptions}; |
| 7 | +use std::path::PathBuf; |
| 8 | +use urlencoding; |
| 9 | +use webbrowser; |
| 10 | + |
| 11 | +use crate::service; // Assuming service::create_client is needed |
| 12 | + |
| 13 | +// Configuration structure |
| 14 | +#[derive(Serialize, Deserialize, Debug, Default)] |
| 15 | +struct Config { |
| 16 | + cli_id: Option<String>, |
| 17 | +} |
| 18 | + |
| 19 | +// Helper function to get the config file path |
| 20 | +fn get_config_path() -> Result<PathBuf> { |
| 21 | + dirs::home_dir() |
| 22 | + .map(|mut path| { |
| 23 | + path.push(".popcorn.yaml"); |
| 24 | + path |
| 25 | + }) |
| 26 | + .ok_or_else(|| anyhow!("Could not find home directory")) |
| 27 | +} |
| 28 | + |
| 29 | +// Helper function to load config |
| 30 | +fn load_config() -> Result<Config> { |
| 31 | + let path = get_config_path()?; |
| 32 | + if !path.exists() { |
| 33 | + return Ok(Config::default()); |
| 34 | + } |
| 35 | + let file = File::open(path)?; |
| 36 | + serde_yaml::from_reader(file).map_err(|e| anyhow!("Failed to parse config file: {}", e)) |
| 37 | +} |
| 38 | + |
| 39 | +// Helper function to save config |
| 40 | +fn save_config(config: &Config) -> Result<()> { |
| 41 | + let path = get_config_path()?; |
| 42 | + let file = OpenOptions::new() |
| 43 | + .write(true) |
| 44 | + .create(true) |
| 45 | + .truncate(true) // Overwrite existing file |
| 46 | + .open(path)?; |
| 47 | + serde_yaml::to_writer(file, config).map_err(|e| anyhow!("Failed to write config file: {}", e)) |
| 48 | +} |
| 49 | + |
| 50 | +// Structure for the API response |
| 51 | +#[derive(Deserialize)] |
| 52 | +struct AuthInitResponse { |
| 53 | + state: String, // This is the cli_id |
| 54 | +} |
| 55 | + |
| 56 | +// Function to handle the login logic |
| 57 | +pub async fn run_auth(reset: bool, auth_provider: &str) -> Result<()> { |
| 58 | + println!("Attempting authentication via {}...", auth_provider); |
| 59 | + |
| 60 | + let popcorn_api_url = std::env::var("POPCORN_API_URL") |
| 61 | + .map_err(|_| anyhow!("POPCORN_API_URL environment variable not set"))?; |
| 62 | + |
| 63 | + let client = service::create_client(None)?; |
| 64 | + |
| 65 | + let init_url = format!("{}/auth/init?provider={}", popcorn_api_url, auth_provider); |
| 66 | + println!("Requesting CLI ID from {}", init_url); |
| 67 | + |
| 68 | + let init_resp = client.get(&init_url).send().await?; |
| 69 | + |
| 70 | + let status = init_resp.status(); |
| 71 | + |
| 72 | + if !status.is_success() { |
| 73 | + let error_text = init_resp.text().await?; |
| 74 | + return Err(anyhow!( |
| 75 | + "Failed to initialize auth ({}): {}", |
| 76 | + status, |
| 77 | + error_text |
| 78 | + )); |
| 79 | + } |
| 80 | + |
| 81 | + let auth_init_data: AuthInitResponse = init_resp.json().await?; |
| 82 | + let cli_id = auth_init_data.state; |
| 83 | + println!("Received CLI ID: {}", cli_id); |
| 84 | + |
| 85 | + let state_json = serde_json::json!({ |
| 86 | + "cli_id": cli_id, |
| 87 | + "is_reset": reset |
| 88 | + }) |
| 89 | + .to_string(); |
| 90 | + let state_b64 = base64_url::encode(&state_json); |
| 91 | + |
| 92 | + let auth_url = match auth_provider { |
| 93 | + "discord" => { |
| 94 | + let base_auth_url = "https://discord.com/oauth2/authorize?client_id=1357446383497511096&response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2Fauth%2Fcli%2Fdiscord&scope=identify"; |
| 95 | + format!("{}&state={}", base_auth_url, state_b64) |
| 96 | + } |
| 97 | + "github" => { |
| 98 | + let client_id = "Ov23lieFd2onYk4OnKIR"; |
| 99 | + let redirect_uri = "http://localhost:8000/auth/cli/github"; |
| 100 | + // URL encode the redirect URI |
| 101 | + let encoded_redirect_uri = urlencoding::encode(redirect_uri); |
| 102 | + format!( |
| 103 | + "https://github.com/login/oauth/authorize?client_id={}&redirect_uri={}&state={}", |
| 104 | + client_id, encoded_redirect_uri, state_b64 |
| 105 | + ) |
| 106 | + } |
| 107 | + _ => { |
| 108 | + return Err(anyhow!( |
| 109 | + "Unsupported authentication provider: {}", |
| 110 | + auth_provider |
| 111 | + )) |
| 112 | + } |
| 113 | + }; |
| 114 | + |
| 115 | + println!( |
| 116 | + "\n>>> Please open the following URL in your browser to log in via {}:", |
| 117 | + auth_provider |
| 118 | + ); |
| 119 | + println!("{}", auth_url); |
| 120 | + println!("\nWaiting for you to complete the authentication in your browser..."); |
| 121 | + println!( |
| 122 | + "After successful authentication with {}, the CLI ID will be saved.", |
| 123 | + auth_provider |
| 124 | + ); |
| 125 | + |
| 126 | + if webbrowser::open(&auth_url).is_err() { |
| 127 | + println!( |
| 128 | + "Could not automatically open the browser. Please copy the URL above and paste it manually." |
| 129 | + ); |
| 130 | + } |
| 131 | + |
| 132 | + // Save the cli_id to config file optimistically |
| 133 | + let mut config = load_config().unwrap_or_default(); |
| 134 | + config.cli_id = Some(cli_id.clone()); |
| 135 | + save_config(&config)?; |
| 136 | + |
| 137 | + println!( |
| 138 | + "\nSuccessfully initiated authentication. Your CLI ID ({}) has been saved to {}. To use the CLI on different machines, you can copy the config file.", |
| 139 | + cli_id, |
| 140 | + get_config_path()?.display() |
| 141 | + ); |
| 142 | + println!("You can now use other commands that require authentication."); |
| 143 | + |
| 144 | + Ok(()) |
| 145 | +} |
0 commit comments