adminx-actix 3.1.2

Actix Web adapter for the adminx admin-panel framework. Translates Actix requests/responses to the neutral adminx-core types and mounts resource routes onto an Actix Scope.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
// adminx-actix/src/lib.rs
//
// Actix Web adapter. Translates the neutral `ApiResponse` into an
// `actix_web::HttpResponse`, extracts the auth cookie into a `ReqCtx`, and wires
// each registered resource's JSON API and HTML UI (plus login/logout) onto an
// Actix `Scope`. All behavior lives in `adminx_core`; this is translation only.

use std::collections::HashMap;
use std::sync::Arc;

use adminx_core::attach::UploadedFile;
use adminx_core::auth;
use adminx_core::csrf;
use adminx_core::registry::all_resources;
use adminx_core::request::ReqCtx;
use adminx_core::resource::Resource;
use adminx_core::response::{ApiBody, ApiResponse};
use adminx_core::storage::storage;
use adminx_core::ui;

use actix_multipart::Multipart;
use actix_web::http::header::{HeaderName, HeaderValue};
use actix_web::http::StatusCode;
use actix_web::{web, HttpRequest, HttpResponse, Scope};
use futures_util::StreamExt;
use serde::Deserialize;
use serde_json::{json, Value};

/// Prefix the adminx scope is mounted at. Used for building UI links.
const MOUNT: &str = "/adminx";

#[derive(Deserialize)]
struct LoginForm {
    email: String,
    password: String,
    /// Hidden CSRF field; absent on a forged post, hence `Option`.
    #[serde(rename = "_csrf")]
    csrf: Option<String>,
}

#[derive(Deserialize)]
struct CodeForm {
    code: String,
    #[serde(rename = "_csrf")]
    csrf: Option<String>,
}

