runique 3.0.2

A Django-inspired web framework for Rust with ORM, templates, and comprehensive security middleware
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
//! Admin router: builds CRUD routes, login/logout, and attaches authentication middleware.
use crate::utils::config::TraceResult;
use std::sync::Arc;

use axum::{
    Extension, Router,
    extract::Path,
    http::{HeaderName, HeaderValue},
    middleware,
    response::{IntoResponse, Redirect, Response},
    routing::{get, post},
};
use serde::Deserialize;
use tower_http::set_header::SetResponseHeaderLayer;

use crate::app::staging::AdminStaging;
use crate::auth::{
    guard::LoginGuard,
    session::{login, logout},
};
use crate::context::template::Request;
use crate::middleware::security::rate_limit_middleware;
use crate::urlpatterns;
use crate::utils::{
    aliases::{AppResult, StrMap, StrVecMap},
    trad::{current_lang, t, tf},
};
use crate::{
    admin::{
        PrototypeAdminState,
        config::AdminConfig,
        middleware::admin_required,
        trad::{inject_admin_prefix, insert_admin_messages},
    },
    flash_now,
};

/// Shared admin state carried in an Axum `Extension`: the resolved config
/// (with the public URL prefix already applied) and the optional login guard
/// used by the login route to throttle brute-force attempts.
#[derive(Clone)]
pub struct AdminState {
    pub config: Arc<AdminConfig>,
    pub login_guard: Option<Arc<LoginGuard>>,
}

#[derive(Deserialize)]
struct AdminLoginData {
    username: String,
    password: String,
    #[serde(default)]
    csrf_token: String,
}

/// Builds the complete admin Axum router: public login routes, protected
/// dashboard/history/logout routes, and the daemon-generated CRUD router —
/// all mounted under the resolved public prefix (`mount_prefix` + admin's own
/// `path`) and wrapped with the auth-required, session-loading and
/// `X-Robots-Tag: noindex` layers.
pub fn build_admin_router(admin_staging: AdminStaging) -> Router {
    // Two independent values, never in competition:
    //   `admin_path`   — the admin's own path (`/site-admin`), from `.routes()`
    //   `mount_prefix` — the segment `.prefix()` puts in front (`/secret`)
    //   `prefix`       — the public base (`/secret/site-admin`), what a visitor types
    //
    // Built-in routes are declared through `urlpatterns!`, which registers their
    // name in the URL registry with the literal path given here — so they must be
    // built with the PUBLIC base, otherwise `{% url "admin_login" %}` resolves to
    // a path the router no longer serves. The generated CRUD router carries no
    // names (its routes are dynamic `{resource}/{action}`), so it is the only one
    // that gets `nest()`ed under the mount prefix.
    let admin_path = admin_staging
        .config
        .prefix
        .trim_end_matches('/')
        .to_string();
    let mount_prefix = admin_staging.mount_prefix.clone();
    let prefix = format!("{mount_prefix}{admin_path}");
    let mut config = admin_staging.config;
    config.prefix = prefix.clone();
    let state = admin_staging.state;

    let login_guard = config.login_guard.clone();
    let rate_limiter = config.rate_limiter.clone();

    let admin_state = Arc::new(AdminState {
        config: Arc::new(config.clone()),
        login_guard,
    });

    // Public routes (login only)
    let login_get_route = urlpatterns! {
        &format!("{prefix}/login") => get(admin_login_get), name = "admin_login",
    };

    let login_post_route = Router::new().route(&format!("{prefix}/login"), post(admin_login_post));

    let login_post_route = if let Some(limiter) = rate_limiter {
        login_post_route.layer(middleware::from_fn_with_state(
            limiter,
            rate_limit_middleware,
        ))
    } else {
        login_post_route
    };

    let public_router = login_get_route.merge(login_post_route);

    // Protected routes (dashboard + logout + history)
    let protected_router = urlpatterns! {
        &format!("{prefix}/") => get(admin_dashboard), name = "admin_dashboard",
        &prefix => get(admin_dashboard_redirect), name = "admin_dashboard_redirect",
        &format!("{prefix}/logout") => post(admin_logout), name = "admin_logout",
        &format!("{prefix}/toggle-template") => get(admin_toggle_template), name = "admin_toggle_template",
        &format!("{prefix}/history") => get(admin_history), name = "admin_history",
        &format!("{prefix}/history/timeline") => get(admin_history_timeline), name = "admin_history_timeline",
        &format!("{prefix}/history/batch/{{batch_id}}") => get(admin_history_batch), name = "admin_history_batch",
        &format!("{prefix}/history/{{id}}") => get(admin_history_diff), name = "admin_history_diff",
    };

    // Generated CRUD routes (also protected)
    let generated_router = if let Some(router) = admin_staging.route_admin {
        router
    } else {
        Router::new()
    };

    // Extra routes registered via .extra_routes() — protected by admin middleware,
    // and each by its resource's right (`extra_route_gate`). Built on `admin_path`,
    // not the public base: they ride along with the generated router through the
    // `nest()` below, which adds the mount prefix.
    let generated_router =
        admin_staging
            .extra_routes
            .into_iter()
            .fold(generated_router, |router, route| {
                let gated = route.router.layer(middleware::from_fn_with_state(
                    (route.resource, route.operation),
                    crate::admin::admin_main::gate::extra_route_gate,
                ));
                router.route(&format!("{}{}", admin_path, route.path), gated)
            });

    // Mount prefix applies here only — the generated routes are the ones whose
    // literal paths still carry `admin_path`. `nest("")` panics, hence the guard.
    let generated_router = if mount_prefix.is_empty() {
        generated_router
    } else {
        Router::new().nest(&mount_prefix, generated_router)
    };

    // Assembly: public + (protected + generated with middleware)
    let mut router = public_router
        .merge(
            protected_router
                .merge(generated_router)
                .layer(middleware::from_fn(admin_required)),
        )
        .layer(middleware::from_fn(
            crate::admin::middleware::admin_middleware::load_admin_user,
        ))
        .layer(Extension(admin_state))
        // Keep the admin out of search indexes without ever naming its path in a
        // public file: a `Disallow` in robots.txt would publish the very prefix a
        // dev picked to stay discreet, and it only asks crawlers not to *fetch* —
        // a linked URL can still be listed. This header says "do not index" and
        // applies to every admin response, login page included (it sits above
        // `admin_required`, which covers protected routes only), so redirects,
        // errors and JSON are covered too. `overriding`: no admin page has a
        // legitimate reason to be indexed, so no handler may weaken it.
        .layer(SetResponseHeaderLayer::overriding(
            HeaderName::from_static("x-robots-tag"),
            HeaderValue::from_static("noindex, nofollow"),
        ));

    if let Some(state) = state {
        // Replace proto_state config with the one from AdminStaging
        // so that templates configured via .templates() are taken into account.
        let order = config.resource_order.clone();
        let config = Arc::new(config);

        // Unwrap the Arc<PrototypeAdminState> to access fields in ownership.
        // try_unwrap succeeds as it is the sole owner at boot.
        let registry = match Arc::try_unwrap(state) {
            Ok(proto) => match Arc::try_unwrap(proto.registry) {
                Ok(mut reg) => {
                    if !order.is_empty() {
                        reg.reorder(&order);
                    }
                    Arc::new(reg)
                }
                Err(arc) => arc,
            },
            Err(arc) => arc.registry.clone(),
        };

        let merged = Arc::new(PrototypeAdminState { registry, config });
        router = router.layer(Extension(merged));
    }

    router
}

