From cc385a9f2f25245a3a7750e19eeef734f638d20b Mon Sep 17 00:00:00 2001 From: Jonathan Grahl Date: Wed, 21 Feb 2024 13:50:00 +0100 Subject: [PATCH] fix: error handling for expired token --- src/commands/auth.rs | 18 ++++++++++++------ src/config/user.rs | 8 ++++++++ 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/src/commands/auth.rs b/src/commands/auth.rs index 77c9578..af5662b 100644 --- a/src/commands/auth.rs +++ b/src/commands/auth.rs @@ -44,7 +44,7 @@ pub enum Commands { /// Login to Molnett Login(Login), - // Login to Docker Registry + /// Login to Docker Registry using Molnett token Docker(Docker), } @@ -97,6 +97,8 @@ impl Login { if let Some(expires_in) = oauthtoken.expires_in() { token.expiry = Some(Utc::now() + chrono::Duration::seconds(expires_in.as_secs() as i64)); + } else { + token.expiry = Some(Utc::now() + chrono::Duration::hours(1)); } base.user_config_mut().write_token(token)?; @@ -114,10 +116,14 @@ pub struct Docker {} impl Docker { pub fn execute(&self, base: &mut CommandBase) -> Result<()> { - let token = base - .user_config - .get_token() - .ok_or_else(|| anyhow!("PANIC"))?; + let token = base.user_config.get_token().ok_or_else(|| { + anyhow!("Could not get Molnett token. Please run molnctl auth login.") + })?; + + if base.user_config.is_token_expired() { + println!("Token expired. Please run molnctl auth login."); + return Ok(()); + } let mut command = Command::new("docker") .arg("login") @@ -129,7 +135,7 @@ impl Docker { .spawn()?; if let Some(mut stdin) = command.stdin.take() { - stdin.write_all(token.as_bytes())?; // drop would happen here + stdin.write_all(token.as_bytes())?; } let output = command.wait_with_output()?; diff --git a/src/config/user.rs b/src/config/user.rs index 9a2c6a2..2f4ae47 100644 --- a/src/config/user.rs +++ b/src/config/user.rs @@ -66,6 +66,14 @@ impl UserConfig { pub fn get_token(&self) -> Option<&str> { self.config.token.as_ref().map(|u| u.access_token.as_str()) } + pub fn is_token_expired(&self) -> bool { + if let Some(token) = &self.config.token { + if let Some(expiry) = token.expiry { + return expiry < chrono::Utc::now(); + } + } + true + } pub fn write_token(&mut self, token: Token) -> Result<(), super::Error> { self.disk_config.token = Some(token.clone()); self.config.token = Some(token);