Skip to main content

tablo_core/panel/
impersonation.rs

1//! What the panel shows of [`Auth::impersonation`](crate::Auth::impersonation): the banner on every
2//! page while a user acts as another, and the [`Impersonate`] action that starts it.
3
4use topcoat::{
5    context::Cx,
6    icon::icon,
7    view::{BoxView, ViewExt, attributes, view},
8};
9
10use crate::{Action, ActionDef, Outcome, PanelUser, Places, Resource, WriteError};
11
12/// Acts as the record's user: an [`Action`] for a resource whose model is the panel's user type,
13/// placed on its rows and record pages.
14///
15/// Its button shows only on a user the signed-in user may act as under the panel's
16/// [`Impersonation`](crate::Impersonation) rule, and never while they act as someone already.
17/// Running it lands on the panel root as that user. The resource's policy must also allow
18/// [`Ability::Run`](crate::Ability::Run) on the record.
19///
20/// ```rust
21/// # use tablo_core::{Allow, Impersonate, NoForm, Resource, ResourceDef, auth::AdminUser};
22/// struct Users;
23///
24/// impl Resource for Users {
25///     type Model = AdminUser;
26///     type Form = NoForm<AdminUser>;
27///
28///     fn declare() -> ResourceDef<Self> {
29///         ResourceDef::new().policy(Allow).action::<Impersonate>()
30///     }
31/// }
32/// ```
33#[derive(Debug, Clone, Copy)]
34pub struct Impersonate;
35
36impl<R: Resource> Action<R> for Impersonate
37where
38    R::Model: PanelUser,
39{
40    type Input = ();
41
42    const NAME: &'static str = "impersonate";
43
44    fn declare() -> ActionDef<R> {
45        ActionDef::new()
46            .places(Places::RECORD)
47            .icon(tablo_ui::icons::EYE)
48            .label(crate::text!("tablo-impersonation-start"))
49            .can_run(|cx, record: &R::Model| crate::auth::may_impersonate(cx, record))
50            .success(|_| crate::text!("tablo-impersonation-started"))
51    }
52
53    async fn run(
54        cx: &Cx,
55        records: &[R::Model],
56        (): (),
57        ex: &mut dyn toasty::Executor,
58    ) -> Result<Outcome, WriteError<()>> {
59        let [target] = records else {
60            return Err(WriteError::declined(crate::text!(
61                "tablo-impersonation-one"
62            )));
63        };
64        crate::auth::impersonate(cx, ex, target)
65            .await
66            .map_err(WriteError::Failed)?;
67        Ok(Outcome::done().redirect(crate::auth::panel_prefix(cx)))
68    }
69}
70
71/// The strip above every page while the signed-in user is acted as: whom, and Stop. Nothing
72/// otherwise.
73pub(super) fn banner(cx: &Cx) -> BoxView<'_> {
74    match crate::auth::signed(cx) {
75        Some(signed) if signed.impersonator.is_some() => strip(cx, signed),
76        _ => view! {}.boxed(),
77    }
78}
79
80fn strip<'a>(cx: &'a Cx, signed: &'a crate::auth::SignedIn) -> BoxView<'a> {
81    let csrf = crate::csrf::ensure_token(cx);
82    let stop = crate::auth::stop_impersonating_url(cx);
83    let name = signed.user.display_name().to_owned();
84    view! {
85        <div
86            class="flex flex-wrap items-center justify-between gap-2 border-b border-warning/40 \
87                       bg-warning/15 px-4 py-2 text-sm text-foreground"
88            role="status"
89            data-impersonating=(signed.user.user_id())
90        >
91            <span>(crate::t!(cx, "tablo-impersonation-banner", name = name))</span>
92            <form method="post" action=(stop)>
93                (crate::csrf::field(cx, &csrf))
94                tablo_ui::button(
95                    variant: tablo_ui::ButtonVariant::Outline,
96                    size: tablo_ui::ButtonSize::Sm,
97                    attrs: attributes! { type="submit" },
98                    icon(data: tablo_ui::icons::LOG_OUT)
99                    (crate::t!(cx, "tablo-impersonation-stop"))
100                )
101            </form>
102        </div>
103    }
104    .boxed()
105}