use tonic::service::Interceptor;
use tonic::{Request, Status};
use crate::token::TokenManager;
#[derive(Clone)]
pub struct AuthInterceptor {
token_manager: std::sync::Arc<TokenManager>,
tenant_id: uuid::Uuid,
}
impl AuthInterceptor {
pub fn new(token_manager: std::sync::Arc<TokenManager>, tenant_id: uuid::Uuid) -> Self {
Self {
token_manager,
tenant_id,
}
}
}
impl Interceptor for AuthInterceptor {
fn call(&mut self, mut req: Request<()>) -> Result<Request<()>, Status> {
let token = self
.token_manager
.cached_access_token()
.ok_or_else(|| Status::unauthenticated("no cached access token"))?;
let auth_value = format!("Bearer {}", token.expose())
.parse()
.map_err(|_| Status::internal("failed to construct authorization metadata"))?;
req.metadata_mut().insert("authorization", auth_value);
let tenant_value = self
.tenant_id
.to_string()
.parse()
.map_err(|_| Status::internal("failed to construct x-tenant-id metadata"))?;
req.metadata_mut().insert("x-tenant-id", tenant_value);
Ok(req)
}
}