fix: Cleanup temporary file after feeding auth data

Related: #366
This commit is contained in:
Kevin Yue 2024-06-11 22:20:49 +08:00
parent a25b5cb894
commit 54d4f2ec57
3 changed files with 22 additions and 11 deletions

View File

@ -1,4 +1,4 @@
use std::{collections::HashMap, fs, path::PathBuf}; use std::{collections::HashMap, env::temp_dir, fs, path::PathBuf};
use clap::Args; use clap::Args;
use directories::ProjectDirs; use directories::ProjectDirs;
@ -82,6 +82,11 @@ impl<'a> LaunchGuiHandler<'a> {
async fn feed_auth_data(auth_data: &str) -> anyhow::Result<()> { async fn feed_auth_data(auth_data: &str) -> anyhow::Result<()> {
let _ = tokio::join!(feed_auth_data_gui(auth_data), feed_auth_data_cli(auth_data)); let _ = tokio::join!(feed_auth_data_gui(auth_data), feed_auth_data_cli(auth_data));
// Cleanup the temporary file
let html_file = temp_dir().join("gpauth.html");
let _ = std::fs::remove_file(html_file);
Ok(()) Ok(())
} }

View File

@ -70,6 +70,7 @@ impl SamlAuthData {
let auth_data: SamlAuthData = serde_urlencoded::from_str(auth_data).map_err(|e| { let auth_data: SamlAuthData = serde_urlencoded::from_str(auth_data).map_err(|e| {
warn!("Failed to parse token auth data: {}", e); warn!("Failed to parse token auth data: {}", e);
warn!("Auth data: {}", auth_data);
AuthDataParseError::Invalid AuthDataParseError::Invalid
})?; })?;

View File

@ -1,4 +1,7 @@
use std::{env::temp_dir, io::Write}; use std::{env::temp_dir, fs, io::Write, os::unix::fs::PermissionsExt};
use anyhow::bail;
use log::warn;
pub struct BrowserAuthenticator<'a> { pub struct BrowserAuthenticator<'a> {
auth_request: &'a str, auth_request: &'a str,
@ -14,8 +17,18 @@ impl BrowserAuthenticator<'_> {
open::that_detached(self.auth_request)?; open::that_detached(self.auth_request)?;
} else { } else {
let html_file = temp_dir().join("gpauth.html"); let html_file = temp_dir().join("gpauth.html");
let mut file = std::fs::File::create(&html_file)?;
// Remove the file and error if permission denied
if let Err(err) = fs::remove_file(&html_file) {
if err.kind() != std::io::ErrorKind::NotFound {
warn!("Failed to remove the temporary file: {}", err);
bail!("Please remove the file manually: {:?}", html_file);
}
}
let mut file = fs::File::create(&html_file)?;
file.set_permissions(fs::Permissions::from_mode(0o600))?;
file.write_all(self.auth_request.as_bytes())?; file.write_all(self.auth_request.as_bytes())?;
open::that_detached(html_file)?; open::that_detached(html_file)?;
@ -24,11 +37,3 @@ impl BrowserAuthenticator<'_> {
Ok(()) Ok(())
} }
} }
impl Drop for BrowserAuthenticator<'_> {
fn drop(&mut self) {
// Cleanup the temporary file
let html_file = temp_dir().join("gpauth.html");
let _ = std::fs::remove_file(html_file);
}
}