/// Session key for runtime override of the dashboard template.
///
/// A developer can store a Tera template name in this key to temporarily replace
/// the template configured via `.with_dashboard()`.
/// If absent or empty, `resolve()` applies normally.
///
/// ## Example (in a custom handler):
/// ```rust,ignore
/// session.insert(ADMIN_TEMPLATE_SESSION_KEY, "admin/dashboard").await?;
/// ```
pub const ADMIN_TEMPLATE_SESSION_KEY: &str = "admin_template_override";

async fn admin_dashboard_redirect(Extension(admin): Extension<Arc<AdminState>>) -> Response {
    Redirect::permanent(&format!("{}/", admin.config.prefix.trim_end_matches('/'))).into_response()
}

async fn admin_dashboard(
    Extension(admin): Extension<Arc<AdminState>>,
    Extension(current_user): Extension<crate::auth::session::CurrentUser>,
    proto: Option<Extension<Arc<PrototypeAdminState>>>,
    mut req: Request,
) -> AppResult<Response> {
    let db = req.engine.db.clone();

    let mut resource_counts: std::collections::HashMap<String, u64> =
        std::collections::HashMap::new();

    let resources: Vec<&crate::admin::AdminResource> = if let Some(Extension(ref state)) = proto {
        for (key, entry) in &state.registry.resources {
            if let Some(count_fn) = &entry.count_fn
                && let Ok(n) = (count_fn)(db.clone(), None, Vec::new(), None).await
            {
                resource_counts.insert(key.clone(), n);
            }
        }
        state
            .registry
            .all()
            .filter(|e| current_user.is_superuser || current_user.can_access_resource(e.meta.key))
            .map(|e| &e.meta)
            .collect()
    } else {
        Vec::new()
    };

    // Groups with permission on each resource_key
    let resource_groups: StrVecMap = {
        use crate::auth::permissions::{groupe, groupes_droits};
        use sea_orm::EntityTrait;
        let groupes: std::collections::HashMap<_, String> = groupe::Entity::find()
            .all(&*db)
            .await
            .trace(
                crate::utils::runique_log::get_log()
                    .admin
                    .as_ref()
                    .and_then(|a| a.list),
                "load groupes for permission map",
            )
            .unwrap_or_default()
            .into_iter()
            .map(|g| (g.id, g.nom))
            .collect();
        let rows = groupes_droits::Entity::find()
            .all(&*db)
            .await
            .trace(
                crate::utils::runique_log::get_log()
                    .admin
                    .as_ref()
                    .and_then(|a| a.list),
                "load groupes_droits for permission map",
            )
            .unwrap_or_default();
        let mut map: StrVecMap = StrVecMap::new();
        for r in rows {
            let nom = groupes
                .get(&r.groupe_id)
                .cloned()
                .unwrap_or_else(|| r.groupe_id.to_string());
            let entry = map.entry(r.resource_key).or_default();
            if !entry.contains(&nom) {
                entry.push(nom);
            }
        }
        map
    };

    let session_override: Option<String> = req
        .session
        .get(ADMIN_TEMPLATE_SESSION_KEY)
        .await
        .unwrap_or(None);

    insert_admin_messages(&mut req.context, "dashboard");
    insert_admin_messages(&mut req.context, "base");
    inject_admin_prefix(&mut req.context, &admin.config.prefix);
    req = req
        .insert("current_user", &current_user)
        .insert("site_title", &admin.config.site_title)
        .insert("site_url", admin.config.view_site_href())
        .insert("resources", &resources)
        .insert("resource_groups", &resource_groups)
        .insert("resource_counts", &resource_counts)
        .insert("current_page", "dashboard")
        .insert("lang", current_lang().code())
        .insert("current_resource", &Option::<String>::None)
        .insert("admin_has_session_override", session_override.is_some());

    let template = session_override
        .as_deref()
        .unwrap_or_else(|| admin.config.templates.dashboard.resolve());

    req.render(template)
}

