use crate::SafeUrl;
use serde::Serialize;
use std::fmt;
#[derive(Clone, Eq, PartialEq)]
#[non_exhaustive]
pub enum AuthKind {
SignIn,
Register,
RequestReset,
ResetPassword {
token: String,
},
ConfirmPassword,
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"),
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum AuthFormError {
InvalidAction,
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 {}
#[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 {
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,
})
}
#[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
}
#[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", "")
}
}