use std::cell::Cell;
use crate::config::Env;
use crate::context::Context;
use crate::error::Error;
use crate::handler::BoxFuture;
use crate::middleware::{Middleware, Next};
use crate::response::{IntoResponse, Response};
tokio::task_local! {
static AUTHORIZED: Cell<bool>;
}
pub(crate) fn mark() {
let _ = AUTHORIZED.try_with(|authorized| authorized.set(true));
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Decision {
Allow,
Deny {
status: http::StatusCode,
message: Option<String>,
},
}
impl Decision {
#[track_caller]
pub fn deny(status: impl crate::response::IntoStatus, message: Option<&str>) -> Self {
Self::Deny {
status: status.into_status(),
message: message.map(str::to_owned),
}
}
pub fn is_allowed(&self) -> bool {
matches!(self, Self::Allow)
}
}
impl From<bool> for Decision {
fn from(allowed: bool) -> Self {
if allowed {
Self::Allow
} else {
Self::Deny {
status: http::StatusCode::FORBIDDEN,
message: None,
}
}
}
}
pub fn skip_authorization() {
mark();
}
pub struct VerifyAuthorized;
impl Middleware for VerifyAuthorized {
fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response> {
let route = format!("{} {}", ctx.method(), ctx.path());
Box::pin(AUTHORIZED.scope(Cell::new(false), async move {
let response = next.run(ctx).await;
let authorized = AUTHORIZED.with(Cell::get);
if authorized || response.status().is_client_error() || response.status().is_server_error() {
return response;
}
let message = format!(
"{route} answered without authorizing: call `authorize` (or `skip_authorization` for a public action)"
);
tracing::error!(target: "glacier", "{message}");
if Env::current().is_production() {
response
} else {
Error::internal(message).into_response()
}
}))
}
}