/// Convert a neutral response into an Actix response.
fn into_response(api: ApiResponse) -> HttpResponse {
    let status = StatusCode::from_u16(api.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
    let mut builder = HttpResponse::build(status);
    for (k, v) in &api.headers {
        if let (Ok(name), Ok(val)) = (
            HeaderName::from_bytes(k.as_bytes()),
            HeaderValue::from_str(v),
        ) {
            builder.append_header((name, val));
        }
    }
    match api.body {
        ApiBody::Json(v) => builder.json(v),
        ApiBody::Bytes { content_type, data } => builder.content_type(content_type).body(data),
        ApiBody::Empty => builder.finish(),
    }
}

/// Build a request context, verifying the auth cookie into `claims` and
/// carrying the CSRF cookie through for form posts to check.
fn make_ctx(req: &HttpRequest, mount: &str) -> ReqCtx {
    let token = req.cookie(auth::COOKIE_NAME).map(|c| c.value().to_string());
    let csrf_cookie = req.cookie(csrf::COOKIE_NAME).map(|c| c.value().to_string());
    auth::build_ctx(
        mount,
        req.query_string(),
        token.as_deref(),
        csrf_cookie.as_deref(),
    )
}

/// Build the JSON API + HTML UI routes for a single resource.
fn resource_routes(resource: Box<dyn Resource>, mount: &'static str) -> Scope {
    let r: Arc<dyn Resource> = Arc::from(resource);
    let mut scope = web::scope("");

    // ---------- JSON API ----------
    scope = scope.route("/api", {
        let r = r.clone();
        web::get().to(move |req: HttpRequest| {
            let r = r.clone();
            async move { into_response(r.list(&make_ctx(&req, mount)).await) }
        })
    });
    scope = scope.route("/api", {
        let r = r.clone();
        web::post().to(move |req: HttpRequest, body: web::Json<Value>| {
            let r = r.clone();
            async move { into_response(r.create(&make_ctx(&req, mount), body.into_inner()).await) }
        })
    });
    scope = scope.route("/api/{id}", {
        let r = r.clone();
        web::get().to(move |req: HttpRequest, path: web::Path<String>| {
            let r = r.clone();
            async move { into_response(r.get(&make_ctx(&req, mount), &path.into_inner()).await) }
        })
    });
    scope = scope.route("/api/{id}", {
        let r = r.clone();
        web::put().to(
            move |req: HttpRequest, path: web::Path<String>, body: web::Json<Value>| {
                let r = r.clone();
                async move {
                    into_response(
                        r.update(&make_ctx(&req, mount), &path.into_inner(), body.into_inner())
                            .await,
                    )
                }
            },
        )
    });
    scope = scope.route("/api/{id}", {
        let r = r.clone();
        web::delete().to(move |req: HttpRequest, path: web::Path<String>| {
            let r = r.clone();
            async move { into_response(r.delete(&make_ctx(&req, mount), &path.into_inner()).await) }
        })
    });

    // ---------- HTML UI ----------
    scope = scope.route("/list", {
        let r = r.clone();
        web::get().to(move |req: HttpRequest| {
            let r = r.clone();
            async move { into_response(r.list_page(&make_ctx(&req, mount)).await) }
        })
    });
    scope = scope.route("/new", {
        let r = r.clone();
        web::get().to(move |req: HttpRequest| {
            let r = r.clone();
            async move { into_response(r.new_page(&make_ctx(&req, mount)).await) }
        })
    });
    scope = scope.route("/view/{id}", {
        let r = r.clone();
        web::get().to(move |req: HttpRequest, path: web::Path<String>| {
            let r = r.clone();
            async move { into_response(r.view_page(&make_ctx(&req, mount), &path.into_inner()).await) }
        })
    });
    scope = scope.route("/history/{id}", {
        let r = r.clone();
        web::get().to(move |req: HttpRequest, path: web::Path<String>| {
            let r = r.clone();
            async move { into_response(r.history_page(&make_ctx(&req, mount), &path.into_inner()).await) }
        })
    });
    scope = scope.route("/edit/{id}", {
        let r = r.clone();
        web::get().to(move |req: HttpRequest, path: web::Path<String>| {
            let r = r.clone();
            async move { into_response(r.edit_page(&make_ctx(&req, mount), &path.into_inner()).await) }
        })
    });
    scope = scope.route("/create", {
        let r = r.clone();
        web::post().to(
            move |req: HttpRequest, form: web::Form<HashMap<String, String>>| {
                let r = r.clone();
                async move {
                    into_response(r.create_form(&make_ctx(&req, mount), form.into_inner()).await)
                }
            },
        )
    });
    scope = scope.route("/update/{id}", {
        let r = r.clone();
        web::post().to(
            move |req: HttpRequest,
                  path: web::Path<String>,
                  form: web::Form<HashMap<String, String>>| {
                let r = r.clone();
                async move {
                    into_response(
                        r.update_form(&make_ctx(&req, mount), &path.into_inner(), form.into_inner())
                            .await,
                    )
                }
            },
        )
    });
    scope = scope.route("/{id}/delete", {
        let r = r.clone();
        web::post().to(
            move |req: HttpRequest,
                  path: web::Path<String>,
                  form: web::Form<HashMap<String, String>>| {
                let r = r.clone();
                let mut form = form.into_inner();
                let csrf = form.remove(csrf::FIELD_NAME);
                async move {
                    into_response(r.delete_form(&make_ctx(&req, mount), &path.into_inner(), csrf).await)
                }
            },
        )
    });

    // ---------- File attachments ----------
    // Upload rides a dedicated multipart endpoint; `_csrf` travels as a text
    // part of the same body alongside the file. Mirrors the Axum adapter.
    scope = scope.route("/{id}/attach/{field}", {
        let r = r.clone();
        web::post().to(
            move |req: HttpRequest, path: web::Path<(String, String)>, mut payload: Multipart| {
                let r = r.clone();
                async move {
                    let (id, field) = path.into_inner();
                    let mut csrf = None;
                    let mut file = None;
                    while let Some(Ok(mut item)) = payload.next().await {
                        let name = item
                            .content_disposition()
                            .and_then(|cd| cd.get_name().map(|s| s.to_string()));
                        let filename = item
                            .content_disposition()
                            .and_then(|cd| cd.get_filename().map(|s| s.to_string()));
                        let content_type = item.content_type().map(|m| m.to_string());
                        // Drain this field's chunks into one buffer.
                        let mut bytes = Vec::new();
                        while let Some(Ok(chunk)) = item.next().await {
                            bytes.extend_from_slice(&chunk);
                        }
                        match name.as_deref() {
                            Some(n) if n == csrf::FIELD_NAME => {
                                csrf = String::from_utf8(bytes).ok();
                            }
                            Some("file") => {
                                file = Some(UploadedFile {
                                    filename: filename.unwrap_or_else(|| "upload".into()),
                                    content_type: content_type
                                        .unwrap_or_else(|| "application/octet-stream".into()),
                                    bytes,
                                });
                            }
                            _ => {}
                        }
                    }
                    let ctx = make_ctx(&req, mount);
                    match file {
                        Some(file) => {
                            into_response(r.attach_file(&ctx, &id, &field, csrf, file).await)
                        }
                        None => into_response(
                            adminx_core::CoreError::BadRequest("no file in upload".into()).into(),
                        ),
                    }
                }
            },
        )
    });
    scope = scope.route("/{id}/blob/{field}", {
        let r = r.clone();
        web::get().to(move |req: HttpRequest, path: web::Path<(String, String)>| {
            let r = r.clone();
            async move {
                let (id, field) = path.into_inner();
                into_response(r.serve_file(&make_ctx(&req, mount), &id, &field).await)
            }
        })
    });
    scope = scope.route("/{id}/detach/{field}", {
        let r = r.clone();
        web::post().to(
            move |req: HttpRequest,
                  path: web::Path<(String, String)>,
                  form: web::Form<HashMap<String, String>>| {
                let r = r.clone();
                let mut form = form.into_inner();
                let csrf = form.remove(csrf::FIELD_NAME);
                async move {
                    let (id, field) = path.into_inner();
                    into_response(r.detach_file(&make_ctx(&req, mount), &id, &field, csrf).await)
                }
            },
        )
    });

    // ---------- Ordered relations ----------
    scope = scope.route("/{id}/related/{name}", {
        let r = r.clone();
        web::get().to(move |req: HttpRequest, path: web::Path<(String, String)>| {
            let r = r.clone();
            async move {
                let (id, name) = path.into_inner();
                into_response(r.related_page(&make_ctx(&req, mount), &id, &name).await)
            }
        })
    });
    scope = scope.route("/{id}/related/{name}", {
        let r = r.clone();
        web::post().to(
            move |req: HttpRequest,
                  path: web::Path<(String, String)>,
                  form: web::Form<HashMap<String, String>>| {
                let r = r.clone();
                let mut form = form.into_inner();
                let csrf = form.remove(csrf::FIELD_NAME);
                let op = form.remove("op");
                let member_id = form.remove("member_id");
                async move {
                    let (id, name) = path.into_inner();
                    into_response(
                        r.related_action(&make_ctx(&req, mount), &id, &name, op, member_id, csrf)
                            .await,
                    )
                }
            },
        )
    });

    // ---------- Custom actions ----------
    scope = scope.route("/{id}/action/{name}", {
        let r = r.clone();
        // The action button submits a url-encoded form; parse it as one, use the
        // remaining fields as the action's JSON body, and lift out `_csrf`.
        web::post().to(
            move |req: HttpRequest,
                  path: web::Path<(String, String)>,
                  form: web::Form<HashMap<String, String>>| {
                let r = r.clone();
                let mut form = form.into_inner();
                let csrf = form.remove(csrf::FIELD_NAME);
                let payload = ui::form_to_json(form);
                async move {
                    let (id, name) = path.into_inner();
                    into_response(r.run_action(&make_ctx(&req, mount), &name, id, payload, csrf).await)
                }
            },
        )
    });

    scope
}

async fn dashboard(req: HttpRequest, mount: &'static str) -> HttpResponse {
    let ctx = make_ctx(&req, mount);
    if let Some(deny) = auth::guard_ui(&ctx) {
        return into_response(deny);
    }
    into_response(ui::dashboard(&ctx).await)
}

async fn login_form(req: HttpRequest, mount: &'static str) -> HttpResponse {
    into_response(auth::login_page(&make_ctx(&req, mount), None))
}

async fn login_submit(req: HttpRequest, mount: &'static str, form: web::Form<LoginForm>) -> HttpResponse {
    let ctx = make_ctx(&req, mount);
    into_response(auth::handle_login(&ctx, &form.email, &form.password, form.csrf.as_deref()).await)
}

async fn logout(req: HttpRequest, mount: &'static str) -> HttpResponse {
    into_response(auth::handle_logout(&make_ctx(&req, mount)))
}

async fn mfa_setup_get(req: HttpRequest, mount: &'static str) -> HttpResponse {
    into_response(auth::mfa_setup_page(&make_ctx(&req, mount), None).await)
}

async fn mfa_enable_post(req: HttpRequest, mount: &'static str, form: web::Form<CodeForm>) -> HttpResponse {
    let ctx = make_ctx(&req, mount);
    into_response(auth::handle_mfa_enable(&ctx, &form.code, form.csrf.as_deref()).await)
}

async fn mfa_verify_get(req: HttpRequest, mount: &'static str) -> HttpResponse {
    into_response(auth::mfa_verify_page(&make_ctx(&req, mount), None).await)
}

async fn mfa_verify_post(req: HttpRequest, mount: &'static str, form: web::Form<CodeForm>) -> HttpResponse {
    let ctx = make_ctx(&req, mount);
    into_response(auth::handle_mfa_verify(&ctx, &form.code, form.csrf.as_deref()).await)
}

async fn health() -> HttpResponse {
    let ok = storage().health().await;
    let body = json!({ "status": if ok { "healthy" } else { "unhealthy" } });
    into_response(ApiResponse::json(if ok { 200 } else { 503 }, body))
}

/// Build the full adminx Actix scope, mounted at `/adminx`:
/// `App::new().service(adminx_actix::scope())`.
pub fn scope() -> Scope {
    scope_at(MOUNT)
}

/// Build the adminx Actix scope at a custom mount prefix. The prefix is both the
/// scope path and what in-page links, redirects, and form actions are built
/// from, so one argument keeps them in sync:
///
/// ```ignore
/// App::new().service(adminx_actix::scope_at("/admin"));
/// ```
///
/// The prefix must be a `&'static str` (it is captured by the route handlers).
pub fn scope_at(mount: &'static str) -> Scope {
    let mut scope = web::scope(mount)
        .route("", web::get().to(move |req: HttpRequest| dashboard(req, mount)))
        .route("/", web::get().to(move |req: HttpRequest| dashboard(req, mount)))
        .route("/health", web::get().to(health))
        .route("/login", web::get().to(move |req: HttpRequest| login_form(req, mount)))
        .route(
            "/login",
            web::post().to(move |req: HttpRequest, f: web::Form<LoginForm>| login_submit(req, mount, f)),
        )
        .route("/logout", web::get().to(move |req: HttpRequest| logout(req, mount)))
        .route("/mfa/setup", web::get().to(move |req: HttpRequest| mfa_setup_get(req, mount)))
        .route(
            "/mfa/enable",
            web::post().to(move |req: HttpRequest, f: web::Form<CodeForm>| mfa_enable_post(req, mount, f)),
        )
        .route("/mfa/verify", web::get().to(move |req: HttpRequest| mfa_verify_get(req, mount)))
        .route(
            "/mfa/verify",
            web::post().to(move |req: HttpRequest, f: web::Form<CodeForm>| mfa_verify_post(req, mount, f)),
        );

    let resources = all_resources();
    tracing::info!("adminx-actix: mounting {} resource(s) at '{}'", resources.len(), mount);

    for resource in resources {
        let base = format!("/{}", resource.base_path());
        tracing::info!(
            "adminx-actix: mounting '{}' at '{}{}'",
            resource.resource_name(),
            mount,
            base
        );
        scope = scope.service(web::scope(&base).service(resource_routes(resource, mount)));
    }

    scope
}