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

  • Apply the mixin to your User model
  • Create password reset tokens
  • Reset passwords using tokens
  • Throttle token creation to prevent abuse

Password reset flows follow a common pattern: the user requests a reset, receives a token via email, and submits the token along with a new password. The withManagedPassword mixin creates the tokens and stores their hashes. Its resetPassword method verifies a token, then locks the user row and saves the new password inside a database transaction.

The mixin adds methods for creating reset tokens, and a static resetPassword method that verifies a token and saves the new password.

The withManagedPassword mixin needs a database table for storing reset tokens and must be applied to your User model.

  1. Create the password reset tokens table

    Section titled "Create the password reset tokens table"

    Generate a migration for the password_reset_tokens table. This table stores hashed reset tokens, each tied to a user.

    Terminal
    node ace make:migration create_password_reset_tokens
    database/migrations/xxxx_create_password_reset_tokens.ts
    import hash from '@adonisjs/core/services/hash'
    
    import { BaseSchema } from '@adonisjs/lucid/schema'
    
    export default class extends BaseSchema {
      protected tableName = 'password_reset_tokens'
    
      async up() {
        this.schema.createTable(this.tableName, (table) => {
          table.increments('id')
          table.integer('tokenable_id').notNullable().unsigned()
          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)
      }
    }
    
  2. Apply the withManagedPassword mixin to your User model using compose.

    app/models/user.ts
    import { UserSchema } from '#database/schema'
    import hash from '@adonisjs/core/services/hash'
    import { compose } from '@adonisjs/core/helpers'
    import { withAuthFinder } from '@adonisjs/auth/mixins/lucid'
    import { withManagedPassword } from '@adonisplus/persona/password'
    
    export default class User extends compose(
      UserSchema,
      withAuthFinder(hash),
      withManagedPassword() 
    ) {}
    

    resetPassword saves the new password as given. The withAuthFinder mixin hashes it before the user is saved.

    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 { withManagedPassword } from '@adonisplus/persona/password'
    
    export default class User extends compose(
      UserSchema,
      withManagedPassword({
        table: 'custom_reset_tokens',
        expiresIn: '2 hours',
      })
    ) {}
    
    tablestring

    The database table used to store password reset tokens.

    Defaults to "password_reset_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'.

    passwordColumnNamestring

    The model property resetPassword writes the new password to.

    Defaults to "password".

When a user requests a password reset, look them up by email and create a reset token. The token value is an opaque string safe to include in a URL.

app/controllers/forgot_password_controller.ts
import User from '#models/user'
import type { HttpContext } from '@adonisjs/core/http'
import { forgotPasswordValidator } from '#validators/user'

export default class ForgotPasswordController {
  async store({ request, response }: HttpContext) {
    const { email } = await request.validateUsing(forgotPasswordValidator)
    const user = await User.findBy('email', email)

    // Returns null when a token was created in the last minute
    const token = user ? await user.createPasswordResetToken(true, '1 min') : null
    if (token) {
      // Send token.value!.release() to the user via email
    }

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

You should enable throttling on user-facing endpoints to prevent a single user from flooding the tokens table. 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.

When the user submits the token along with a new password, pass both to the static resetPassword method. It does not delete the token, which stays valid until it expires. Call clearPasswordResetTokens after a successful reset, as the controller below does.

app/controllers/reset_password_controller.ts
import User from '#models/user'
import type { HttpContext } from '@adonisjs/core/http'
import { resetPasswordValidator } from '#validators/user'

export default class ResetPasswordController {
  async store({ request, response }: HttpContext) {
    const { token, password } = await request.validateUsing(resetPasswordValidator)

    const user = await User.resetPassword(token, password, { redirectTo: '/forgot-password' })
    await user.clearPasswordResetTokens()

    return response.redirect('/login')
  }
}

If the token is invalid or expired, or the user no longer exists, the method throws E_INVALID_PASSWORD_TOKEN with status 400. Pass the redirectTo option to choose where an HTML request is redirected. See Errors for the response of each request type.

resetPassword throws E_INVALID_PASSWORD_TOKEN with status 400. See Errors for the response of each request type.

The withManagedPassword mixin adds the following to model instances.

createPasswordResetTokenmethod

Creates a password reset token for the user.

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

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

Deletes all password reset tokens for the user. Returns the number of deleted rows.

await user.clearPasswordResetTokens()
passwordResetTokensDbPasswordTokensProvider

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

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

Resets the user's password using a token value string. Runs inside a database transaction. Returns the user instance with the updated password.

Throws E_INVALID_PASSWORD_TOKEN when the token is invalid, expired, or the user is not found.

const resetUser = await User.resetPassword(tokenValue, newPassword)
const redirectedUser = await User.resetPassword(tokenValue, newPassword, { redirectTo: '/login' })