use tonic::service::Interceptor;
use tonic::Status;
use super::GarrisonGrpcInterceptor;
impl GarrisonGrpcInterceptor {
pub fn new() -> Self {
Self
}
#[allow(clippy::result_large_err)]
pub fn extract_token(metadata: &tonic::metadata::MetadataMap) -> Result<String, Status> {
let auth_header = metadata
.get("authorization")
.ok_or_else(|| Status::unauthenticated("missing Authorization metadata"))?
.to_str()
.map_err(|_| Status::unauthenticated("Authorization metadata is not valid UTF-8"))?;
let token = auth_header
.strip_prefix("Bearer ")
.or_else(|| auth_header.strip_prefix("bearer "))
.or_else(|| auth_header.strip_prefix("BEARER "))
.ok_or_else(|| Status::unauthenticated("Authorization scheme must be Bearer"))?;
if token.is_empty() {
return Err(Status::unauthenticated("empty token after Bearer prefix"));
}
Ok(token.to_string())
}
}
impl Interceptor for GarrisonGrpcInterceptor {
#[allow(clippy::result_large_err)]
fn call(&mut self, request: tonic::Request<()>) -> Result<tonic::Request<()>, Status> {
let _token = Self::extract_token(request.metadata())?;
Ok(request)
}
}