use base64::{Engine, engine::general_purpose::URL_SAFE};
use std::fs::read_to_string;
use crate::error::TokenError;
pub use biscuit_auth::{Biscuit, PublicKey};
pub fn encode_token(token_bytes: &[u8]) -> String {
URL_SAFE.encode(token_bytes)
}
pub fn decode_token(token_string: &str) -> Result<Vec<u8>, TokenError> {
URL_SAFE
.decode(token_string)
.map_err(|e| TokenError::generic(format!("Failed to decode base64 token: {e}")))
}
pub fn public_key_from_pem_file(path: &str) -> Result<PublicKey, TokenError> {
let key_string = read_to_string(path)
.map_err(|e| TokenError::generic(format!("Failed to read file: {e}")))?;
let key = PublicKey::from_pem(&key_string)
.map_err(|e| TokenError::generic(format!("Failed to parse PEM: {e}")))?;
Ok(key)
}
pub fn parse_token(token_string: &str, public_key: PublicKey) -> Result<Biscuit, TokenError> {
Ok(Biscuit::from_base64(token_string, public_key)?)
}