2017-04-22 01:21:04 -04:00
|
|
|
use serde::de::DeserializeOwned;
|
2017-02-22 02:45:28 -05:00
|
|
|
use serde::ser::Serialize;
|
2017-04-11 01:41:44 -04:00
|
|
|
use serde_json::map::Map;
|
2018-10-28 14:58:35 -04:00
|
|
|
use serde_json::{from_str, to_string, Value};
|
2017-02-22 02:45:28 -05:00
|
|
|
|
2019-07-06 14:36:32 -04:00
|
|
|
use crate::errors::Result;
|
|
|
|
use crate::header::Header;
|
2017-02-22 02:45:28 -05:00
|
|
|
|
2017-04-12 21:08:07 -04:00
|
|
|
/// The return type of a successful call to decode
|
2017-02-22 02:45:28 -05:00
|
|
|
#[derive(Debug)]
|
2017-04-22 01:41:25 -04:00
|
|
|
pub struct TokenData<T> {
|
2017-07-02 17:49:14 -04:00
|
|
|
/// The decoded JWT header
|
2017-02-22 02:45:28 -05:00
|
|
|
pub header: Header,
|
2017-07-02 17:49:14 -04:00
|
|
|
/// The decoded JWT claims
|
2018-10-28 14:58:35 -04:00
|
|
|
pub claims: T,
|
2017-02-22 02:45:28 -05:00
|
|
|
}
|
|
|
|
|
2019-11-08 14:00:19 -05:00
|
|
|
pub(crate) fn encode(input: &[u8]) -> String {
|
|
|
|
base64::encode_config(input, base64::URL_SAFE_NO_PAD)
|
|
|
|
}
|
|
|
|
|
|
|
|
pub(crate) fn decode(input: &str) -> Result<Vec<u8>> {
|
|
|
|
base64::decode_config(input, base64::URL_SAFE_NO_PAD).map_err(|e| e.into())
|
|
|
|
}
|
|
|
|
|
2019-11-03 11:13:22 -05:00
|
|
|
/// Serializes a struct to JSON and encodes it in base64
|
2019-11-08 14:00:19 -05:00
|
|
|
pub(crate) fn encode_part<T: Serialize>(input: &T) -> Result<String> {
|
2019-11-03 11:13:22 -05:00
|
|
|
let json = to_string(input)?;
|
2019-11-08 14:00:19 -05:00
|
|
|
Ok(encode(json.as_bytes()))
|
2017-04-11 01:41:44 -04:00
|
|
|
}
|
|
|
|
|
2019-11-06 17:32:13 -05:00
|
|
|
/// Decodes from base64 and deserializes from JSON to a struct AND a hashmap of Value so we can
|
|
|
|
/// run validation on it
|
2019-11-08 14:00:19 -05:00
|
|
|
pub(crate) fn from_jwt_part_claims<B: AsRef<str>, T: DeserializeOwned>(
|
2018-10-28 14:58:35 -04:00
|
|
|
encoded: B,
|
|
|
|
) -> Result<(T, Map<String, Value>)> {
|
2019-11-08 14:00:19 -05:00
|
|
|
let s = String::from_utf8(decode(encoded.as_ref())?)?;
|
2017-04-11 01:41:44 -04:00
|
|
|
|
|
|
|
let claims: T = from_str(&s)?;
|
2018-10-28 14:58:35 -04:00
|
|
|
let map: Map<_, _> = from_str(&s)?;
|
2017-04-11 01:41:44 -04:00
|
|
|
Ok((claims, map))
|
2017-02-22 02:45:28 -05:00
|
|
|
}
|