Skip to main content

actix_web_admin/
site.rs

1use crate::handlers;
2use crate::registry::{AdminRegistry, SharedRegistry};
3use crate::resource::{AdminPrefix, AdminTitle};
4use actix_web::web;
5use std::sync::Arc;
6
7/// Main entry point for configuring the admin site.
8pub struct AdminSite {
9    prefix: String,
10    title: String,
11}
12
13impl AdminSite {
14    /// Create a new admin site with the given URL prefix.
15    pub fn new(prefix: &str) -> Self {
16        let prefix = prefix.trim_start_matches('/');
17        Self {
18            prefix: format!("/{}", prefix),
19            title: "Admin".to_string(),
20        }
21    }
22
23    /// Set the title of the admin site.
24    pub fn title(mut self, t: &str) -> Self {
25        self.title = t.to_string();
26        self
27    }
28
29    /// Mount the admin site onto an Actix-Web application.
30    pub fn mount(self, cfg: &mut web::ServiceConfig, registry: AdminRegistry) {
31        let shared_registry: SharedRegistry = Arc::new(registry);
32        let prefix = self.prefix.clone();
33        let title = self.title.clone();
34
35        cfg.app_data(web::Data::new(shared_registry.clone()));
36        cfg.app_data(web::Data::new(AdminTitle(title)));
37        cfg.app_data(web::Data::new(AdminPrefix(prefix.clone())));
38
39        cfg.service(
40            web::scope(&prefix)
41                .route("", web::get().to(handlers::dashboard::index))
42                .route("/", web::get().to(handlers::dashboard::index))
43                .route("/login", web::get().to(handlers::auth::login_page))
44                .route("/login", web::post().to(handlers::auth::login))
45                .route("/logout", web::get().to(handlers::auth::logout))
46                .service(
47                    web::scope("/{slug}")
48                        .route("", web::get().to(handlers::resource::list))
49                        .route("/", web::get().to(handlers::resource::list))
50                        .route("/new", web::get().to(handlers::resource::new))
51                        .route("/new", web::post().to(handlers::resource::create))
52                        .route("/{id}", web::get().to(handlers::resource::edit))
53                        .route("/{id}", web::post().to(handlers::resource::update))
54                        .route("/{id}/delete", web::post().to(handlers::resource::delete)),
55                ),
56        );
57    }
58}