From 3dc9295a54e153383c0f598e6a1969e6c947f318 Mon Sep 17 00:00:00 2001 From: Kevin Butler Date: Thu, 5 Nov 2015 19:34:08 +0000 Subject: [PATCH] Allow custom encoded types for Part --- src/lib.rs | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index cb7a7a5..ee2a32a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -30,12 +30,16 @@ pub enum Algorithm { /// A part of the JWT: header and claims specifically /// Allows converting from/to struct with base64 pub trait Part { + type Encoded: AsRef; + fn from_base64>(encoded: B) -> Result where Self: Sized; - fn to_base64(&self) -> Result; + fn to_base64(&self) -> Result; } impl Part for T where T: Encodable + Decodable { - fn to_base64(&self) -> Result { + type Encoded = String; + + fn to_base64(&self) -> Result { let encoded = try!(json::encode(&self)); Ok(encoded.as_bytes().to_base64(base64::URL_SAFE)) } @@ -65,6 +69,8 @@ impl Header { } impl Part for Header { + type Encoded = &'static str; + fn from_base64>(encoded: B) -> Result where Self: Sized { let algoritm = match encoded.as_ref() { b"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9" => { Algorithm::HS256 }, @@ -76,14 +82,14 @@ impl Part for Header { Ok(Header::new(algoritm)) } - fn to_base64(&self) -> Result { + fn to_base64(&self) -> Result { let encoded = match self.alg { Algorithm::HS256 => { "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9" }, Algorithm::HS384 => { "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzM4NCJ9" }, Algorithm::HS512 => { "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9" }, }; - Ok(encoded.into()) + Ok(encoded) } } @@ -113,7 +119,7 @@ pub fn encode>(claims: &T, secret: B, algorithm: Algorit let encoded_header = try!(Header::new(algorithm).to_base64()); let encoded_claims = try!(claims.to_base64()); // seems to be a tiny bit faster than format!("{}.{}", x, y) - let payload = [encoded_header, encoded_claims].join("."); + let payload = [encoded_header, encoded_claims.as_ref()].join("."); let signature = sign(&*payload, secret.as_ref(), algorithm); Ok([payload, signature].join("."))