Email Verification
- Introduction
- Setting up verification
- Sending verification links
- Verifying the email
- Requiring a verified email
- Changing a user's email
- Customizing the verification email
- Testing
Introduction
Many web applications require users to confirm their email address before accessing sensitive features or receiving transactional mail. dust-framework can send a signed verification link to the user's inbox, validate it when opened, and protect routes with middleware, while leaving your application in charge of rendering the verification notice page.
Before getting started, configure authentication so users can sign in.
Setting up verification
To enable email verification, derive MustVerifyEmail on your User model. The derive reads the user's address from email and verification timestamp from email_verified_at. New applications include both columns on User and in its migration:
use dust::auth::{Authenticatable, MustVerifyEmail};use dust::model::model;use dust::time::Timestamp;#[model]#[derive(Authenticatable, MustVerifyEmail)]pub struct User { pub id: i64, pub email: String, pub email_verified_at: Option<Timestamp>, // ...}dust-framework sends verification links 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):
use dust::mail::Address;impl From<&User> for Address { fn from(user: &User) -> Self { Address::new(&user.email).with_name(&user.name) }}Email verification requires three routes behind Authenticate: a notice page prompting the user to check their inbox, a route to resend the verification email, and the route that handles clicking the verification link. Throttle the resend and verify routes with separate buckets to prevent inbox flooding and brute-force attempts while allowing users who request a new link to open it immediately:
use dust::auth::Authenticate;use dust::http::middleware::Throttle;route.middleware(Authenticate).group(|route| { route.get("/verify-email", verification::notice); route .post("/verify-email", verification::resend) .middleware(Throttle::per_minute(6).bucket("verification-resend")); route .get("/verify-email/{id}/{hash}", verification::verify) .middleware(Throttle::per_minute(6).bucket("verification-verify"));});| Method | URI | Handler |
|---|---|---|
GET |
/verify-email |
Shows the notice asking the user to check their inbox |
POST |
/verify-email |
Sends a new verification link |
GET |
/verify-email/{id}/{hash} |
Verifies the address behind a signed link |
Each verification link carries the user's ID and a hash of their email address in the {id} and {hash} parameters, so the verification route needs both. To let dust-framework locate the notice page and verification route, mark those two handlers with #[dust::auth::page(..)]:
#[dust::auth::page(verification_notice)]pub async fn notice(user: Authenticated<User>) -> dust::Result<Response> { // ...}#[dust::auth::page(verify_email)]pub async fn verify(verification: EmailVerification<User>) -> dust::Result<Redirect> { // ...}Sending verification links
Send the first link as soon as a user signs up. Take EmailVerification<User> as a handler argument, and pass the new user to send_link. This sign-up handler creates the user, logs them in, and sends the link:
use dust::auth::{Auth, EmailVerification};use dust::hash::Password;use dust::model::create;use dust::prelude::*;#[dust::input]#[validate(anyone)]pub struct SignUp { #[validate(required, max_length(255))] name: String, #[transform(lowercase)] #[validate(required, email, unique(User::email))] email: String, #[validate(required, password, confirmed)] password: Password,}pub async fn sign_up( auth: Auth<User>, verification: EmailVerification<User>, Valid(form): Valid<SignUp>,) -> dust::Result<Redirect> { let user = create!(User { name: &form.name, email: &form.email, password: &form.password, }) .await?; auth.login(&user).await?; verification.send_link(&user).await?; Ok(redirect!(dashboard::show))}send_link queues a VerificationEmail containing a signed link valid for 60 minutes. It does nothing if the user's email is already verified.
Emails get lost and links expire, so the notice page has a form that asks for a new link, which posts to the resend handler. Both handlers send a user who has already verified their email, such as in another tab, on to the page they wanted:
use dust::auth::{EmailVerification, MustVerifyEmail};use dust::prelude::*;#[dust::auth::page(verification_notice)]pub async fn notice(user: Authenticated<User>) -> Response { if user.has_verified_email() { return Redirect::intended(dashboard::show, ()).into_response(); } view("auth.verify-email", data! { email => &user.email }).into_response()}pub async fn resend( user: Authenticated<User>, verification: EmailVerification<User>,) -> dust::Result<Redirect> { if user.has_verified_email() { return Ok(Redirect::intended(dashboard::show, ())); } verification.send_link(&user).await?; Ok(Redirect::back().with("status", "We've sent you a new verification link."))}The notice returns a Response, so that one branch can redirect and the other can render the page.
Verifying the email
When the user opens the link, it runs the handler marked #[dust::auth::page(verify_email)]. Call verify there:
use dust::auth::EmailVerification;use dust::prelude::*;#[dust::auth::page(verify_email)]pub async fn verify(verification: EmailVerification<User>) -> dust::Result<Redirect> { verification.verify().await?; Ok(Redirect::intended(dashboard::show, ()).with("status", "Your email is verified."))}verify checks that the link hasn't been changed or expired, and that it was sent to the logged-in user at their current address. Then it sets the user's email_verified_at to now, and returns the user. A user who opens the same link twice gets the same result.
verify rejects invalid requests in three cases:
- Guests are redirected to the login page; after signing in,
Redirect::intendedreturns them to the verification link. - Expired or tampered links return a
403withInvalidSignature. - Links belonging to another user or an outdated email address return a
403withInvalidVerificationLink.
| Situation | What the user sees |
|---|---|
| A guest opens the link | The login page, then the link is tried again after sign-in. |
| The link is expired or was edited | A 403 InvalidSignature error. |
| The link belongs to another user | A 403 InvalidVerificationLink error. |
| The address was changed after the link was sent | A 403 InvalidVerificationLink error. |
| The address is already verified | The same success redirect; verifying twice is harmless. |
Rather than showing a 403 error page for an expired or invalid link, you can catch InvalidSignature and InvalidVerificationLink right inside the handler and redirect the user back to the verification notice page with a status message:
use dust::auth::{EmailVerification, InvalidVerificationLink};use dust::prelude::*;use dust::url::InvalidSignature;#[dust::auth::page(verify_email)]pub async fn verify(verification: EmailVerification<User>) -> dust::Result<Redirect> { if let Err(error) = verification.verify().await { if error.is::<InvalidSignature>() || error.is::<InvalidVerificationLink>() { return Ok(redirect!(notice).with( "status", "That verification link has expired or is invalid. Please request a new one.", )); } return Err(error); } Ok(Redirect::intended(dashboard::show, ()).with("status", "Your email is verified."))}You may also handle either error globally by registering a custom error renderer.
Requiring a verified email
Some pages, such as billing, should wait until the user has verified their email. The RequireVerifiedEmail middleware lets only those users through. Put it after Authenticate:
use dust::auth::{Authenticate, RequireVerifiedEmail};route.middleware(Authenticate).middleware(RequireVerifiedEmail).group(|route| { route.get("/billing", billing::show);});RequireVerifiedEmail redirects unverified users to your notice page. Once they open the link, Redirect::intended in your verify handler sends them back to the page they originally requested. Requests expecting JSON receive a 403 instead.
If User doesn't derive MustVerifyEmail, RequireVerifiedEmail allows every logged-in user through. To check verification status directly in your own code, call user.has_verified_email():
use dust::auth::MustVerifyEmail;if !user.has_verified_email() { // ...}Changing a user's email
Whenever a user updates their email address, clear email_verified_at in the same update and send a new verification link to the updated address:
use dust::auth::EmailVerification;use dust::model::update;use dust::prelude::*;#[dust::input]#[validate(authenticated)]pub struct UpdateEmail { #[transform(lowercase)] #[validate(required, email)] email: String,}pub async fn update_email( Authenticated(mut user): Authenticated<User>, verification: EmailVerification<User>, Valid(form): Valid<UpdateEmail>,) -> dust::Result<Redirect> { update!(user { email: &form.email, email_verified_at: None }).await?; verification.send_link(&user).await?; Ok(Redirect::back())}Any verification link sent to the previous address becomes invalid immediately because each link is hashed against the user's current email address.
Customizing the verification email
By default, dust-framework sends verification links using the built-in dust::auth::VerificationEmail mailable, which uses the subject "Verify your email address" 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/verify-email.html to resources/views/vendor/dust/auth/verify-email.html in your application and edit it to fit your brand. The template receives url for the signed verification link and minutes for the expiration window.
To send a mailable of your own, build the link with url, and queue your mailable wherever you would call send_link. This VerifyYourEmail mailable greets the user by name, and renders resources/views/mail/verify-your-email.html:
use dust::auth::{EmailVerification, MustVerifyEmail};use dust::mail::{self, Mailable};use dust::prelude::*;#[derive(Mailable)]#[mail(subject = "Verify your email address")]pub struct VerifyYourEmail { pub name: String, pub url: String,}pub async fn resend( user: Authenticated<User>, verification: EmailVerification<User>,) -> dust::Result<Redirect> { if user.has_verified_email() { return Ok(Redirect::intended(dashboard::show, ())); } let url = verification.url(&user)?; mail::to(&user).queue(VerifyYourEmail { name: user.name.clone(), url }).await?; Ok(Redirect::back().with("status", "We've sent you a new verification link."))}Unlike send_link, your own email goes out even to a user who has already verified their email, so check first, as this handler does.
Testing
To test email verification, fake mail, read the signed url from the queued VerificationEmail, and visit it as the user:
use app::models::User;use dust::auth::VerificationEmail;use dust::mail;use dust::testing::prelude::*;#[dust::test]async fn users_can_verify_their_email(app: Application) -> dust::Result<()> { let mail = mail::fake(); let user = User::factory().unverified().create().await?; app.post("/verify-email").acting_as(&user).await.assert_redirect(); let emails = mail.queued::<VerificationEmail>(); let link = &emails[0].mailable().url; app.get(link) .acting_as(&user) .await .assert_redirect_to(route!(dashboard::show)?); Ok(())}The default User factory creates verified users out of the box, so use User::factory().create().await? for verified users and .unverified() when testing unverified accounts.