2021-09-28 12:16:51 -04:00
|
|
|
use serde::{Deserialize, Serialize};
|
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
|
|
|
|
2021-03-05 03:10:03 -05:00
|
|
|
pub(crate) fn b64_encode<T: AsRef<[u8]>>(input: T) -> String {
|
2019-11-08 14:00:19 -05:00
|
|
|
base64::encode_config(input, base64::URL_SAFE_NO_PAD)
|
|
|
|
}
|
|
|
|
|
2021-03-05 03:10:03 -05:00
|
|
|
pub(crate) fn b64_decode<T: AsRef<[u8]>>(input: T) -> 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> {
|
2021-09-28 12:16:51 -04:00
|
|
|
let json = serde_json::to_vec(input)?;
|
2021-03-05 03:10:03 -05:00
|
|
|
Ok(b64_encode(json))
|
2017-04-11 01:41:44 -04:00
|
|
|
}
|
|
|
|
|
2021-09-28 12:16:51 -04:00
|
|
|
/// This is used to decode from base64 then deserialize from JSON to several structs:
|
|
|
|
/// - The user-provided struct
|
|
|
|
/// - The ClaimsForValidation struct from this crate to run validation on
|
|
|
|
pub(crate) struct DecodedJwtPartClaims {
|
|
|
|
b64_decoded: Vec<u8>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl DecodedJwtPartClaims {
|
|
|
|
pub fn from_jwt_part_claims(encoded_jwt_part_claims: impl AsRef<[u8]>) -> Result<Self> {
|
|
|
|
Ok(Self { b64_decoded: b64_decode(encoded_jwt_part_claims)? })
|
|
|
|
}
|
2017-04-11 01:41:44 -04:00
|
|
|
|
2021-09-28 12:16:51 -04:00
|
|
|
pub fn deserialize<'a, T: Deserialize<'a>>(&'a self) -> Result<T> {
|
|
|
|
Ok(serde_json::from_slice(&self.b64_decoded)?)
|
|
|
|
}
|
2017-02-22 02:45:28 -05:00
|
|
|
}
|