|
1 | | -use oauth2::{ApplicationSecret, ConsoleApplicationSecret}; |
| 1 | +use oauth2::{ApplicationSecret, ConsoleApplicationSecret, TokenStorage, Token}; |
2 | 2 | use rustc_serialize::json; |
3 | 3 |
|
4 | 4 | use std::fs; |
5 | 5 | use std::env; |
6 | 6 | use std::io; |
7 | 7 | use std::fmt; |
8 | | -use std::path::Path; |
| 8 | +use std::path::{Path, PathBuf}; |
9 | 9 |
|
10 | 10 | use std::io::{Write, Read}; |
11 | 11 |
|
12 | 12 | use std::default::Default; |
13 | 13 |
|
| 14 | + |
| 15 | +pub struct JsonTokenStorage { |
| 16 | + pub program_name: &'static str, |
| 17 | + pub db_dir: String, |
| 18 | +} |
| 19 | + |
| 20 | +impl JsonTokenStorage { |
| 21 | + fn path(&self, scope_hash: u64) -> PathBuf { |
| 22 | + Path::new(&self.db_dir).join(&format!("{}-token-{}.json", self.program_name, scope_hash)) |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +impl TokenStorage for JsonTokenStorage { |
| 27 | + // NOTE: logging might be interesting, currently we swallow all errors |
| 28 | + fn set(&mut self, scope_hash: u64, token: Option<Token>) { |
| 29 | + let json_token = json::encode(&token).unwrap(); |
| 30 | + let res = fs::OpenOptions::new().create(true).write(true).open(&self.path(scope_hash)); |
| 31 | + if let Ok(mut f) = res { |
| 32 | + f.write(json_token.as_bytes()).ok(); |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + fn get(&self, scope_hash: u64) -> Option<Token> { |
| 37 | + if let Ok(mut f) = fs::File::open(&self.path(scope_hash)) { |
| 38 | + let mut json_string = String::new(); |
| 39 | + if let Ok(_) = f.read_to_string(&mut json_string) { |
| 40 | + if let Ok(token) = json::decode::<Token>(&json_string) { |
| 41 | + return Some(token) |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | + None |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | + |
14 | 50 | #[derive(Debug)] |
15 | 51 | pub enum ApplicationSecretError { |
16 | 52 | DecoderError((String, json::DecoderError)), |
|
0 commit comments