Smeltery
Get started

Security

v0.1

Temper: the authentication routes

Temper (smeltery::temper) puts the flows above behind routes: login, logout, registration, password reset, e-mail verification, password confirmation and profile and password updates, each feature switched on in one builder. The app keeps the pages (TemperViews: one closure per page returning any response, such as a #[derive(Mold)] struct or an Alloy page), the actions (traits with a typed, validated Input: CreatesNewUsers, ResetsUserPasswords, UpdatesUserPasswords, UpdatesUserProfileInformation) and, where it wants, its own answers (TemperResponses). Every check runs through the core functions of this section.

rust
use serde::Deserialize;
use smeltery::http::Html;
use smeltery::temper::{PasswordInput, ResetsUserPasswords, Temper, TemperExt as _, TemperViews};
use smeltery::Validate;

/// The reset form: the app's password rules.
#[derive(Deserialize, Validate)]
pub struct ResetForm {
    #[validate(required, email)]
    #[serde(deserialize_with = "smeltery::auth::deserialize_email")]
    pub email: String,
    #[validate(required, min = 8, confirmed)]
    pub password: String,
    pub password_confirmation: Option<String>,
}

impl PasswordInput for ResetForm {
    fn email(&self) -> &str { &self.email }
    fn password(&self) -> &str { &self.password }
}

pub struct ResetUserPassword;

impl ResetsUserPasswords<User> for ResetUserPassword {
    type Input = ResetForm;
}

fn build(app: smeltery::AppBuilder) -> smeltery::AppBuilder {
    app.temper(
        Temper::<User>::new()
            .reset_passwords(ResetUserPassword)
            .email_verification()
            .views(
                TemperViews::new()
                    .login(|_| Html("<h1>Log in</h1>"))
                    .forgot_password(|_| Html("<h1>Forgot your password?</h1>"))
                    .reset_password(|ctx| Html(format!("<h1>New password</h1><p>{} chars</p>", ctx.token().len())))
                    .verify_email(|_| Html("<h1>Check your inbox</h1>"))
                    .confirm_password(|_| Html("<h1>Confirm your password</h1>")),
            ),
    )
}

.temper(…) registers User as the user model (.auth::<User>(); call .auth with no other model), the web routes below and its login pipeline as the login completion (app.login_completion()), and never flashes a field named code as old input. The app stops at boot when a page route has no view (the error names the TemperViews method), when without_route names an unknown route, when the prefix is invalid, or when .auth::<…>() registers another model.

Route Name Middleware Feature
GET / POST /login login, login.store guest; throttle:30,1 on POST always
POST /logout logout auth always
GET / POST /register register, register.store guest; throttle:6,1 on POST registration
GET / POST /forgot-password password.request, password.email guest; throttle:6,1 on POST reset_passwords
GET / POST /reset-password/{token} password.reset, password.update guest; throttle:6,1 on POST reset_passwords
GET /email/verify verification.notice auth email_verification
GET /email/verify/{id}/{hash} verification.verify auth, throttle:6,1 email_verification
POST /email/verification-notification verification.send auth (six a minute per user) email_verification
PUT /user/profile-information user-profile-information.update auth, throttle:6,1 update_profile_information
PUT /user/password user-password.update auth, throttle:6,1 update_passwords
GET / POST /user/confirm-password password.confirm, password.confirm.store auth; throttle:6,1 on POST always
GET /user/confirmed-password-status password.confirmation auth always
GET / POST /two-factor-challenge two-factor.login, two-factor.login.store guest; throttle:30,1 on POST two_factor
POST / DELETE /user/two-factor-authentication, POST /user/confirmed-two-factor-authentication, GET /user/two-factor-qr-code, GET /user/two-factor-secret-key, GET / POST /user/two-factor-recovery-codes two-factor.enable, two-factor.disable, two-factor.confirm, two-factor.qr-code, two-factor.secret-key, two-factor.recovery-codes, two-factor.regenerate-recovery-codes auth, password.confirm; throttle:6,1 on POST two_factor

A login checks the password with auth.validate (the login budgets above), then runs the login pipeline: the app's login policies (app.check_login, see Authentication; .login_policy(|app, user| …) adds one typed on the user model), the app's steps (Temper::login_pipeline), the sign-in (auth.login_user; Temper is the app's login completion), the Login event and the answer (the remembered page, else AUTH_HOME; JSON clients get 200 {"two_factor": false}). A wrong address or password answers "These credentials do not match our records." on email: the login page for browsers and Inertia visits, 422 for JSON clients. A password update checks current_password through auth.confirm_password (five tries a minute per user) and stores the new one with auth.set_password, so this device stays signed in and every other session ends. A profile update that changes the address empties email_verified_at through auth::mark_unverified when the app requires verified addresses, and sends a link to the new address. JSON clients (Accept: application/json) get status codes and JSON bodies throughout; .views(false) registers no page routes (browser requests then get redirects to pages that do not exist). The reset page's ctx.token() and ctx.email() come from the link as sent: render them escaped. Other options: .home(path), .prefix("/auth"), .routes(false), .without_route(name), .limits(Limits::new().login("30,1").forms("6,1")), .listen(f) for TemperEvents (user ids only; listeners never change the answer). smeltery::temper::login_pipeline(&ctx, &user, remember) signs a user in through the same pipeline from another sign-in path. Pipeline steps gate new sign-ins only: an open session or a remember-me restore never meets them, so locking an account out also ends its credentials (auth::end_credentials). Steps run for web sign-ins only; a rule that must also hold for API tokens and remember-me cookies (a suspended account) is a login policy. Registration asks the login policies after creating the account: a refusal (an account that awaits approval) keeps the account, fires Registered, signs nobody in and answers the refusal. When the action returns a user that has two-factor authentication (an existing account), the request fails with 500 and nobody is signed in. A refusal at the two-factor challenge answers JSON clients with the message on code and sends browsers to the login page with it on email. .two_factor(TwoFactor::new()) (a user model implementing TwoFactorAuthenticatable over the columns two_factor_secret, two_factor_recovery_codes, two_factor_confirmed_at, two_factor_last_step) adds codes from an authenticator app (RFC 6238 TOTP) and single-use recovery codes: a correct password then gives a pending login (a new session id; five minutes; bound to the password hash; ended after five wrong codes) and the challenge page (JSON clients: 200 {"two_factor": true}) instead of a sign-in. Secrets are encrypted with App::encrypt("temper.two-factor", <user id>, …), recovery codes stored as SHA-256 hashes and shown once; a code is accepted once (one conditional UPDATE of the last accepted time step), a recovery code removed by compare-and-set; every code counts against the account's budget (five per five minutes, one hundred a day, shared by processes through the cache) before it is checked; past it the challenge answers 429 with Retry-After (browsers: the message on the challenge page). The login policies are asked again before a code is checked. The QR code is an SVG data URI for an <img>. Turning two-factor on (confirmed) or off replaces the remember token. It also registers core's SecondFactor, removes an enrolment when a reset verifies a previously unverified address, and adds temper:two-factor-disable <email> --force. A new APP_KEY makes stored secrets unreadable: app codes are refused (two-factor stays on), recovery codes still work. The crate's README (smeltery-temper) has the full reference.

↑↓ moveEnter openEsc close