This guide covers the withManagedEmail mixin from @adonisplus/persona/email. You will learn how to:

  • Apply the mixin and understand the two-column email pattern
  • Create users with unverified email addresses
  • Verify emails using cryptographic tokens
  • Handle email change requests safely
  • Throttle token creation to prevent abuse

Your application must verify that a user owns the email address they signed up with. It must also let users change their email later without losing access to their account.

The withManagedEmail mixin uses a two-column email pattern. Your users table stores two values: a verified email (the primary address) and an unverified_email (an address awaiting verification). The two values tell the state of the account.

  • When email equals unverified_email, the account is inactive. The user signed up but has not verified their address yet.
  • When unverified_email is null, the account is active. The primary email is verified and there is no pending change.
  • When unverified_email differs from email, the user has requested an email change. The primary address stays intact until the new one is verified.

The withManagedEmail mixin needs database tables for storing the pending email and verification tokens, and must be applied to your User model.

  1. Add the unverified email column to users

    Section titled "Add the unverified email column to users"

    Generate a migration to add an unverified_email column to your existing users table. This column stores a pending email address awaiting verification.

    Terminal
    node ace make:migration add_unverified_email_to_users --alter=users
    database/migrations/xxxx_add_unverified_email_to_users.ts
    import { BaseSchema } from '@adonisjs/lucid/schema'
    
    export default class extends BaseSchema {
      protected tableName = 'users'
    
      async up() {
        if (await this.schema.hasColumn(this.tableName, 'unverified_email')) {
          return
        }
        this.schema.alterTable(this.tableName, (table) => {
          table.string('unverified_email', 254).nullable().after('email').index()
        })
      }
    
      async down() {
        this.schema.alterTable(this.tableName, (table) => {
          table.dropColumn('unverified_email')
        })
      }
    }
    
  2. Create the email verification tokens table

    Section titled "Create the email verification tokens table"

    Generate a migration for the email_verification_tokens table. This table stores hashed verification tokens, each tied to a user and an email address.

    Terminal
    node ace make:migration create_email_verification_tokens
    database/migrations/xxxx_create_email_verification_tokens.ts
    import hash from '@adonisjs/core/services/hash'
    
    import { BaseSchema } from '@adonisjs/lucid/schema'
    
    export default class extends BaseSchema {
      protected tableName = 'email_verification_tokens'
    
      async up() {
        this.schema.createTable(this.tableName, (table) => {
          table.increments('id')
          table.integer('tokenable_id').notNullable().unsigned()
          table.string('email').notNullable()
          table.string('hash', 80).notNullable()
          table.timestamp('created_at', { precision: 6, useTz: true }).notNullable()
          table.timestamp('expires_at', { precision: 6, useTz: true }).nullable()
        })
      }
    
      async down() {
        this.schema.dropTable(this.tableName)
      }
    }
    
  3. Apply the withManagedEmail mixin to your User model using compose.

    app/models/user.ts
    import { UserSchema } from '#database/schema'
    import { compose } from '@adonisjs/core/helpers'
    import { withManagedEmail } from '@adonisplus/persona/email'
    
    export default class User extends compose(
      UserSchema,
      withManagedEmail() 
    ) {}
    

    You can customize the token provider by passing a config object.

    app/models/user.ts
    import { UserSchema } from '#database/schema'
    import { compose } from '@adonisjs/core/helpers'
    import { withManagedEmail } from '@adonisplus/persona/email'
    
    export default class User extends compose(
      UserSchema,
      withManagedEmail({
        table: 'custom_email_tokens',
        expiresIn: '2 hours',
      })
    ) {}
    
    tablestring

    The database table used to store email verification tokens.

    Defaults to "email_verification_tokens".

    tokenSecretLengthnumber

    The length of the cryptographically secure random string used as the token secret.

    Defaults to 40.

    expiresInstring | number

    How long tokens remain valid. Accepts a number in seconds or a time expression string like '1 day' or '2 hours'.

    Defaults to '1 day'.

When you create a new user, set both email and unverifiedEmail to the same value. This marks the account as inactive until the email is verified.

Warning

You must normalize email addresses to lowercase before passing them to the model. The module stores and compares emails exactly as given. If one user signs up with Alice@example.com and another with alice@example.com, a case-sensitive collation (the PostgreSQL default) stores them as two different addresses.

Per RFC 5321, the local part of an email address is technically case-sensitive. In practice, no major email provider enforces this. Lowercasing on input is the industry standard.

app/controllers/signup_controller.ts
import User from '#models/user'
import db from '@adonisjs/lucid/services/db'
import type { HttpContext } from '@adonisjs/core/http'
import { signupValidator } from '#validators/user'

export default class SignupController {
  async store({ request, response }: HttpContext) {
    const { email, password } = await request.validateUsing(signupValidator)

    const token = await db.transaction(async (trx) => {
      const user = await User.create({ email, unverifiedEmail: email, password }, { client: trx })
      return user.createEmailVerificationToken()
    })

    // Send token.value!.release() to the user via email
    return response.redirect('/login')
  }
}

user.hasInactiveAccount is true while email equals unverifiedEmail, and user.hasActiveAccount is its opposite.

Warning

An unverified signup keeps its address in the unique users.email column. Nobody else can sign up with that address until you delete the account. Delete accounts that have stayed inactive (hasInactiveAccount) for a set time, for example from a scheduled command.

When the user clicks the verification link, pass the token string to the static verifyEmail method. This method verifies the token, checks that no other user already owns the email, and switches the user's email inside a database transaction.

