From f2fed3726df0fcf52610f76202f2816b633db427 Mon Sep 17 00:00:00 2001 From: Curtis McEnroe Date: Thu, 24 Dec 2015 16:15:18 -0500 Subject: [PATCH] Derive or impl Encodable and Decodable for tokens --- src/token/bearer.rs | 2 +- src/token/expiring.rs | 39 ++++++++++++++++++++++++++++++++++++++- src/token/statik.rs | 2 +- 3 files changed, 40 insertions(+), 3 deletions(-) diff --git a/src/token/bearer.rs b/src/token/bearer.rs index a001589..0ff675d 100644 --- a/src/token/bearer.rs +++ b/src/token/bearer.rs @@ -7,7 +7,7 @@ use client::response::{FromResponse, ParseError, JsonHelper}; /// The bearer token type. /// /// See [RFC 6750](http://tools.ietf.org/html/rfc6750). -#[derive(Debug, PartialEq, Eq)] +#[derive(Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)] pub struct Bearer { access_token: String, scope: Option, diff --git a/src/token/expiring.rs b/src/token/expiring.rs index d274ec6..f47d225 100644 --- a/src/token/expiring.rs +++ b/src/token/expiring.rs @@ -1,5 +1,6 @@ -use chrono::{DateTime, UTC, Duration}; +use chrono::{DateTime, UTC, Duration, TimeZone}; use rustc_serialize::json::Json; +use rustc_serialize::{Encodable, Encoder, Decodable, Decoder}; use super::Lifetime; use client::response::{FromResponse, ParseError, JsonHelper}; @@ -54,6 +55,42 @@ impl FromResponse for Expiring { } } +#[derive(RustcEncodable, RustcDecodable)] +struct Serializable { + refresh_token: String, + expires: i64, +} + +impl<'a> From<&'a Expiring> for Serializable { + fn from(expiring: &Expiring) -> Self { + Serializable { + refresh_token: expiring.refresh_token.clone(), + expires: expiring.expires.timestamp(), + } + } +} + +impl Into for Serializable { + fn into(self) -> Expiring { + Expiring { + refresh_token: self.refresh_token, + expires: UTC.timestamp(self.expires, 0), + } + } +} + +impl Encodable for Expiring { + fn encode(&self, s: &mut S) -> Result<(), S::Error> { + Serializable::from(self).encode(s) + } +} + +impl Decodable for Expiring { + fn decode(d: &mut D) -> Result { + Serializable::decode(d).map(Into::into) + } +} + #[cfg(test)] mod tests { use chrono::{UTC, Duration}; diff --git a/src/token/statik.rs b/src/token/statik.rs index ece2bac..d9ee569 100644 --- a/src/token/statik.rs +++ b/src/token/statik.rs @@ -4,7 +4,7 @@ use super::Lifetime; use client::response::{FromResponse, ParseError, JsonHelper}; /// A static, non-expiring token. -#[derive(Debug, PartialEq, Eq)] +#[derive(Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)] pub struct Static; impl Lifetime for Static {