Skip to main content

brainos_httpadapter/
auth.rs

1//! Authentication middleware helpers for HTTP routes.
2
3use axum::http::{HeaderMap, StatusCode};
4
5use crate::state::AppState;
6
7/// Extract the raw key from `Authorization: Bearer <key>`.
8pub fn extract_bearer(headers: &HeaderMap) -> Option<&str> {
9    headers
10        .get("authorization")
11        .and_then(|v| v.to_str().ok())
12        .and_then(brain_core::auth::extract_bearer_from_value)
13}
14
15/// Check that the request carries a valid key with the given permission.
16/// Returns `Err((StatusCode::UNAUTHORIZED, message))` on failure.
17pub fn check_auth(
18    state: &AppState,
19    headers: &HeaderMap,
20    permission: &str,
21) -> Result<(), (StatusCode, String)> {
22    let provided_key = extract_bearer(headers);
23    let result = brain_core::check_auth(&state.api_keys, provided_key, permission);
24    if result.is_allowed() {
25        Ok(())
26    } else {
27        Err((
28            StatusCode::UNAUTHORIZED,
29            result
30                .error_message(permission)
31                .unwrap_or_else(|| "Unauthorized".to_string()),
32        ))
33    }
34}