capy-auth 0.10.0

Optional database-backed browser sessions and explicit authorization for Capy.
Documentation
use crate::Secret;
use capy_core::{AppError, Result};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use validator::ValidateEmail;

/// Public identity; persistence/security fields never cross the API boundary.
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct UserResponse {
    /// Database identity.
    pub id: i64,
    /// Display name.
    pub name: String,
    /// Canonical account email.
    pub email: String,
}
/// Registration input. Debug redacts the password.
#[derive(Debug, Deserialize, JsonSchema)]
pub struct RegisterRequest {
    /// Display name, 2..=100 characters after trimming.
    pub name: String,
    /// Email, trimmed and lowercased without provider-specific rewriting.
    pub email: String,
    /// Password, 12..=128 Unicode characters, no composition rules.
    #[schemars(with = "String")]
    pub password: Secret,
}
/// Login input; failures do not distinguish unknown users from incorrect passwords.
#[derive(Debug, Deserialize, JsonSchema)]
pub struct LoginRequest {
    /// Account email.
    pub email: String,
    /// Password.
    #[schemars(with = "String")]
    pub password: Secret,
}
/// Password reset request; the public response does not reveal account existence.
#[derive(Debug, Deserialize, JsonSchema)]
pub struct ForgotPasswordRequest {
    /// Account email.
    pub email: String,
}
/// Single-use reset credential and replacement password.
#[derive(Debug, Deserialize, JsonSchema)]
pub struct ResetPasswordRequest {
    /// Reset secret from the application's delivery adapter.
    #[schemars(with = "String")]
    pub token: Secret,
    /// Replacement password.
    #[schemars(with = "String")]
    pub password: Secret,
}
/// Constant public reset-request response.
#[derive(Debug, Serialize, JsonSchema)]
pub struct ResetRequestedResponse {
    /// The same message for known and unknown accounts.
    pub message: &'static str,
}
/// CSRF bootstrap response; do not log it or cache it.
#[derive(Serialize, JsonSchema)]
pub struct CsrfResponse {
    /// Send in X-CSRF-Token on every state-changing request.
    pub csrf_token: String,
}
impl std::fmt::Debug for CsrfResponse {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("CsrfResponse([REDACTED])")
    }
}
/// Deterministic whole-address lowercase and whitespace trimming.
/// This deliberately treats case variants as one account, with no alias/dot rewriting.
pub fn normalize_email(email: &str) -> Result<String> {
    let email = email.trim().to_lowercase();
    if email.len() > 254 || !email.validate_email() {
        return Err(invalid("email", "Enter a valid email address."));
    }
    Ok(email)
}
pub(crate) fn validate_password(password: &Secret, new: bool) -> Result<()> {
    let length = password.expose().chars().count();
    if !(if new { 12 } else { 1 }..=128).contains(&length) || password.expose().len() > 512 {
        return Err(invalid(
            "password",
            if new {
                "Use 12 to 128 characters."
            } else {
                "Invalid password length."
            },
        ));
    }
    Ok(())
}
pub(crate) fn invalid(field: &str, message: &str) -> AppError {
    AppError::Validation([(field.into(), vec![message.into()])].into())
}