Implement Encodable and Decodable for Token

This commit is contained in:
Curtis McEnroe 2015-11-29 15:36:12 -05:00
parent e89146a3fd
commit b5a56ff97e
1 changed files with 45 additions and 1 deletions

View File

@ -1,4 +1,5 @@
use chrono::{DateTime, UTC};
use chrono::{DateTime, UTC, TimeZone};
use rustc_serialize::{Encodable, Encoder, Decodable, Decoder};
/// OAuth 2.0 access token.
///
@ -29,3 +30,46 @@ impl Token {
self.expires.map_or(false, |dt| dt < UTC::now())
}
}
#[derive(RustcEncodable, RustcDecodable)]
struct SerializableToken {
access_token: String,
token_type: String,
expires: Option<i64>,
refresh_token: Option<String>,
scope: Option<String>,
}
impl SerializableToken {
fn from_token(token: &Token) -> Self {
SerializableToken {
access_token: token.access_token.clone(),
token_type: token.token_type.clone(),
expires: token.expires.as_ref().map(DateTime::timestamp),
refresh_token: token.refresh_token.clone(),
scope: token.scope.clone(),
}
}
fn into_token(self) -> Token {
Token {
access_token: self.access_token,
token_type: self.token_type,
expires: self.expires.map(|t| UTC.timestamp(t, 0)),
refresh_token: self.refresh_token,
scope: self.scope,
}
}
}
impl Encodable for Token {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
SerializableToken::from_token(self).encode(s)
}
}
impl Decodable for Token {
fn decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error> {
SerializableToken::decode(d).map(SerializableToken::into_token)
}
}