genius-core-client 0.4.0

Genius Core Client Library. Written in Rust and using PyO3 for Python bindings.
Documentation
use tonic::metadata::{AsciiMetadataValue, KeyAndValueRef, MetadataMap};
use tonic::{Request, Status};

pub struct AuthInterceptor {
    pub(crate) token: String,
}
impl tonic::service::Interceptor for AuthInterceptor {
    fn call(&mut self, request: Request<()>) -> Result<Request<()>, Status> {
        let token_value: AsciiMetadataValue =
            format!("Bearer {}", self.token).try_into().map_err(|e| {
                Status::new(
                    tonic::Code::Internal,
                    format!("Failed to convert token to AsciiMetadataValue: {}", e),
                )
            })?;

        // we *must* copy here, as some requests have a MetadataMap of fixed size and we can't tell which ones
        let mut metadata = MetadataMap::new();
        for val in request.metadata().iter() {
            match val {
                KeyAndValueRef::Ascii(key, value) => {
                    metadata.insert(key, value.clone());
                }
                KeyAndValueRef::Binary(key, value) => {
                    metadata.insert_bin(key, value.clone());
                }
            }
        }
        metadata.insert("authorization", token_value);

        // reconstruct the request
        let (_, extensions, message) = request.into_parts();
        Ok(Request::from_parts(metadata, extensions, message))
    }
}