use crate::manager::Config;
use actix_web::Error;
use actix_web::body::MessageBody;
use actix_web::dev::{ServiceRequest, ServiceResponse};
use actix_web::middleware::Next;
use actix_web::web::Data;
pub async fn authentication_middleware(req: ServiceRequest, next: Next<impl MessageBody>) -> Result<ServiceResponse<impl MessageBody>, Error> {
if req.path() == "/shutdown" {
next.call(req).await
} else {
let config = req.app_data::<Data<Config>>().map(|c| c.get_ref().clone());
if let Some(config) = config {
if let Some(auth_header) = req.headers().get("Authorization") {
if auth_header.to_str().unwrap_or("") != config.api_key {
return Err(actix_web::error::ErrorUnauthorized("Invalid API Key"));
}
} else {
return Err(actix_web::error::ErrorUnauthorized("Missing API Key"));
}
}
next.call(req).await
}
}