# Password management

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

## Overview

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.

## Setup

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

::steps

### 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.

```bash
node ace make:migration create_password_reset_tokens
```

```ts [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)
  }
}

```

### Apply the mixin
Apply the `withManagedPassword` mixin to your User model using `compose`.

```ts [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' // [!code ++]

export default class User extends compose(
  UserSchema,
  withAuthFinder(hash),
  withManagedPassword() // [!code ++]
) {}

```

`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.

```ts [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,
  // [!code ++:4]
  withManagedPassword({
    table: 'custom_reset_tokens',
    expiresIn: '2 hours',
  })
) {}

```

::::field-group

:::field{name="table" type="string"}
The database table used to store password reset tokens.

Defaults to `"password_reset_tokens"`.
:::

:::field{name="tokenSecretLength" type="number"}
The length of the cryptographically secure random string used as the token secret.

Defaults to `40`.
:::

:::field{name="expiresIn" type="string | 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'`.
:::

:::field{name="passwordColumnName" type="string"}
The model property `resetPassword` writes the new password to.

Defaults to `"password"`.
:::

::::


::

## Creating reset tokens

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.

```ts [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`.

## Resetting the password

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.

```ts [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](/docs/packages/persona/introduction#errors) for the response of each request type.

## Errors

`resetPassword` throws `E_INVALID_PASSWORD_TOKEN` with status 400. See [Errors](/docs/packages/persona/introduction#errors) for the response of each request type.

## Instance properties and methods

The `withManagedPassword` mixin adds the following to model instances.

::::field-group

:::field{name="createPasswordResetToken" type="method"}
Creates a password reset token for the user.

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

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

:::

:::field{name="clearPasswordResetTokens" type="method"}
Deletes all password reset tokens for the user. Returns the number of deleted rows.

```ts
await user.clearPasswordResetTokens()
```

:::

::::

## Static properties and methods

::::field-group

:::field{name="passwordResetTokens" type="DbPasswordTokensProvider"}
The token provider instance attached to the model. You can use it directly for lower-level token operations.

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

:::

:::field{name="resetPassword" type="static 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.

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

:::

::::
