Skip to main content

laravel_rust_admin/
panel.rs

1//! `AdminPanel` builder and `laravel::foundation::ServiceProvider` integration.
2
3use std::collections::HashMap;
4use std::future::Future;
5use std::marker::PhantomData;
6use std::str::FromStr;
7use std::sync::Arc;
8
9use futures_util::future::BoxFuture;
10use laravel::config::app::Environment;
11use laravel::config::{Config, Env};
12use laravel::container::{Container, Registrar};
13use laravel::foundation::ServiceProvider;
14use laravel::http::{IntoMiddleware, MiddlewareGroup, Request};
15use laravel::model::Model;
16use serde::Serialize;
17
18use crate::config::{AccentColor, AdminConfig};
19use crate::http::{AuthorizePanel, LOCKED_MESSAGE, LockedPanel, register_routes};
20use crate::protocol::{AdminUserDto, BadgeColor, DashboardWidgetDto, ShellBootstrap};
21use crate::resource::{AdminResource, ErasedResource, ResourceAdapter};
22use crate::widget::{DashboardWidget, ErasedWidget, FnWidget, RequestWidget, StatWidget};
23
24/// Signed-in user details displayed in the admin sidebar footer and dashboard greeting.
25#[derive(Debug, Clone)]
26pub struct AdminUser {
27    /// The name shown in the sidebar, and greeted on the dashboard.
28    pub name: String,
29    /// The address shown under the name in the user menu.
30    pub email: Option<String>,
31    /// The URL of a picture to show instead of the user's initials.
32    pub avatar_url: Option<String>,
33    /// What the user is to the application, such as `Owner`. The user menu shows it when there's no email.
34    pub role: Option<String>,
35}
36
37impl AdminUser {
38    /// A user with a name, and nothing else yet.
39    #[must_use]
40    pub fn new(name: impl Into<String>) -> Self {
41        Self {
42            name: name.into(),
43            email: None,
44            avatar_url: None,
45            role: None,
46        }
47    }
48
49    /// Sets the email address shown in the user menu.
50    #[must_use]
51    pub fn email(mut self, email: impl Into<String>) -> Self {
52        self.email = Some(email.into());
53        self
54    }
55
56    /// Sets the URL of the user's picture.
57    #[must_use]
58    pub fn avatar_url(mut self, url: impl Into<String>) -> Self {
59        self.avatar_url = Some(url.into());
60        self
61    }
62
63    /// Sets the user's role, such as `Owner`.
64    #[must_use]
65    pub fn role(mut self, role: impl Into<String>) -> Self {
66        self.role = Some(role.into());
67        self
68    }
69
70    pub(crate) fn into_dto(self) -> AdminUserDto {
71        AdminUserDto {
72            name: self.name,
73            email: self.email,
74            avatar_url: self.avatar_url,
75            role: self.role,
76        }
77    }
78}
79
80/// An async function of the request, which is how the panel asks your application who may enter,
81/// and who the current user is.
82///
83/// Every `async fn` that takes a `&Request` and returns a `laravel::Result<T>` implements this
84/// trait, so write one and pass its name:
85///
86/// ```ignore
87/// async fn admins_only(request: &Request) -> laravel::Result<bool> {
88///     Ok(request.user::<User>().await?.is_some_and(|user| user.is_admin))
89/// }
90///
91/// AdminPanel::new().authorize(admins_only)
92/// ```
93///
94/// A closure works too when it names its argument's type and returns a boxed future, such as
95/// `|_request: &Request| Box::pin(async { Ok(true) })`.
96pub trait RequestFn<'a, T>: Send + Sync + 'static {
97    /// The future the function returns.
98    type Future: Future<Output = laravel::Result<T>> + Send + 'a;
99
100    /// Calls the function with the request.
101    fn call(&self, request: &'a Request) -> Self::Future;
102}
103
104impl<'a, T, F, Fut> RequestFn<'a, T> for F
105where
106    F: Fn(&'a Request) -> Fut + Send + Sync + 'static,
107    Fut: Future<Output = laravel::Result<T>> + Send + 'a,
108{
109    type Future = Fut;
110
111    fn call(&self, request: &'a Request) -> Fut {
112        self(request)
113    }
114}
115
116/// A [`RequestFn`] behind a pointer, which the panel can keep and call.
117pub(crate) type RequestHook<T> = Arc<dyn for<'a> Fn(&'a Request) -> BoxFuture<'a, laravel::Result<T>> + Send + Sync>;
118
119fn hook<T: 'static>(function: impl for<'a> RequestFn<'a, T>) -> RequestHook<T> {
120    Arc::new(move |request| Box::pin(function.call(request)))
121}
122
123pub(crate) type PanelGate = RequestHook<bool>;
124
125pub(crate) type UserResolver = RequestHook<Option<AdminUser>>;
126
127/// Runtime state registered in Laravel's service container as a singleton.
128#[derive(Clone)]
129pub struct PanelState {
130    pub(crate) base_path: String,
131    pub(crate) brand: String,
132    pub(crate) subtitle: Option<String>,
133    pub(crate) accent: AccentColor,
134    pub(crate) logout_url: Option<String>,
135    pub(crate) vite_dev_url: Option<String>,
136    pub(crate) resources: Arc<Vec<Arc<dyn ErasedResource>>>,
137    pub(crate) resource_index: Arc<HashMap<String, usize>>,
138    pub(crate) widgets: Arc<Vec<Arc<dyn ErasedWidget>>>,
139    pub(crate) user_resolver: Option<UserResolver>,
140}
141
142impl std::fmt::Debug for PanelState {
143    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
144        f.debug_struct("PanelState")
145            .field("base_path", &self.base_path)
146            .field("brand", &self.brand)
147            .field("resources", &self.resources.len())
148            .field("widgets", &self.widgets.len())
149            .finish_non_exhaustive()
150    }
151}
152
153impl PanelState {
154    pub(crate) fn find_resource(&self, slug: &str) -> Option<&Arc<dyn ErasedResource>> {
155        let index = *self.resource_index.get(slug)?;
156        self.resources.get(index)
157    }
158
159    pub(crate) fn bootstrap(&self) -> ShellBootstrap {
160        ShellBootstrap {
161            base_path: self.base_path.clone(),
162            api_base: format!("{}/api", self.base_path),
163            brand: self.brand.clone(),
164            subtitle: self.subtitle.clone(),
165            accent: self.accent,
166            logout_url: self.logout_url.clone(),
167        }
168    }
169
170    pub(crate) async fn resolve_user(&self, request: &Request) -> laravel::Result<Option<AdminUserDto>> {
171        let Some(resolver) = &self.user_resolver else {
172            return Ok(None);
173        };
174        Ok(resolver(request).await?.map(AdminUser::into_dto))
175    }
176
177    pub(crate) async fn resolve_dashboard_widgets(
178        &self,
179        request: &Request,
180    ) -> laravel::Result<Vec<DashboardWidgetDto>> {
181        if !self.widgets.is_empty() {
182            let mut resolved = Vec::with_capacity(self.widgets.len());
183            for widget in self.widgets.iter() {
184                resolved.push(widget.resolve(request).await?);
185            }
186            return Ok(resolved);
187        }
188
189        // A panel without widgets of its own shows how many records each resource has.
190        let mut resolved = Vec::with_capacity(self.resources.len());
191        for resource in self.resources.iter() {
192            let count = resource.total_count(request).await?;
193            let slug = resource.slug();
194            resolved.push(
195                StatWidget::new(
196                    format!("resource_count_{slug}"),
197                    resource.plural_label(),
198                    format_number(count),
199                )
200                .description(format!("Total {} in database", resource.plural_label().to_lowercase()))
201                .icon(resource.icon())
202                .color(BadgeColor::Zinc)
203                .href(format!("{}/resources/{slug}", self.base_path))
204                .build(),
205            );
206        }
207        Ok(resolved)
208    }
209}
210
211/// Fluent builder for configuring and mounting an admin panel as a Laravel `ServiceProvider`.
212///
213/// ```no_run
214/// use laravel::Application;
215/// use laravel_rust_admin::AdminPanel;
216///
217/// let admin = AdminPanel::new()
218///     .path("/admin")
219///     .brand("Acme Console");
220///
221/// Application::configure()
222///     .with_providers(|providers| {
223///         providers.add(admin);
224///     });
225/// ```
226pub struct AdminPanel {
227    path: Option<String>,
228    brand: Option<String>,
229    subtitle: Option<String>,
230    accent: AccentColor,
231    logout_url: Option<String>,
232    vite_dev_url: Option<String>,
233    middleware: MiddlewareGroup,
234    /// Whether the application attached middleware of its own, such as `Authenticate`.
235    has_middleware: bool,
236    resources: Vec<Arc<dyn ErasedResource>>,
237    widgets: Vec<Arc<dyn ErasedWidget>>,
238    gate: Option<PanelGate>,
239    user_resolver: Option<UserResolver>,
240}
241
242impl std::fmt::Debug for AdminPanel {
243    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
244        f.debug_struct("AdminPanel")
245            .field("path", &self.path)
246            .field("brand", &self.brand)
247            .field("accent", &self.accent)
248            .field("resources", &self.resources.len())
249            .field("widgets", &self.widgets.len())
250            .finish_non_exhaustive()
251    }
252}
253
254impl Default for AdminPanel {
255    fn default() -> Self {
256        Self::new()
257    }
258}
259
260impl AdminPanel {
261    /// Create a new admin panel mounted at `/admin` by default.
262    #[must_use]
263    pub fn new() -> Self {
264        Self {
265            path: None,
266            brand: None,
267            subtitle: None,
268            accent: AccentColor::Zinc,
269            logout_url: None,
270            vite_dev_url: None,
271            middleware: MiddlewareGroup::new(),
272            has_middleware: false,
273            resources: Vec::new(),
274            widgets: Vec::new(),
275            gate: None,
276            user_resolver: None,
277        }
278    }
279
280    /// Set the URL prefix where the panel is mounted (e.g. `"/admin"` or `"/ops"`).
281    #[must_use]
282    pub fn path(mut self, path: impl Into<String>) -> Self {
283        self.path = Some(normalize_path(&path.into()));
284        self
285    }
286
287    /// Set the brand title displayed in the sidebar header and browser tab.
288    #[must_use]
289    pub fn brand(mut self, brand: impl Into<String>) -> Self {
290        self.brand = Some(brand.into());
291        self
292    }
293
294    /// Optional subtitle shown beneath the brand name (e.g. `"Production"` or `"Workspace"`).
295    #[must_use]
296    pub fn subtitle(mut self, subtitle: impl Into<String>) -> Self {
297        self.subtitle = Some(subtitle.into());
298        self
299    }
300
301    /// Sets the color of the panel's primary buttons, checked controls, and brand mark.
302    #[must_use]
303    pub fn accent(mut self, accent: AccentColor) -> Self {
304        self.accent = accent;
305        self
306    }
307
308    /// Optional logout URL rendered in the sidebar user profile dropdown.
309    #[must_use]
310    pub fn logout_url(mut self, url: impl Into<String>) -> Self {
311        self.logout_url = Some(url.into());
312        self
313    }
314
315    /// Optional Vite dev server URL (e.g. `"http://localhost:5173"`) for hot-reloading UI work.
316    #[must_use]
317    pub fn vite_dev_url(mut self, url: impl Into<String>) -> Self {
318        self.vite_dev_url = Some(url.into().trim_end_matches('/').to_owned());
319        self
320    }
321
322    /// Attach Laravel middleware (such as `laravel::auth::Authenticate`) to all admin routes.
323    ///
324    /// A panel with neither middleware nor an [`authorize`](Self::authorize) gate is open to
325    /// everyone, so it only answers in the `local` and `testing` environments. Everywhere else
326    /// it responds with a `403` until you add one of the two.
327    #[must_use]
328    pub fn middleware(mut self, middleware: impl IntoMiddleware) -> Self {
329        self.middleware.append(middleware);
330        self.has_middleware = true;
331        self
332    }
333
334    /// Decide who may use the panel, with a gate that runs before every panel request.
335    ///
336    /// Returning `Ok(false)` rejects the request with `403 Forbidden`. The gate runs after the
337    /// panel's [`middleware`](Self::middleware), so it can read the user that `Authenticate`
338    /// loaded:
339    ///
340    /// ```ignore
341    /// async fn admins_only(request: &Request) -> laravel::Result<bool> {
342    ///     Ok(request.user::<User>().await?.is_some_and(|user| user.is_admin))
343    /// }
344    ///
345    /// AdminPanel::new()
346    ///     .middleware(laravel::auth::Authenticate)
347    ///     .authorize(admins_only)
348    /// ```
349    #[must_use]
350    pub fn authorize(mut self, gate: impl for<'a> RequestFn<'a, bool>) -> Self {
351        self.gate = Some(hook(gate));
352        self
353    }
354
355    /// Tell the panel who is using it, for the user menu in the sidebar and the greeting on the
356    /// dashboard. Return `None` when there is no one to show.
357    ///
358    /// ```ignore
359    /// async fn current_user(request: &Request) -> laravel::Result<Option<AdminUser>> {
360    ///     let user = request.user::<User>().await?;
361    ///     Ok(user.map(|user| AdminUser::new(user.name).email(user.email)))
362    /// }
363    ///
364    /// AdminPanel::new().user_resolver(current_user)
365    /// ```
366    #[must_use]
367    pub fn user_resolver(mut self, resolver: impl for<'a> RequestFn<'a, Option<AdminUser>>) -> Self {
368        self.user_resolver = Some(hook(resolver));
369        self
370    }
371
372    /// Register an [`AdminResource`] with this panel.
373    #[must_use]
374    pub fn resource<R>(mut self) -> Self
375    where
376        R: AdminResource,
377        <R::Model as Model>::Key: FromStr,
378        R::Model: Serialize,
379    {
380        // Two resources at one URL would make the second unreachable without a word of warning.
381        assert!(
382            self.resources.iter().all(|resource| resource.slug() != R::slug()),
383            "two admin resources share the slug `{}`; give one of them a different `slug()`",
384            R::slug(),
385        );
386        self.resources.push(ResourceAdapter::<R>::erased());
387        self
388    }
389
390    /// Add a widget to the dashboard. Widgets appear in the order you add them.
391    ///
392    /// A panel without widgets shows a count of each resource's records instead.
393    #[must_use]
394    pub fn widget(mut self, widget: impl DashboardWidget) -> Self {
395        self.widgets.push(Arc::new(widget));
396        self
397    }
398
399    /// Add a dashboard widget that is an async function, which runs each time the dashboard
400    /// loads. It returns a [`StatWidget`], a [`ChartWidget`](crate::ChartWidget), or a
401    /// [`TableWidget`](crate::TableWidget):
402    ///
403    /// ```ignore
404    /// async fn open_orders() -> laravel::Result<StatWidget> {
405    ///     let count = Order::query().filter(Order::status.eq(OrderStatus::Pending)).count().await?;
406    ///     Ok(StatWidget::new("open_orders", "Open orders", count.to_string()))
407    /// }
408    ///
409    /// AdminPanel::new().widget_fn(open_orders)
410    /// ```
411    #[must_use]
412    pub fn widget_fn<F, Fut, W>(self, widget: F) -> Self
413    where
414        F: Fn() -> Fut + Send + Sync + 'static,
415        Fut: Future<Output = laravel::Result<W>> + Send + 'static,
416        W: Into<DashboardWidgetDto> + 'static,
417    {
418        self.widget(FnWidget(widget))
419    }
420
421    /// Add a dashboard widget that is an async function of the request, such as one that shows
422    /// the logged-in user's own numbers. Like [`authorize`](Self::authorize), it takes an
423    /// `async fn(&Request)`.
424    #[must_use]
425    pub fn widget_for_request<F, W>(self, widget: F) -> Self
426    where
427        F: for<'a> RequestFn<'a, W>,
428        W: Into<DashboardWidgetDto> + 'static,
429    {
430        self.widget(RequestWidget(widget, PhantomData))
431    }
432}
433
434impl ServiceProvider for AdminPanel {
435    fn config(&self, config: &mut Config, env: &Env) {
436        config.discover(env!("CARGO_CRATE_NAME"), env);
437    }
438
439    fn register(&self, app: &mut Registrar) {
440        let cfg = app.config().section::<AdminConfig>();
441        let base_path = normalize_path(self.path.as_deref().unwrap_or(&cfg.path));
442        let brand = self.brand.clone().unwrap_or_else(|| cfg.brand.clone());
443        let vite_dev_url = self
444            .vite_dev_url
445            .clone()
446            .or_else(|| cfg.vite_dev_url.clone())
447            .map(|url| url.trim_end_matches('/').to_owned());
448
449        let mut resources = self.resources.clone();
450        resources.sort_by_key(|r| r.navigation_sort());
451
452        let mut resource_index = HashMap::with_capacity(resources.len());
453        for (idx, resource) in resources.iter().enumerate() {
454            resource_index.insert(resource.slug().to_owned(), idx);
455        }
456
457        let state = PanelState {
458            base_path: base_path.clone(),
459            brand,
460            subtitle: self.subtitle.clone(),
461            accent: self.accent,
462            logout_url: self.logout_url.clone(),
463            vite_dev_url,
464            resources: Arc::new(resources),
465            resource_index: Arc::new(resource_index),
466            widgets: Arc::new(self.widgets.clone()),
467            user_resolver: self.user_resolver.clone(),
468        };
469
470        app.instance(state.clone());
471        app.routing().assets("laravel-rust-admin", laravel::embed!("dist"));
472
473        let mut middleware = self.middleware.clone();
474        if let Some(gate) = self.gate.clone() {
475            middleware.append(AuthorizePanel::new(gate));
476        }
477        if self.is_locked(&app.config().app.env) {
478            middleware.append(LockedPanel);
479        }
480
481        app.routing().web(move |router| {
482            register_routes(router, &base_path, middleware);
483        });
484    }
485
486    async fn boot(&self, app: &Container) -> laravel::Result<()> {
487        let environment = &app.config().app.env;
488        if self.is_locked(environment) {
489            tracing::warn!(
490                environment = environment.as_str(),
491                "laravel-rust-admin: {LOCKED_MESSAGE}"
492            );
493        }
494
495        Ok(())
496    }
497}
498
499impl AdminPanel {
500    /// Whether the panel refuses every request, because nothing decides who may use it and the
501    /// application isn't running on a developer's machine or in a test.
502    fn is_locked(&self, environment: &Environment) -> bool {
503        let unprotected = self.gate.is_none() && !self.has_middleware;
504        unprotected && !matches!(environment, Environment::Local | Environment::Testing)
505    }
506}
507
508fn normalize_path(raw: &str) -> String {
509    let trimmed = raw.trim().trim_matches('/');
510    if trimmed.is_empty() {
511        "/admin".to_owned()
512    } else {
513        format!("/{trimmed}")
514    }
515}
516
517fn format_number(n: u64) -> String {
518    let digits = n.to_string();
519    let mut out = String::with_capacity(digits.len() + digits.len() / 3);
520    for (idx, ch) in digits.chars().rev().enumerate() {
521        if idx > 0 && idx % 3 == 0 {
522            out.push(',');
523        }
524        out.push(ch);
525    }
526    out.chars().rev().collect()
527}