/// `load_admin_user` (outer layer) puts the account here only while the
/// database still lets it into the admin: the session alone vouches for nothing.
fn signed_in_admin(current_user: Option<&Extension<crate::auth::session::CurrentUser>>) -> bool {
    current_user.is_some_and(|Extension(user)| user.can_access_admin())
}

async fn admin_login_get(
    Extension(admin): Extension<Arc<AdminState>>,
    axum::extract::Query(params): axum::extract::Query<StrMap>,
    current_user: Option<Extension<crate::auth::session::CurrentUser>>,
    mut req: Request,
) -> AppResult<Response> {
    let from_logout = params.get("from").is_some_and(|v| v == "logout");
    if !from_logout && signed_in_admin(current_user.as_ref()) {
        return Ok(Redirect::to(&format!("{}/", admin.config.prefix)).into_response());
    }

    insert_admin_messages(&mut req.context, "login");
    inject_admin_prefix(&mut req.context, &admin.config.prefix);

    req = req
        .insert("site_title", &admin.config.site_title)
        .insert("site_url", admin.config.view_site_href())
        .insert("lang", current_lang().code());
    req.render(admin.config.templates.login.resolve())
}

async fn admin_login_post(
    Extension(admin): Extension<Arc<AdminState>>,
    current_user: Option<Extension<crate::auth::session::CurrentUser>>,
    mut req: Request,
) -> Response {
    use crate::utils::crypto::csrf::unmask_csrf_token;
    use subtle::ConstantTimeEq;
    if signed_in_admin(current_user.as_ref()) {
        return Redirect::to(&format!("{}/", admin.config.prefix)).into_response();
    }
    // Fail fast under memory pressure: a saturated session store would refuse the new
    // session at commit time and surface as a generic 500. Return a clean 503 instead.
    if req.engine.session_store_saturated() {
        return axum::http::StatusCode::SERVICE_UNAVAILABLE.into_response();
    }
    let data = AdminLoginData {
        username: req.prisme.data.get("username").cloned().unwrap_or_default(),
        password: req.prisme.data.get("password").cloned().unwrap_or_default(),
        csrf_token: req
            .prisme
            .data
            .get(crate::utils::constante::session_key::session::CSRF_TOKEN_KEY)
            .cloned()
            .unwrap_or_default(),
    };
    let csrf_valid = unmask_csrf_token(&data.csrf_token)
        .map(|unmasked| {
            bool::from(
                unmasked
                    .as_bytes()
                    .ct_eq(req.csrf_token.as_str().as_bytes()),
            )
        })
        .unwrap_or(false);
    if !csrf_valid {
        insert_admin_messages(&mut req.context, "login");
        inject_admin_prefix(&mut req.context, &admin.config.prefix);
        req = req
            .insert("lang", current_lang().code())
            .insert("site_title", &admin.config.site_title)
            .insert("site_url", admin.config.view_site_href())
            .insert("error", t("csrf.invalid_or_missing").to_string());
        return req
            .render(admin.config.templates.login.resolve())
            .unwrap_or_else(axum::response::IntoResponse::into_response);
    }

    // Login guard verification (brute-force)
    if let Some(guard) = &admin.login_guard {
        let key = LoginGuard::effective_key(&data.username, "unknown");
        if guard.is_locked(&key) {
            let secs = guard.remaining_lockout_secs(&key).unwrap_or(0);
            insert_admin_messages(&mut req.context, "login");
            inject_admin_prefix(&mut req.context, &admin.config.prefix);
            req = req
                .insert("lang", current_lang().code())
                .insert("site_title", &admin.config.site_title)
                .insert("site_url", admin.config.view_site_href())
                .insert("error", tf("admin.login.error_locked", &[secs]));
            return req
                .render(admin.config.templates.login.resolve())
                .unwrap_or_else(axum::response::IntoResponse::into_response);
        }
    }

    let result =
        crate::auth::authenticate_admin(&req.engine.db, &data.username, &data.password).await;

    if let Some(user) = result {
        if let Some(guard) = &admin.login_guard {
            let key = LoginGuard::effective_key(&data.username, "unknown");
            guard.record_success(&key);
        }

        let db_store = req
            .engine
            .session_db_store
            .read()
            .ok()
            .and_then(|g| g.as_ref().cloned());
        let exclusive = req.engine.features.exclusive_login;
        if login(&req.session, &user, db_store.as_deref(), exclusive)
            .await
            .is_err()
        {
            insert_admin_messages(&mut req.context, "login");
            insert_admin_messages(&mut req.context, "base");
            inject_admin_prefix(&mut req.context, &admin.config.prefix);
            req = req
                .insert("lang", current_lang().code())
                .insert("site_title", &admin.config.site_title)
                .insert("site_url", admin.config.view_site_href())
                .insert("error", t("admin.login.error_session").to_string());
            return req
                .render(admin.config.templates.login.resolve())
                .unwrap_or_else(axum::response::IntoResponse::into_response);
        }

        Redirect::to(&format!("{}/", admin.config.prefix)).into_response()
    } else {
        if let Some(guard) = &admin.login_guard {
            let key = LoginGuard::effective_key(&data.username, "unknown");
            guard.record_failure(&key);
        }

        insert_admin_messages(&mut req.context, "login");
        insert_admin_messages(&mut req.context, "base");
        inject_admin_prefix(&mut req.context, &admin.config.prefix);
        req = req
            .insert("lang", current_lang().code())
            .insert("site_title", &admin.config.site_title)
            .insert("site_url", admin.config.view_site_href())
            .insert("error", t("admin.login.error_credentials").to_string());
        req.render(admin.config.templates.login.resolve())
            .unwrap_or_else(axum::response::IntoResponse::into_response)
    }
}

