dust

Resetting Passwords

Introduction

dust-framework can handle generating and verifying password reset tokens, sending reset emails, and updating user passwords through the Passwords<User> extractor, while leaving your application in charge of the routes and forms.

Before getting started, configure authentication so users can sign in.

Preparing your application

dust-framework sends password reset emails using the mail system by passing your user to mail::to(&user). To make User usable as a recipient, implement From<&User> for Address in src/models/user.rs (see Recipients):

rust
use dust::mail::Address;impl From<&User> for Address {    fn from(user: &User) -> Self {        Address::new(&user.email).with_name(&user.name)    }}

Reset emails are queued so the response doesn't wait for your mail provider, which means a queue worker must be running to deliver them.

dust-framework keeps reset tokens in your default cache store. When you run more than one server, use a store that every server shares, such as database or redis, not memory.

Reset links start with the request's host. In production, dust-framework answers only requests for the host in your APP_URL and its subdomains, so a forged Host header can't point a link at another site. If you serve other domains too, add them to your trusted hosts.

Routing

A reset needs four routes: two to show the forgot password form and send the link, and two to show the reset form and save the new password. Add them to your web routes, behind RedirectIfAuthenticated, which sends a user who is already logged in to their home page instead:

rust
use dust::auth::RedirectIfAuthenticated;route.middleware(RedirectIfAuthenticated).group(|route| {    route.get("/forgot-password", passwords::show_forgot_password);    route.post("/forgot-password", passwords::send_reset_link);    route.get("/reset-password/{token}", passwords::show_reset_password);    route.post("/reset-password", passwords::reset_password);});
Method URI Handler
GET /forgot-password Shows the form that asks for the email address
POST /forgot-password Sends the reset link
GET /reset-password/{token} Shows the form that sets a new password
POST /reset-password Saves the new password

The reset form posts to a different URI from the one that shows it, so the token travels in a hidden field rather than in the form's action. Keep the token out of your logs and analytics; it is as sensitive as the password it can replace.

Throttle the handler that sends the email, so a script can't flood a user's inbox or use your mail provider's quota:

rust
use dust::http::middleware::Throttle;route    .post("/forgot-password", passwords::send_reset_link)    .middleware(Throttle::per_minute(6).bucket("password-reset"));

The handler already skips a second email within 60 seconds, but the throttle also limits requests for addresses that don't exist, which would otherwise cost a query each time. To learn more, check out the rate limiting guide.

Sending reset links

Your forgot password page should show a form with an email field. When the user submits it, validate the email and pass it to send_reset_link, which emails the user a link to your reset page:

rust
use dust::auth::Passwords;use dust::prelude::*;use dust::view::View;#[dust::input]#[validate(anyone)]pub struct ForgotPassword {    #[validate(required, email)]    email: String,}pub async fn show_forgot_password() -> View {    view("auth.forgot-password", data! {})}pub async fn send_reset_link(    passwords: Passwords<User>,    Valid(form): Valid<ForgotPassword>,) -> dust::Result<Redirect> {    passwords.send_reset_link(&form.email).await?;    Ok(        Redirect::back()            .with("status", "If that email has an account, we've sent it a reset link."),    )}

When no user matches the email, send_reset_link sends nothing and returns the same outcome so the response never reveals whether an account exists. Keep your status message identical in both cases. If the user requests another link within 60 seconds, send_reset_link skips sending; otherwise, the new link replaces the previous one.

Resetting the password

The link in the email opens the handler you marked with #[dust::auth::page(reset_password)]. The reset token arrives in the {token} route parameter and the email address arrives in the query string, as in https://acme.test/reset-password/4Fq…?email=taylor%40example.com.

Your reset page should show a form with the email, a new password and its confirmation, and the token in a hidden field. When the user submits it, pass the form's values to reset:

rust
use dust::auth::Passwords;use dust::hash::Password;use dust::prelude::*;use dust::view::View;#[dust::input]#[validate(anyone)]pub struct ResetPassword {    #[validate(required)]    token: String,    #[validate(required, email)]    email: String,    #[validate(required, password, confirmed)]    password: Password,}#[dust::query]pub struct ResetLink {    #[default]    email: String,}pub async fn show_reset_password(    Params(token): Params<String>,    Query(link): Query<ResetLink>,) -> View {    view("auth.reset-password", data! { token, email => link.email })}pub async fn reset_password(    passwords: Passwords<User>,    Valid(form): Valid<ResetPassword>,) -> dust::Result<Redirect> {    passwords.reset(&form.email, &form.token, &form.password).await?;    Ok(redirect!(auth::show_login).with("status", "Your password has been reset."))}

