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;
|
2017-02-22 02:45:28 -05:00
|
|
|
|
2019-11-11 14:16:34 -05:00
|
|
|
pub(crate) fn b64_encode(input: &[u8]) -> String {
|
2019-11-08 14:00:19 -05:00
|
|
|
base64::encode_config(input, base64::URL_SAFE_NO_PAD)
|
|
|
|
}
|
|
|
|
|
2019-11-11 14:16:34 -05:00
|
|
|
pub(crate) fn b64_decode(input: &str) -> Result<Vec<u8>> {
|
2019-11-08 14:00:19 -05:00
|
|
|
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-11 14:16:34 -05:00
|
|
|
pub(crate) fn b64_encode_part<T: Serialize>(input: &T) -> Result<String> {
|
2019-11-03 11:13:22 -05:00
|
|
|
let json = to_string(input)?;
|
2019-11-11 14:16:34 -05:00
|
|
|
Ok(b64_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-11 14:16:34 -05:00
|
|
|
let s = String::from_utf8(b64_decode(encoded.as_ref())?)?;
|
2017-04-11 01:41:44 -04:00
|
|
|
|
|
|
|
let claims: T = from_str(&s)?;
|
2019-11-09 06:42:40 -05:00
|
|
|
let validation_map: Map<_, _> = from_str(&s)?;
|
|
|
|
Ok((claims, validation_map))
|
2017-02-22 02:45:28 -05:00
|
|
|
}
|