laravel-rust-admin 0.1.1

Admin panel framework for Laravel for Rust: auto-generated CRUD tables, forms, actions, and dashboard widgets from your models.
Documentation
//! Middleware that decides who may reach the panel at all.

use laravel::http::{Middleware, Next, Request, Response, StatusCode};

use crate::panel::PanelGate;

/// Runs the gate given to [`AdminPanel::authorize`](crate::AdminPanel::authorize) before every
/// panel route, and answers `403` when it returns `false`.
#[derive(Clone)]
pub(crate) struct AuthorizePanel {
    gate: PanelGate,
}

impl AuthorizePanel {
    pub(crate) fn new(gate: PanelGate) -> Self {
        Self { gate }
    }
}

impl Middleware for AuthorizePanel {
    async fn handle(&self, request: Request, next: Next) -> laravel::Result<Response> {
        let allowed = (self.gate)(&request).await?;
        if !allowed {
            return Err(laravel::abort_with(
                StatusCode::FORBIDDEN,
                "You do not have access to this admin panel.",
            ));
        }
        Ok(next.run(request).await)
    }
}

/// What a visitor is told when the panel is [locked](LockedPanel).
pub(crate) const LOCKED_MESSAGE: &str = "This admin panel has no access control configured, so it only opens in the `local` and \
     `testing` environments. Add `AdminPanel::authorize(..)` or `AdminPanel::middleware(..)`.";

/// Answers every panel route with a `403`.
///
/// A panel with neither a gate nor middleware would otherwise be open to anyone who finds its
/// URL. The provider adds this middleware to such a panel outside the `local` and `testing`
/// environments, so forgetting to protect the panel can't expose it in production.
#[derive(Clone, Copy)]
pub(crate) struct LockedPanel;

impl Middleware for LockedPanel {
    async fn handle(&self, _request: Request, _next: Next) -> laravel::Result<Response> {
        Err(laravel::abort_with(StatusCode::FORBIDDEN, LOCKED_MESSAGE))
    }
}