Weaken parameter requirements for encode

This commit is contained in:
Kevin Butler 2015-11-05 17:10:55 +00:00
parent b1c10c7085
commit 09c4d14609
3 changed files with 10 additions and 12 deletions

View File

@ -13,14 +13,12 @@ struct Claims {
#[bench]
fn bench_encode(b: &mut test::Bencher) {
b.iter(|| encode::<Claims>(
Claims {
sub: "b@b.com".to_owned(),
company: "ACME".to_owned()
},
"secret".to_owned(),
Algorithm::HS256
));
let claim = Claims {
sub: "b@b.com".to_owned(),
company: "ACME".to_owned()
};
b.iter(|| encode(&claim, "secret", Algorithm::HS256));
}
#[bench]

View File

@ -16,7 +16,7 @@ fn main() {
company: "ACME".to_owned()
};
let key = "secret";
let token = match encode::<Claims>(my_claims, key.to_owned(), Algorithm::HS256) {
let token = match encode(&my_claims, key, Algorithm::HS256) {
Ok(t) => t,
Err(_) => panic!() // in practice you would return the error
};

View File

@ -85,12 +85,12 @@ fn verify(signature: &str, data: &str, secret: &[u8], algorithm: Algorithm) -> b
}
/// Encode the claims passed and sign the payload using the algorithm and the secret
pub fn encode<T: Part>(claims: T, secret: String, algorithm: Algorithm) -> Result<String, Error> {
pub fn encode<T: Part, B: AsRef<[u8]>>(claims: &T, secret: B, algorithm: Algorithm) -> Result<String, Error> {
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 signature = sign(&*payload, secret.as_bytes(), algorithm);
let signature = sign(&*payload, secret.as_ref(), algorithm);
Ok([payload, signature].join("."))
}
@ -177,7 +177,7 @@ mod tests {
sub: "b@b.com".to_owned(),
company: "ACME".to_owned()
};
let token = encode::<Claims>(my_claims.clone(), "secret".to_owned(), Algorithm::HS256).unwrap();
let token = encode(&my_claims, "secret", Algorithm::HS256).unwrap();
let claims = decode::<Claims>(token.to_owned(), "secret".to_owned(), Algorithm::HS256).unwrap();
assert_eq!(my_claims, claims);
}