/// Maps resource key → nav title, so the history view shows the readable name
/// ("User profiles") instead of the raw key/table ("user_profile").
/// History stores `resource_key` = `meta.key`, so the lookup is direct.
fn resource_title_map<'a>(
    resources: &[&'a crate::admin::AdminResource],
) -> std::collections::HashMap<&'a str, &'a str> {
    resources.iter().map(|r| (r.key, r.title)).collect()
}

/// Picks a human label from a fetched object's JSON for the history view.
/// Tries the resource's primary display column first, then a few conventional
/// label fields. Returns `None` if nothing usable is found (→ `#pk` fallback).
fn object_label_from_json(obj: &serde_json::Value, preferred: Option<&str>) -> Option<String> {
    fn stringify(v: &serde_json::Value) -> Option<String> {
        match v {
            serde_json::Value::String(s) if !s.is_empty() => Some(s.clone()),
            serde_json::Value::Number(n) => Some(n.to_string()),
            _ => None,
        }
    }
    if let Some(col) = preferred
        && let Some(s) = obj.get(col).and_then(stringify)
    {
        return Some(s);
    }
    const FALLBACK: &[&str] = &[
        "nom", "name", "titre", "title", "libelle", "username", "label", "email",
    ];
    FALLBACK
        .iter()
        .find_map(|key| obj.get(*key).and_then(stringify))
}

/// Injects the context shared by every admin history view (flash messages, admin
/// prefix, nav state, resource list + titles, site identity). Each handler adds
/// its page-specific keys to `req`, then finishes with this call.
fn inject_admin_chrome(
    mut req: Request,
    admin: &AdminState,
    current_user: &crate::auth::session::CurrentUser,
    resources: &[&crate::admin::AdminResource],
    current_page: &str,
) -> Request {
    insert_admin_messages(&mut req.context, "base");
    inject_admin_prefix(&mut req.context, &admin.config.prefix);
    req.insert("current_page", current_page)
        .insert("current_resource", &Option::<String>::None)
        .insert("resources", resources)
        .insert("resource_titles", resource_title_map(resources))
        .insert("current_user", current_user)
        .insert("site_title", &admin.config.site_title)
        .insert("site_url", admin.config.view_site_href())
        .insert("lang", current_lang().code())
}

