use std::sync::Arc;
use axum::extract::{Request, State};
use axum::http::header::{AUTHORIZATION, WWW_AUTHENTICATE};
use axum::http::HeaderValue;
use axum::middleware::Next;
use axum::response::{IntoResponse, Response};
use seiva_identity::{Authenticator, Principal};
use crate::problem::Problem;
use crate::request_id::RequestIdExt;
pub async fn authn(
State(authenticator): State<Arc<dyn Authenticator>>,
mut request: Request,
next: Next,
) -> Response {
let presented = request
.headers()
.get(AUTHORIZATION)
.and_then(|value| value.to_str().ok())
.map(str::to_owned);
let Some(header) = presented else {
request.extensions_mut().insert(Principal::anonymous());
return next.run(request).await;
};
let bearer = header
.strip_prefix("Bearer ")
.or_else(|| header.strip_prefix("bearer "))
.unwrap_or("")
.trim();
match authenticator.authenticate(bearer) {
Ok(principal) => {
request.extensions_mut().insert(principal);
next.run(request).await
}
Err(_) => {
let request_id = request.extensions().request_id();
let mut response = Problem::unauthorized("the bearer token did not authenticate")
.with_instance(request.uri().path().to_owned())
.with_request_id_opt(request_id)
.into_response();
response
.headers_mut()
.insert(WWW_AUTHENTICATE, HeaderValue::from_static("Bearer"));
response
}
}
}