Functional Weave
Code in Rust

auth.validate-login@1.0.0

impl/rust.rs

1,638 bytes · the Rust implementation · view raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

use super::funejson::Value;  ← the fune runtime: the JSON value the test vectors use; fune build keeps it only where a signature takes one
use super::auth_normalise_email::normalise_email;  ← from auth.normalise-email ^1.0.0 · built alongside by fune

fn is_ascii_space(ch: char) -> bool {
    matches!(ch, ' ' | '\t' | '\n' | '\r' | '\u{0C}' | '\u{0B}')
}

/// A login form checked for shape only: the email to look up when valid, and
/// a message for each field that needs fixing. The password is never judged
/// against a policy here, so a password set under older rules still logs in.
pub fn validate_login(email: &str, password: &str) -> LoginCheck {
    let mut fields: Vec<(String, String)> = Vec::new();

    let normalised = normalise_email(email);
    if normalised.is_none() {
        let message = if email.trim_matches(is_ascii_space).is_empty() {
            "Enter your email address."
        } else {
            "Enter a valid email address, like name@example.com."
        };
        fields.push(("email".to_string(), message.to_string()));
    }
    if password.is_empty() {
        fields.push(("password".to_string(), "Enter your password.".to_string()));
    }

    LoginCheck { valid: fields.is_empty(), email: normalised, fields }
}

pub fn login_check_to_value(check: &LoginCheck) -> Value {
    Value::obj(vec![
        ("valid", Value::Bool(check.valid)),
        ("email", check.email.as_deref().map(Value::str).unwrap_or(Value::Null)),
        (
            "fields",
            Value::Obj(check.fields.iter().map(|(k, v)| (k.clone(), Value::str(v))).collect()),
        ),
    ])
}

pub fn fune_vector(args: &[Value]) -> Value {
    // A non-string is an empty field, as in TypeScript and Python.
    login_check_to_value(&validate_login(args[0].as_str(), args[1].as_str()))
}