async fn admin_history(
    Extension(admin): Extension<Arc<AdminState>>,
    Extension(current_user): Extension<crate::auth::session::CurrentUser>,
    proto: Option<Extension<Arc<PrototypeAdminState>>>,
    axum::extract::Query(params): axum::extract::Query<StrMap>,
    mut req: Request,
) -> AppResult<Response> {
    use crate::admin::history;
    use sea_orm::{ColumnTrait, EntityTrait, PaginatorTrait, QueryFilter, QueryOrder};

    if !current_user.is_staff && !current_user.is_superuser {
        req.notices
            .error(t("admin.access.insufficient_rights").to_string())
            .await;
        return Ok(
            axum::response::Redirect::to(&format!("{}/", admin.config.prefix)).into_response(),
        );
    }

    let page = params
        .get("page")
        .and_then(|p| p.parse::<u64>().ok())
        .unwrap_or(1)
        .max(1);
    let per_page = admin.config.page_size;

    let filter_resource: Option<String> = params.get("resource").filter(|v| !v.is_empty()).cloned();
    let filter_action: Option<String> = params.get("action").filter(|v| !v.is_empty()).cloned();
    let filter_user: Option<String> = params.get("user").filter(|v| !v.is_empty()).cloned();

    let mut query = history::Entity::find().order_by_desc(history::Column::CreatedAt);
    if let Some(ref res) = filter_resource {
        query = query.filter(history::Column::ResourceKey.eq(res.clone()));
    }
    if let Some(ref action) = filter_action {
        query = query.filter(history::Column::Action.eq(action.clone()));
    }
    if let Some(ref user) = filter_user {
        query = query.filter(history::Column::Username.eq(user.clone()));
    }

    // Access control: a non-superuser only sees audit rows for resources they can
    // access. Without a registry (proto absent) we can't resolve perms, so a
    // non-superuser sees nothing rather than everything.
    if !current_user.is_superuser {
        let allowed = proto
            .as_ref()
            .map(|Extension(s)| s.registry.accessible_keys(&current_user))
            .unwrap_or_default();
        query = query.filter(history::Column::ResourceKey.is_in(allowed));
    }

    let paginator = query.paginate(&req.engine.db, per_page);
    let total_pages = paginator.num_pages().await.unwrap_or(1);
    let raw_entries: Vec<history::Model> = paginator
        .fetch_page(page - 1)
        .await
        .trace(
            crate::utils::runique_log::get_log()
                .admin
                .as_ref()
                .and_then(|a| a.list),
            "history fetch_page",
        )
        .unwrap_or_default();

    #[derive(serde::Serialize)]
    struct HistoryRow {
        id: i64,
        resource_key: String,
        object_pk: String,
        action: String,
        username: String,
        created_at: chrono::NaiveDateTime,
        summary: Option<String>,
        batch_id: Option<String>,
        batch_count: usize,
        /// Human label of the target object (resolved read-time via the resource's
        /// `get_fn`). `None` if the object was deleted or has no display column —
        /// the template then falls back to `#object_pk`.
        object_label: Option<String>,
    }

    let mut entries: Vec<HistoryRow> = Vec::new();
    let mut seen_batches: std::collections::HashSet<String> = std::collections::HashSet::new();
    for e in raw_entries {
        if let Some(ref bid) = e.batch_id {
            if seen_batches.contains(bid) {
                if let Some(row) = entries
                    .iter_mut()
                    .find(|r| r.batch_id.as_deref() == Some(bid))
                {
                    row.batch_count += 1;
                }
                continue;
            }
            seen_batches.insert(bid.clone());
        }
        entries.push(HistoryRow {
            id: e.id,
            resource_key: e.resource_key,
            object_pk: e.object_pk,
            action: e.action,
            username: e.username,
            created_at: e.created_at,
            summary: e.summary,
            batch_id: e.batch_id,
            batch_count: 1,
            object_label: None,
        });
    }

    let resources = proto
        .as_ref()
        .map(|Extension(s)| s.registry.visible_to(&current_user))
        .unwrap_or_default();

    // Resolve object_pk -> human label via each resource's `get_fn` (read-time,
    // deduped per (resource, pk)). Batch rows are skipped (no single object) and
    // deleted objects stay unresolved -> the template falls back to `#object_pk`.
    if let Some(Extension(ref state)) = proto {
        let mut cache: std::collections::HashMap<(String, String), String> =
            std::collections::HashMap::new();
        for row in &entries {
            if row.batch_count > 1 || row.object_pk.is_empty() {
                continue;
            }
            let key = (row.resource_key.clone(), row.object_pk.clone());
            if cache.contains_key(&key) {
                continue;
            }
            let Some(res) = state.registry.get(&row.resource_key) else {
                continue;
            };
            let Some(get_fn) = &res.get_fn else { continue };
            let preferred = match &res.meta.display.columns {
                crate::admin::ColumnFilter::Include(cols) => cols.first().map(|(c, _)| c.clone()),
                _ => None,
            };
            if let Ok(Some(obj)) = get_fn(req.engine.db.clone(), row.object_pk.clone()).await
                && let Some(label) = object_label_from_json(&obj, preferred.as_deref())
            {
                cache.insert(key, label);
            }
        }
        for row in &mut entries {
            row.object_label = cache
                .get(&(row.resource_key.clone(), row.object_pk.clone()))
                .cloned();
        }
    }

    req = req
        .insert("entries", &entries)
        .insert("page", page)
        .insert("total_pages", total_pages)
        .insert("filter_resource", &filter_resource)
        .insert("filter_action", &filter_action)
        .insert("filter_user", &filter_user);
    req = inject_admin_chrome(req, &admin, &current_user, &resources, "history");

    req.render("admin/history.html")
}

