Derive or impl Encodable and Decodable for tokens

This commit is contained in:
Curtis McEnroe 2015-12-24 16:15:18 -05:00
parent cce6471a93
commit f2fed3726d
3 changed files with 40 additions and 3 deletions

View File

@ -7,7 +7,7 @@ use client::response::{FromResponse, ParseError, JsonHelper};
/// The bearer token type. /// The bearer token type.
/// ///
/// See [RFC 6750](http://tools.ietf.org/html/rfc6750). /// See [RFC 6750](http://tools.ietf.org/html/rfc6750).
#[derive(Debug, PartialEq, Eq)] #[derive(Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
pub struct Bearer<L: Lifetime> { pub struct Bearer<L: Lifetime> {
access_token: String, access_token: String,
scope: Option<String>, scope: Option<String>,

View File

@ -1,5 +1,6 @@
use chrono::{DateTime, UTC, Duration}; use chrono::{DateTime, UTC, Duration, TimeZone};
use rustc_serialize::json::Json; use rustc_serialize::json::Json;
use rustc_serialize::{Encodable, Encoder, Decodable, Decoder};
use super::Lifetime; use super::Lifetime;
use client::response::{FromResponse, ParseError, JsonHelper}; 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<Expiring> for Serializable {
fn into(self) -> Expiring {
Expiring {
refresh_token: self.refresh_token,
expires: UTC.timestamp(self.expires, 0),
}
}
}
impl Encodable for Expiring {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
Serializable::from(self).encode(s)
}
}
impl Decodable for Expiring {
fn decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error> {
Serializable::decode(d).map(Into::into)
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use chrono::{UTC, Duration}; use chrono::{UTC, Duration};

View File

@ -4,7 +4,7 @@ use super::Lifetime;
use client::response::{FromResponse, ParseError, JsonHelper}; use client::response::{FromResponse, ParseError, JsonHelper};
/// A static, non-expiring token. /// A static, non-expiring token.
#[derive(Debug, PartialEq, Eq)] #[derive(Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
pub struct Static; pub struct Static;
impl Lifetime for Static { impl Lifetime for Static {