Skip to main content

oxblade_adminlte/
auth.rs

1use crate::SafeUrl;
2use serde::Serialize;
3use std::fmt;
4
5/// The upstream AdminLTE authentication view to render. Your app handles authentication.
6///
7/// ```
8/// use oxblade_adminlte::AuthKind;
9/// let view = AuthKind::SignIn;
10/// assert_eq!(view, AuthKind::SignIn);
11/// ```
12#[derive(Clone, Eq, PartialEq)]
13#[non_exhaustive]
14pub enum AuthKind {
15    /// PHP's login view.
16    SignIn,
17    /// PHP's registration view.
18    Register,
19    /// PHP's password reset request view.
20    RequestReset,
21    /// PHP's password reset form.
22    ResetPassword {
23        /// The reset token issued by the application's auth flow.
24        token: String,
25    },
26    /// PHP's password confirmation view.
27    ConfirmPassword,
28    /// PHP's resend-verification view.
29    VerifyEmail,
30}
31
32impl fmt::Debug for AuthKind {
33    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
34        match self {
35            Self::SignIn => formatter.write_str("SignIn"),
36            Self::Register => formatter.write_str("Register"),
37            Self::RequestReset => formatter.write_str("RequestReset"),
38            Self::ResetPassword { .. } => formatter
39                .debug_struct("ResetPassword")
40                .field("token", &"<redacted>")
41                .finish(),
42            Self::ConfirmPassword => formatter.write_str("ConfirmPassword"),
43            Self::VerifyEmail => formatter.write_str("VerifyEmail"),
44        }
45    }
46}
47
48/// Why an AdminLTE auth view could not be configured.
49///
50/// ```
51/// use oxblade_adminlte::AuthFormError;
52/// assert!(!AuthFormError::MissingToken.to_string().is_empty());
53/// ```
54#[derive(Clone, Copy, Debug, Eq, PartialEq)]
55#[non_exhaustive]
56pub enum AuthFormError {
57    /// The form action is not a rooted path on the current origin.
58    InvalidAction,
59    /// A CSRF or reset token has not been supplied.
60    MissingToken,
61}
62
63impl fmt::Display for AuthFormError {
64    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
65        formatter.write_str(match self {
66            Self::InvalidAction => "the auth action must be a rooted same-origin path",
67            Self::MissingToken => "the application must supply a non-empty form token",
68        })
69    }
70}
71impl std::error::Error for AuthFormError {}
72
73/// Escaped view data for the PHP auth card and its forms.
74///
75/// Pass this value under the `auth` key to `adminlte::auth.form`, alongside a
76/// resolved layout. The application owns the target route and CSRF validation.
77///
78/// ```
79/// use oxblade_adminlte::{AuthForm, AuthKind};
80/// let form = AuthForm::new(AuthKind::SignIn, "/login".parse()?, "example-csrf")?;
81/// let _ = form;
82/// # Ok::<(), Box<dyn std::error::Error>>(())
83/// ```
84#[derive(Clone, Serialize)]
85pub struct AuthForm {
86    title: &'static str,
87    classes: &'static str,
88    box_class: &'static str,
89    action: SafeUrl,
90    fields: Vec<Field>,
91    remember_checked: bool,
92}
93
94impl AuthForm {
95    /// Builds an auth card with the app's validated POST action and CSRF token.
96    ///
97    /// ```
98    /// use oxblade_adminlte::{AuthForm, AuthKind};
99    /// assert!(AuthForm::new(AuthKind::Register, "/register".parse()?, "csrf").is_ok());
100    /// # Ok::<(), Box<dyn std::error::Error>>(())
101    /// ```
102    pub fn new(kind: AuthKind, action: SafeUrl, csrf: &str) -> Result<Self, AuthFormError> {
103        if !action.as_str().starts_with('/') || action.as_str().contains('#') {
104            return Err(AuthFormError::InvalidAction);
105        }
106        if csrf.trim().is_empty() {
107            return Err(AuthFormError::MissingToken);
108        }
109        let mut fields = vec![Field::hidden("_token", csrf)];
110        let (title, classes, box_class) = match kind {
111            AuthKind::SignIn => {
112                fields.extend([Field::email(), Field::password(false), Field::remember()]);
113                ("Sign in", "login-page bg-body-secondary", "login-box")
114            }
115            AuthKind::Register => {
116                fields.extend([
117                    Field::visible("name", "text", "Name", "name"),
118                    Field::email(),
119                    Field::password(true),
120                    Field::confirmation(),
121                ]);
122                ("Register", "register-page bg-body-secondary", "register-box")
123            }
124            AuthKind::RequestReset => {
125                fields.push(Field::email());
126                (
127                    "Send password reset link",
128                    "login-page bg-body-secondary",
129                    "login-box",
130                )
131            }
132            AuthKind::ResetPassword { token } => {
133                if token.trim().is_empty() {
134                    return Err(AuthFormError::MissingToken);
135                }
136                fields.extend([
137                    Field::hidden("token", &token),
138                    Field::email(),
139                    Field::password(true),
140                    Field::confirmation(),
141                ]);
142                ("Reset password", "login-page bg-body-secondary", "login-box")
143            }
144            AuthKind::ConfirmPassword => {
145                fields.push(Field::password(false));
146                (
147                    "Confirm password",
148                    "lockscreen bg-body-secondary",
149                    "lockscreen-wrapper",
150                )
151            }
152            AuthKind::VerifyEmail => (
153                "Resend verification email",
154                "login-page bg-body-secondary",
155                "login-box",
156            ),
157        };
158        Ok(Self {
159            title,
160            classes,
161            box_class,
162            action,
163            fields,
164            remember_checked: false,
165        })
166    }
167
168    /// Preserves the app's old name, email and remember input, never a password.
169    ///
170    /// ```
171    /// use oxblade_adminlte::{AuthForm, AuthKind};
172    /// let _form = AuthForm::new(AuthKind::SignIn, "/login".parse()?, "csrf")?
173    ///     .old("", "reader@example.test", true);
174    /// # Ok::<(), Box<dyn std::error::Error>>(())
175    /// ```
176    #[must_use]
177    pub fn old(mut self, name: &str, email: &str, remember: bool) -> Self {
178        for field in &mut self.fields {
179            match field.name {
180                "name" => field.value = name.into(),
181                "email" => field.value = email.into(),
182                _ => {}
183            }
184        }
185        self.remember_checked = remember;
186        self
187    }
188
189    /// Shows an app-provided plain-text validation message beside an input.
190    ///
191    /// ```
192    /// use oxblade_adminlte::{AuthForm, AuthKind};
193    /// let _form = AuthForm::new(AuthKind::SignIn, "/login".parse()?, "csrf")?
194    ///     .with_error("email", "Enter an email address");
195    /// # Ok::<(), Box<dyn std::error::Error>>(())
196    /// ```
197    #[must_use]
198    pub fn with_error(mut self, name: &str, message: impl Into<String>) -> Self {
199        if let Some(field) = self
200            .fields
201            .iter_mut()
202            .find(|field| field.name == name && field.kind != "hidden")
203        {
204            field.error = Some(message.into());
205        }
206        self
207    }
208}
209
210#[derive(Clone, Serialize)]
211struct Field {
212    name: &'static str,
213    kind: &'static str,
214    label: &'static str,
215    autocomplete: &'static str,
216    value: String,
217    error: Option<String>,
218}
219
220impl Field {
221    fn visible(
222        name: &'static str,
223        kind: &'static str,
224        label: &'static str,
225        autocomplete: &'static str,
226    ) -> Self {
227        Self {
228            name,
229            kind,
230            label,
231            autocomplete,
232            value: String::new(),
233            error: None,
234        }
235    }
236
237    fn hidden(name: &'static str, value: &str) -> Self {
238        Self {
239            value: value.to_owned(),
240            ..Self::visible(name, "hidden", "", "")
241        }
242    }
243
244    fn email() -> Self {
245        Self::visible("email", "email", "Email", "email")
246    }
247
248    fn password(is_new: bool) -> Self {
249        Self::visible(
250            "password",
251            "password",
252            "Password",
253            if is_new {
254                "new-password"
255            } else {
256                "current-password"
257            },
258        )
259    }
260
261    fn confirmation() -> Self {
262        Self::visible(
263            "password_confirmation",
264            "password",
265            "Confirm password",
266            "new-password",
267        )
268    }
269
270    fn remember() -> Self {
271        Self::visible("remember", "checkbox", "Remember me", "")
272    }
273}