async fn admin_history_diff(
    Path(entry_id): Path<i64>,
    Extension(admin): Extension<Arc<AdminState>>,
    Extension(current_user): Extension<crate::auth::session::CurrentUser>,
    proto: Option<Extension<Arc<PrototypeAdminState>>>,
    mut req: Request,
) -> AppResult<Response> {
    use crate::admin::history;
    use crate::context::template::AppError;
    use crate::errors::error::ErrorContext;
    use sea_orm::EntityTrait;

    if !current_user.is_staff && !current_user.is_superuser {
        req.notices
            .error(t("admin.access.insufficient_rights").to_string())
            .await;
        return Ok(
            axum::response::Redirect::to(&format!("{}/", admin.config.prefix)).into_response(),
        );
    }

    let entry = history::Entity::find_by_id(entry_id)
        .one(&req.engine.db)
        .await
        .map_err(|e| Box::new(AppError::new(ErrorContext::database(e))))?
        .ok_or_else(|| Box::new(AppError::new(ErrorContext::not_found("Entry not found"))))?;

    // Access control: don't leak a diff for a resource the user can't access.
    if !current_user.is_superuser && !current_user.can_access_resource(&entry.resource_key) {
        req.notices
            .error(t("admin.access.insufficient_rights").to_string())
            .await;
        return Ok(
            axum::response::Redirect::to(&format!("{}/", admin.config.prefix)).into_response(),
        );
    }

    #[derive(serde::Serialize)]
    struct DiffField {
        key: String,
        old_val: String,
        new_val: String,
    }

    // Second passage de redaction, côté lecture. Il ne fait pas doublon avec celui
    // de l'écriture : il neutralise les lignes écrites **avant** que la règle
    // n'existe, sans migration de données, et il garantit que la valeur n'entre
    // jamais dans le contexte de rendu — un template d'historique surchargé par un
    // projet, ou un `{{ __tera_context }}` en mode debug, ne peut donc pas la
    // révéler.
    let diff_fields: Vec<DiffField> = entry
        .summary
        .as_deref()
        .and_then(|s| serde_json::from_str::<serde_json::Value>(s).ok())
        .and_then(|v| v.as_object().cloned())
        .map(|mut map| {
            crate::admin::history::redact_sensitive(&mut map);
            let mut fields: Vec<DiffField> = map
                .into_iter()
                .filter_map(|(k, v)| {
                    let obj = v.as_object()?;
                    let str_val = |v: &serde_json::Value| match v {
                        serde_json::Value::String(s) => s.clone(),
                        other => other.to_string(),
                    };
                    Some(DiffField {
                        key: k,
                        old_val: obj.get("old").map(str_val).unwrap_or_default(),
                        new_val: obj.get("new").map(str_val).unwrap_or_default(),
                    })
                })
                .collect();
            fields.sort_by(|a, b| a.key.cmp(&b.key));
            fields
        })
        .unwrap_or_default();

    let resources = proto
        .as_ref()
        .map(|Extension(s)| s.registry.visible_to(&current_user))
        .unwrap_or_default();

    req = req
        .insert("entry", &entry)
        .insert("diff_fields", &diff_fields);
    req = inject_admin_chrome(req, &admin, &current_user, &resources, "history");

    req.render("admin/history_diff.html")
}

