32 lines
871 B
Rust
32 lines
871 B
Rust
/// Auth middleware for sync endpoints.
|
|
///
|
|
/// Sync and swarm endpoints require `Authorization: Bearer {api_key}`.
|
|
/// The API key is configured at server startup and stored in AppState.
|
|
use axum::{
|
|
extract::{Request, State},
|
|
http::StatusCode,
|
|
middleware::Next,
|
|
response::Response,
|
|
};
|
|
use std::sync::Arc;
|
|
|
|
use crate::state::AppState;
|
|
|
|
/// Axum middleware that checks the Authorization header on sync/swarm routes.
|
|
pub async fn require_auth(
|
|
State(state): State<Arc<AppState>>,
|
|
req: Request,
|
|
next: Next,
|
|
) -> Result<Response, StatusCode> {
|
|
let api_key = req
|
|
.headers()
|
|
.get("Authorization")
|
|
.and_then(|v| v.to_str().ok())
|
|
.and_then(|v| v.strip_prefix("Bearer "));
|
|
|
|
match api_key {
|
|
Some(key) if key == state.api_key => Ok(next.run(req).await),
|
|
_ => Err(StatusCode::UNAUTHORIZED),
|
|
}
|
|
}
|