Make the email field read-only, with autocomplete="username", so a password manager saves the new password for that account.

reset verifies the reset token, stores the new password, and returns the user. Each reset token is single-use and valid for 60 minutes. If a reset token is invalid or expired, reset returns a validation error on the email field with the message "This password reset token is invalid.", so display errors for that field. Like changing a password, a reset logs the user out on every device.

Logging the user in after a reset

reset doesn't log the user in. To log them in instead of sending them to the login page, pass the user that reset returns to login:

rust
use dust::auth::{Auth, Passwords};use dust::prelude::*;pub async fn reset_password(    passwords: Passwords<User>,    auth: Auth<User>,    Valid(form): Valid<ResetPassword>,) -> dust::Result<Redirect> {    let user = passwords.reset(&form.email, &form.token, &form.password).await?;    auth.login(&user).await?;    Ok(redirect!(dashboard::show))}

Checking a link before showing the form

A user may open an expired or already-used link. To notify them before they enter a new password, call validate on the reset page. It returns the matching user, or None, without consuming the reset token:

rust
use dust::auth::Passwords;use dust::prelude::*;use dust::view::View;pub async fn show_reset_password(    passwords: Passwords<User>,    Params(token): Params<String>,    Query(ResetLink { email }): Query<ResetLink>,) -> dust::Result<View> {    if passwords.validate(&email, &token).await?.is_none() {        return Ok(view("auth.reset-link-expired", data! {}));    }    Ok(view("auth.reset-password", data! { token, email }))}

Calling validate first lets you show a friendly "request a new link" page instead of a 422 after the user has already typed a new password. The check does not use up the token, so the same link still works when the user submits the form.

Customizing the reset email

By default, dust-framework sends password reset links using the built-in dust::auth::ResetPasswordEmail mailable, which uses the subject "Reset your password" and renders with dust-framework's mail components.

To customize the email's wording or layout without writing a custom mailable, copy resources/views/auth/reset-password.html to resources/views/vendor/dust/auth/reset-password.html in your application and edit it to fit your brand. The template receives url for the reset link and minutes for the expiration window.

To send a custom mailable, such as a ResetYourPassword email greeting the user by name, call send_reset_link_with. It generates a reset token and passes both the user and reset token to your closure so you can build the link and queue the email. Because each reset token is bound to the email address passed in, include that same email address in the link:

rust
use dust::auth::Passwords;use dust::mail;use dust::prelude::*;pub async fn send_reset_link(    passwords: Passwords<User>,    Valid(form): Valid<ForgotPassword>,) -> dust::Result<Redirect> {    passwords        .send_reset_link_with(&form.email, async |user, token| {            let url = route!(show_reset_password, token = &token, email = &form.email)?;            mail::to(&user).queue(ResetYourPassword { name: user.name.clone(), url }).await        })        .await?;    Ok(        Redirect::back()            .with("status", "If that email has an account, we've sent it a reset link."),    )}

Because a reset token allows changing the user's password, keep it out of unencrypted storage. Queue the email via mail::to(..).queue(..), which encrypts queued mail, rather than placing the reset token in a plain queued job.

Testing

To test a password reset, fake mail, read the token from the queued ResetPasswordEmail, and submit the reset form with it:

rust
use app::models::User;use dust::auth::ResetPasswordEmail;use dust::mail;use dust::testing::prelude::*;#[dust::test]async fn users_can_reset_their_password(app: Application) -> dust::Result<()> {    let mail = mail::fake();    let user = User::factory().create().await?;    app.post("/forgot-password")        .form([("email", user.email.as_str())])        .await        .assert_redirect();    let emails = mail.queued::<ResetPasswordEmail>();    let token = &emails[0].mailable().token;    app.post("/reset-password")        .form([            ("token", token.as_str()),            ("email", user.email.as_str()),            ("password", "new-password"),            ("password_confirmation", "new-password"),        ])        .await        .assert_redirect_to(route!(auth::show_login)?);    Ok(())}