async fn admin_history_timeline(
    Extension(admin): Extension<Arc<AdminState>>,
    Extension(current_user): Extension<crate::auth::session::CurrentUser>,
    proto: Option<Extension<Arc<PrototypeAdminState>>>,
    axum::extract::Query(params): axum::extract::Query<StrMap>,
    mut req: Request,
) -> AppResult<Response> {
    use crate::admin::history;
    use sea_orm::{ColumnTrait, EntityTrait, PaginatorTrait, QueryFilter, QueryOrder};

    if !current_user.is_staff && !current_user.is_superuser {
        req.notices
            .error(t("admin.access.insufficient_rights").to_string())
            .await;
        return Ok(
            axum::response::Redirect::to(&format!("{}/", admin.config.prefix)).into_response(),
        );
    }

    let page = params
        .get("page")
        .and_then(|p| p.parse::<u64>().ok())
        .unwrap_or(1)
        .max(1);
    let per_page = admin.config.page_size;

    let filter_user_id: Option<crate::utils::Pk> =
        params.get("user_id").and_then(|v| v.parse().ok());
    let filter_resource: Option<String> = params.get("resource").filter(|v| !v.is_empty()).cloned();
    let filter_object_id: Option<String> =
        params.get("object_id").filter(|v| !v.is_empty()).cloned();

    let mut query = history::Entity::find().order_by_desc(history::Column::CreatedAt);

    if let Some(uid) = filter_user_id {
        query = query.filter(history::Column::UserId.eq(uid));
    }
    if let Some(ref res) = filter_resource {
        query = query.filter(history::Column::ResourceKey.eq(res.clone()));
    }
    if let Some(ref oid) = filter_object_id {
        query = query.filter(history::Column::ObjectPk.eq(oid.clone()));
    }

    // Access control: non-superuser sees only accessible resources (see admin_history).
    if !current_user.is_superuser {
        let allowed = proto
            .as_ref()
            .map(|Extension(s)| s.registry.accessible_keys(&current_user))
            .unwrap_or_default();
        query = query.filter(history::Column::ResourceKey.is_in(allowed));
    }

    let paginator = query.paginate(&req.engine.db, per_page);
    let total_pages = paginator.num_pages().await.unwrap_or(1);
    let total = paginator.num_items().await.unwrap_or(0);
    let entries: Vec<history::Model> = paginator
        .fetch_page(page - 1)
        .await
        .trace(
            crate::utils::runique_log::get_log()
                .admin
                .as_ref()
                .and_then(|a| a.list),
            "history fetch_page",
        )
        .unwrap_or_default();

    let filter_type = if filter_object_id.is_some() && filter_resource.is_some() {
        "object"
    } else if filter_user_id.is_some() {
        "user"
    } else if filter_resource.is_some() {
        "resource"
    } else {
        "all"
    };

    let resources = proto
        .as_ref()
        .map(|Extension(s)| s.registry.visible_to(&current_user))
        .unwrap_or_default();

    req = req
        .insert("entries", &entries)
        .insert("page", page)
        .insert("total_pages", total_pages)
        .insert("total", total)
        .insert("filter_type", filter_type)
        .insert("filter_user_id", filter_user_id)
        .insert("filter_resource", &filter_resource)
        .insert("filter_object_id", &filter_object_id);
    req = inject_admin_chrome(req, &admin, &current_user, &resources, "history");

    req.render("admin/history_timeline.html")
}

