diff --git a/src/mako/cli/lib/engine.mako b/src/mako/cli/lib/engine.mako index f18e1112cb0..548755ed215 100644 --- a/src/mako/cli/lib/engine.mako +++ b/src/mako/cli/lib/engine.mako @@ -12,15 +12,14 @@ hub_type_name = 'api::' + hub_type(c.schemas, util.canonical_name()) %>\ mod cmn; -use cmn::InvalidOptionsError; -use std::default::Default; +use cmn::{InvalidOptionsError, JsonTokenStorage}; -use oauth2::{Authenticator, DefaultAuthenticatorDelegate, MemoryStorage}; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate}; struct Engine { opt: Options, config_dir: String, - hub: ${hub_type_name}>, + hub: ${hub_type_name}>, } @@ -83,7 +82,10 @@ self.opt.${cmd_ident(method)} { let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, hyper::Client::new(), - ::default(), None); + JsonTokenStorage { + program_name: "${util.program_name()}", + db_dir: config_dir.clone(), + }, None); let engine = Engine { opt: opt, config_dir: config_dir, diff --git a/src/rust/cli/cmn.rs b/src/rust/cli/cmn.rs index c65af983e73..de0d1977ab6 100644 --- a/src/rust/cli/cmn.rs +++ b/src/rust/cli/cmn.rs @@ -1,16 +1,52 @@ -use oauth2::{ApplicationSecret, ConsoleApplicationSecret}; +use oauth2::{ApplicationSecret, ConsoleApplicationSecret, TokenStorage, Token}; use rustc_serialize::json; use std::fs; use std::env; use std::io; use std::fmt; -use std::path::Path; +use std::path::{Path, PathBuf}; use std::io::{Write, Read}; use std::default::Default; + +pub struct JsonTokenStorage { + pub program_name: &'static str, + pub db_dir: String, +} + +impl JsonTokenStorage { + fn path(&self, scope_hash: u64) -> PathBuf { + Path::new(&self.db_dir).join(&format!("{}-token-{}.json", self.program_name, scope_hash)) + } +} + +impl TokenStorage for JsonTokenStorage { + // NOTE: logging might be interesting, currently we swallow all errors + fn set(&mut self, scope_hash: u64, token: Option) { + let json_token = json::encode(&token).unwrap(); + let res = fs::OpenOptions::new().create(true).write(true).open(&self.path(scope_hash)); + if let Ok(mut f) = res { + f.write(json_token.as_bytes()).ok(); + } + } + + fn get(&self, scope_hash: u64) -> Option { + if let Ok(mut f) = fs::File::open(&self.path(scope_hash)) { + let mut json_string = String::new(); + if let Ok(_) = f.read_to_string(&mut json_string) { + if let Ok(token) = json::decode::(&json_string) { + return Some(token) + } + } + } + None + } +} + + #[derive(Debug)] pub enum ApplicationSecretError { DecoderError((String, json::DecoderError)),