oxblade-adminlte 0.1.0

Rust port of jeroennoten/laravel-adminlte: AdminLTE dashboard layouts, menus and plugins for Laravel for Rust.
Documentation
use crate::SafeUrl;
use serde::Serialize;
use std::fmt;

/// The upstream AdminLTE authentication view to render. Your app handles authentication.
///
/// ```
/// use oxblade_adminlte::AuthKind;
/// let view = AuthKind::SignIn;
/// assert_eq!(view, AuthKind::SignIn);
/// ```
#[derive(Clone, Eq, PartialEq)]
#[non_exhaustive]
pub enum AuthKind {
    /// PHP's login view.
    SignIn,
    /// PHP's registration view.
    Register,
    /// PHP's password reset request view.
    RequestReset,
    /// PHP's password reset form.
    ResetPassword {
        /// The reset token issued by the application's auth flow.
        token: String,
    },
    /// PHP's password confirmation view.
    ConfirmPassword,
    /// PHP's resend-verification view.
    VerifyEmail,
}

impl fmt::Debug for AuthKind {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::SignIn => formatter.write_str("SignIn"),
            Self::Register => formatter.write_str("Register"),
            Self::RequestReset => formatter.write_str("RequestReset"),
            Self::ResetPassword { .. } => formatter
                .debug_struct("ResetPassword")
                .field("token", &"<redacted>")
                .finish(),
            Self::ConfirmPassword => formatter.write_str("ConfirmPassword"),
            Self::VerifyEmail => formatter.write_str("VerifyEmail"),
        }
    }
}

/// Why an AdminLTE auth view could not be configured.
///
/// ```
/// use oxblade_adminlte::AuthFormError;
/// assert!(!AuthFormError::MissingToken.to_string().is_empty());
/// ```
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum AuthFormError {
    /// The form action is not a rooted path on the current origin.
    InvalidAction,
    /// A CSRF or reset token has not been supplied.
    MissingToken,
}

impl fmt::Display for AuthFormError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(match self {
            Self::InvalidAction => "the auth action must be a rooted same-origin path",
            Self::MissingToken => "the application must supply a non-empty form token",
        })
    }
}
impl std::error::Error for AuthFormError {}

/// Escaped view data for the PHP auth card and its forms.
///
/// Pass this value under the `auth` key to `adminlte::auth.form`, alongside a
/// resolved layout. The application owns the target route and CSRF validation.
///
/// ```
/// use oxblade_adminlte::{AuthForm, AuthKind};
/// let form = AuthForm::new(AuthKind::SignIn, "/login".parse()?, "example-csrf")?;
/// let _ = form;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Clone, Serialize)]
pub struct AuthForm {
    title: &'static str,
    classes: &'static str,
    box_class: &'static str,
    action: SafeUrl,
    fields: Vec<Field>,
    remember_checked: bool,
}

impl AuthForm {
    /// Builds an auth card with the app's validated POST action and CSRF token.
    ///
    /// ```
    /// use oxblade_adminlte::{AuthForm, AuthKind};
    /// assert!(AuthForm::new(AuthKind::Register, "/register".parse()?, "csrf").is_ok());
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn new(kind: AuthKind, action: SafeUrl, csrf: &str) -> Result<Self, AuthFormError> {
        if !action.as_str().starts_with('/') || action.as_str().contains('#') {
            return Err(AuthFormError::InvalidAction);
        }
        if csrf.trim().is_empty() {
            return Err(AuthFormError::MissingToken);
        }
        let mut fields = vec![Field::hidden("_token", csrf)];
        let (title, classes, box_class) = match kind {
            AuthKind::SignIn => {
                fields.extend([Field::email(), Field::password(false), Field::remember()]);
                ("Sign in", "login-page bg-body-secondary", "login-box")
            }
            AuthKind::Register => {
                fields.extend([
                    Field::visible("name", "text", "Name", "name"),
                    Field::email(),
                    Field::password(true),
                    Field::confirmation(),
                ]);
                ("Register", "register-page bg-body-secondary", "register-box")
            }
            AuthKind::RequestReset => {
                fields.push(Field::email());
                (
                    "Send password reset link",
                    "login-page bg-body-secondary",
                    "login-box",
                )
            }
            AuthKind::ResetPassword { token } => {
                if token.trim().is_empty() {
                    return Err(AuthFormError::MissingToken);
                }
                fields.extend([
                    Field::hidden("token", &token),
                    Field::email(),
                    Field::password(true),
                    Field::confirmation(),
                ]);
                ("Reset password", "login-page bg-body-secondary", "login-box")
            }
            AuthKind::ConfirmPassword => {
                fields.push(Field::password(false));
                (
                    "Confirm password",
                    "lockscreen bg-body-secondary",
                    "lockscreen-wrapper",
                )
            }
            AuthKind::VerifyEmail => (
                "Resend verification email",
                "login-page bg-body-secondary",
                "login-box",
            ),
        };
        Ok(Self {
            title,
            classes,
            box_class,
            action,
            fields,
            remember_checked: false,
        })
    }

    /// Preserves the app's old name, email and remember input, never a password.
    ///
    /// ```
    /// use oxblade_adminlte::{AuthForm, AuthKind};
    /// let _form = AuthForm::new(AuthKind::SignIn, "/login".parse()?, "csrf")?
    ///     .old("", "reader@example.test", true);
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    #[must_use]
    pub fn old(mut self, name: &str, email: &str, remember: bool) -> Self {
        for field in &mut self.fields {
            match field.name {
                "name" => field.value = name.into(),
                "email" => field.value = email.into(),
                _ => {}
            }
        }
        self.remember_checked = remember;
        self
    }

    /// Shows an app-provided plain-text validation message beside an input.
    ///
    /// ```
    /// use oxblade_adminlte::{AuthForm, AuthKind};
    /// let _form = AuthForm::new(AuthKind::SignIn, "/login".parse()?, "csrf")?
    ///     .with_error("email", "Enter an email address");
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    #[must_use]
    pub fn with_error(mut self, name: &str, message: impl Into<String>) -> Self {
        if let Some(field) = self
            .fields
            .iter_mut()
            .find(|field| field.name == name && field.kind != "hidden")
        {
            field.error = Some(message.into());
        }
        self
    }
}

#[derive(Clone, Serialize)]
struct Field {
    name: &'static str,
    kind: &'static str,
    label: &'static str,
    autocomplete: &'static str,
    value: String,
    error: Option<String>,
}

impl Field {
    fn visible(
        name: &'static str,
        kind: &'static str,
        label: &'static str,
        autocomplete: &'static str,
    ) -> Self {
        Self {
            name,
            kind,
            label,
            autocomplete,
            value: String::new(),
            error: None,
        }
    }

    fn hidden(name: &'static str, value: &str) -> Self {
        Self {
            value: value.to_owned(),
            ..Self::visible(name, "hidden", "", "")
        }
    }

    fn email() -> Self {
        Self::visible("email", "email", "Email", "email")
    }

    fn password(is_new: bool) -> Self {
        Self::visible(
            "password",
            "password",
            "Password",
            if is_new {
                "new-password"
            } else {
                "current-password"
            },
        )
    }

    fn confirmation() -> Self {
        Self::visible(
            "password_confirmation",
            "password",
            "Confirm password",
            "new-password",
        )
    }

    fn remember() -> Self {
        Self::visible("remember", "checkbox", "Remember me", "")
    }
}