async fn admin_history_batch(
    Path(batch_id): Path<String>,
    Extension(admin): Extension<Arc<AdminState>>,
    Extension(current_user): Extension<crate::auth::session::CurrentUser>,
    proto: Option<Extension<Arc<PrototypeAdminState>>>,
    mut req: Request,
) -> AppResult<Response> {
    use crate::admin::history;
    use sea_orm::{ColumnTrait, EntityTrait, QueryFilter, QueryOrder};

    if !current_user.is_staff && !current_user.is_superuser {
        req.notices
            .error(t("admin.access.insufficient_rights").to_string())
            .await;
        return Ok(
            axum::response::Redirect::to(&format!("{}/", admin.config.prefix)).into_response(),
        );
    }

    let entries: Vec<history::Model> = history::Entity::find()
        .filter(history::Column::BatchId.eq(batch_id.clone()))
        .order_by_asc(history::Column::Id)
        .all(&req.engine.db)
        .await
        .trace(
            crate::utils::runique_log::get_log()
                .admin
                .as_ref()
                .and_then(|a| a.list),
            "history batch fetch",
        )
        .unwrap_or_default();

    // Access control: a batch belongs to a single resource — block if the user
    // can't access it (an empty/unknown batch simply renders nothing).
    if !current_user.is_superuser
        && let Some(first) = entries.first()
        && !current_user.can_access_resource(&first.resource_key)
    {
        req.notices
            .error(t("admin.access.insufficient_rights").to_string())
            .await;
        return Ok(
            axum::response::Redirect::to(&format!("{}/", admin.config.prefix)).into_response(),
        );
    }

    #[derive(serde::Serialize)]
    struct DiffField {
        key: String,
        old_val: String,
        new_val: String,
    }

    #[derive(serde::Serialize)]
    struct BatchEntry {
        id: i64,
        object_pk: String,
        display_name: Option<String>,
        action: String,
        summary: Option<String>,
        diff_fields: Vec<DiffField>,
    }

    fn parse_diff(summary: Option<&str>) -> Vec<DiffField> {
        summary
            .and_then(|s| serde_json::from_str::<serde_json::Value>(s).ok())
            .and_then(|v| v.as_object().cloned())
            .map(|mut map| {
                // Même redaction côté lecture que la vue diff : les lignes écrites
                // avant l'existence de la règle passent aussi par ici.
                crate::admin::history::redact_sensitive(&mut map);
                let mut fields: Vec<DiffField> = map
                    .into_iter()
                    .filter_map(|(k, v)| {
                        let obj = v.as_object()?;
                        let str_val = |v: &serde_json::Value| match v {
                            serde_json::Value::String(s) => s.clone(),
                            other => other.to_string(),
                        };
                        Some(DiffField {
                            key: k,
                            old_val: obj.get("old").map(str_val).unwrap_or_default(),
                            new_val: obj.get("new").map(str_val).unwrap_or_default(),
                        })
                    })
                    .collect();
                fields.sort_by(|a, b| a.key.cmp(&b.key));
                fields
            })
            .unwrap_or_default()
    }

    fn extract_display_name(val: &serde_json::Value) -> Option<String> {
        let obj = val.as_object()?;
        for key in &["username", "name", "title", "email", "label", "slug"] {
            if let Some(serde_json::Value::String(s)) = obj.get(*key)
                && !s.is_empty()
            {
                return Some(s.clone());
            }
        }
        None
    }

    let resource_key = entries
        .first()
        .map(|e| e.resource_key.clone())
        .unwrap_or_default();
    let username = entries
        .first()
        .map(|e| e.username.clone())
        .unwrap_or_default();
    let created_at = entries.first().map(|e| e.created_at);
    let action = entries
        .first()
        .map(|e| e.action.clone())
        .unwrap_or_default();

    let get_fn = proto
        .as_ref()
        .and_then(|Extension(state)| state.registry.get(&resource_key))
        .and_then(|entry| entry.get_fn.clone());

    let mut batch_entries: Vec<BatchEntry> = Vec::new();
    for e in entries {
        let display_name = if let Some(ref f) = get_fn {
            f(req.engine.db.clone(), e.object_pk.clone())
                .await
                .ok()
                .flatten()
                .as_ref()
                .and_then(extract_display_name)
        } else {
            None
        };
        let diff = parse_diff(e.summary.as_deref());
        batch_entries.push(BatchEntry {
            id: e.id,
            object_pk: e.object_pk,
            display_name,
            action: e.action,
            summary: e.summary,
            diff_fields: diff,
        });
    }

    let resources = proto
        .as_ref()
        .map(|Extension(s)| s.registry.visible_to(&current_user))
        .unwrap_or_default();

    req = req
        .insert("batch_id", &batch_id)
        .insert("batch_entries", &batch_entries)
        .insert("resource_key", &resource_key)
        .insert("username", &username)
        .insert("created_at", created_at)
        .insert("action", &action);
    req = inject_admin_chrome(req, &admin, &current_user, &resources, "history");

    req.render("admin/history_batch.html")
}

async fn admin_toggle_template(
    Extension(admin): Extension<Arc<AdminState>>,
    req: Request,
) -> Response {
    let current: Option<String> = req
        .session
        .get::<String>(ADMIN_TEMPLATE_SESSION_KEY)
        .await
        .unwrap_or(None);
    let session_level = crate::utils::runique_log::get_log()
        .session
        .as_ref()
        .and_then(|s| s.store);
    if current.is_some() {
        req.session
            .remove::<String>(ADMIN_TEMPLATE_SESSION_KEY)
            .await
            .trace(session_level, "remove admin template session key");
    } else {
        req.session
            .insert(ADMIN_TEMPLATE_SESSION_KEY, "admin/dashboard.html")
            .await
            .trace(session_level, "insert admin template session key");
    }
    Redirect::to(&format!("{}/", admin.config.prefix)).into_response()
}

async fn admin_logout(Extension(admin): Extension<Arc<AdminState>>, req: Request) -> Response {
    let session = &req.session;
    let db_store = req
        .engine
        .session_db_store
        .read()
        .ok()
        .and_then(|g| g.as_ref().cloned());
    logout(session, db_store.as_deref()).await.trace(
        crate::utils::runique_log::get_log()
            .session
            .as_ref()
            .and_then(|s| s.store),
        "admin logout",
    );
    let login_url = format!("{}/login?from=logout", admin.config.prefix);
    flash_now!(info => t("admin.logout_success").as_ref());
    Redirect::to(&login_url).into_response()
}