app/controllers/email_verification_notifications_controller.ts
import type { HttpContext } from '@adonisjs/core/http'

export default class EmailVerificationNotificationsController {
  async store({ auth, response }: HttpContext) {
    const token = await auth.getUserOrFail().createEmailVerificationToken(true, '1 min')
    if (token) {
      // Send token.value!.release() to the user via email
    }
    return response.redirect().back()
  }
}

If verification fails (invalid token, expired token, email already taken, or user not found), the method throws E_INVALID_EMAIL_TOKEN with status 400. The message is the same for every cause, to prevent information leakage. Pass the redirectTo option to choose where an HTML request is redirected, as the controller above does. See Errors for the response of each request type.

verifyEmail does not delete the token. Call clearEmailVerificationTokens after a successful verification, and before issuing a new token.

When an existing user changes their email, the request has one of three outcomes.

  1. The new email is the current one. Nothing changes (SKIPPED).
  2. The user changed back to their verified email. Clear the pending change and delete all tokens (REVERTED).
  3. The email is new. Update the pending email, delete the old tokens, and issue a new verification token (ISSUED_TOKEN).

The withEmail method knows the account state. For an inactive account, it sets both email and unverifiedEmail. For an active account, it sets only unverifiedEmail, which keeps the verified address until the new one is verified. Run the update inside lockForUpdate. The lock prevents two requests from changing the email at the same time.

app/controllers/account_email_controller.ts
import type { HttpContext } from '@adonisjs/core/http'
import { changeEmailValidator } from '#validators/user'

export default class AccountEmailController {
  async update({ auth, request, response }: HttpContext) {
    const { email: newEmail } = await request.validateUsing(changeEmailValidator)

    const result = await auth.getUserOrFail().lockForUpdate(async (freshUser) => {
      if (!freshUser.hasEmailChanged(newEmail)) {
        return { type: 'SKIPPED' } as const
      }

      if (freshUser.hasEmailReverted(newEmail)) {
        freshUser.unverifiedEmail = null
        await freshUser.save()
        await freshUser.clearEmailVerificationTokens()
        return { type: 'REVERTED' } as const
      }

      await freshUser.withEmail(newEmail).save()
      await freshUser.clearEmailVerificationTokens()
      return { type: 'ISSUED_TOKEN', token: await freshUser.createEmailVerificationToken() } as const
    })

    if (result.type === 'ISSUED_TOKEN') {
      // Send result.token.value!.release() to the new address via email
    }

    return response.redirect().back()
  }
}

When resending verification emails, use the shouldThrottle parameter to prevent abuse. The first argument enables throttling. The second sets the throttle window (defaults to 60 seconds). When a token was created within the window, the method returns null instead of creating a new one.

// Returns null if a token was created within the throttle window
const resentToken = await user.createEmailVerificationToken(true, '1 min')

if (resentToken) {
  // Send resentToken.value!.release() to the user via email
}

You should always enable throttling on user-facing endpoints. Without it, every call creates a new token, which lets a single user flood the tokens table.

verifyEmail throws E_INVALID_EMAIL_TOKEN with status 400. See Errors for the response of each request type.

The withManagedEmail mixin adds the following to model instances.

emailstring
The verified primary email address. Mapped to the email database column.
unverifiedEmailstring | null
The pending email address awaiting verification. Mapped to the unverified_email database column. null when there is no pending change.
hasActiveAccountboolean
true when the primary email is verified (unverifiedEmail is null or differs from email).
hasInactiveAccountboolean
true when the primary email has not been verified (email equals unverifiedEmail).
createEmailVerificationTokenmethod

Creates a verification token for the user's unverifiedEmail. Throws a RuntimeException if unverifiedEmail is null.

// Without throttling
const token = await user.createEmailVerificationToken()

// With throttling (returns null within the window)
const throttledToken = await user.createEmailVerificationToken(true, '1 min')
clearEmailVerificationTokensmethod

Deletes all email verification tokens for the user. Returns the number of deleted rows.

await user.clearEmailVerificationTokens()
hasEmailChangedmethod

Returns true if the provided email differs from the current pending email (or the primary email when no pending change exists).

user.hasEmailChanged('new@example.com')
hasEmailRevertedmethod

Returns true if the user is reverting back to their verified primary email. Only true when unverifiedEmail exists and the new email matches email.

user.hasEmailReverted('original@example.com')
withEmailmethod

Updates the local email and unverifiedEmail attributes. For inactive accounts, updates both columns. For active accounts, only updates unverifiedEmail. Returns this for chaining.

await user.withEmail('new@example.com').save()
switchEmailmethod

Sets the primary email and clears unverifiedEmail to null. Used internally by verifyEmail. Returns this for chaining.

user.switchEmail('verified@example.com')
emailVerificationTokensDbEmailTokensProvider

The token provider instance attached to the model. You can use it directly for lower-level token operations.

const tokens = await User.emailVerificationTokens.all(user)
const lastCreated = await User.emailVerificationTokens.lastCreatedAt(user)
await User.emailVerificationTokens.delete(user, tokenId)
verifyEmailstatic method

Verifies an email using a token value string. Runs inside a database transaction. Returns the user instance with the updated email.

Throws E_INVALID_EMAIL_TOKEN when the token is invalid, expired, the email is already taken by another user, or the user no longer has a matching unverifiedEmail.

const verifiedUser = await User.verifyEmail(tokenValue)
const redirectedUser = await User.verifyEmail(tokenValue, { redirectTo: '/login' })