Docs / Security / Resetting Passwords
Resetting Passwords
Introduction
Most web applications provide a way for users to reset their forgotten passwords. Rather than forcing you to re-implement this by hand for every application you create, laraflare provides convenient services for sending password reset links and secure resetting passwords.
Note
Want to get started fast? Install a laraflare application starter kit in a fresh laraflare application. laraflare's starter kits will take care of scaffolding your entire authentication system, including resetting forgotten passwords.
Configuration
Your application's password reset configuration file is stored at config/auth.ts. Be sure to review the options available to you in this file. By default, laraflare is configured to use the database password reset driver.
The password reset driver configuration option defines where password reset data will be stored. laraflare includes two drivers:
database- password reset data is stored in a relational database (D1).cache- password reset data is stored in one of your cache-based stores.
Driver Prerequisites
Database
When using the default database driver, a table must be created to store your application's password reset tokens. Typically, this is included in laraflare's default create_users_table database migration. The table's name is set by the table option of the broker in config/auth.ts (password_reset_tokens by default).
Cache
There is also a cache driver available for handling password resets, which does not require a dedicated database table. Entries are keyed by a SHA-256 hash of the user's email address:
passwords: {
users: {
driver: 'cache',
provider: 'users',
store: 'passwords', // Optional...
expire: 60,
throttle: 60,
},
},
To prevent a call to npx artisan cache:clear from flushing your password reset data, you can optionally specify a separate cache store with the store configuration key. The value should correspond to a store configured in your config/cache.ts configuration value.
Model Preparation
Before using the password reset features of laraflare, your application's User model (app/Models/User.ts) must use the Notifiable mixin. Typically, this mixin is already included on the default User model that is created with new laraflare applications.
Next, verify that your User model implements the CanResetPasswordContract contract. The User model included with the framework already implements this interface, and uses the CanResetPassword mixin to include the methods needed to implement the interface.
Configuring Trusted Hosts
By default, laraflare will respond to all requests it receives regardless of the content of the HTTP request's Host header. In addition, the Host header's value will be used when generating absolute URLs to your application during a web request.
Typically, you should configure your web server or Cloudflare route to only send requests to your application that match a given hostname. However, if you do not have the ability to do that and need to instruct laraflare to only respond to certain hostnames, you may do so by using the trustHosts middleware method in your application's bootstrap/app.ts file. This is particularly important when your application offers password reset functionality.
To learn more about this middleware method, please consult the TrustHosts middleware documentation.
Routing
To properly implement support for allowing users to reset their passwords, we will need to define several routes. First, we will need a pair of routes to handle allowing the user to request a password reset link via their email address. Second, we will need a pair of routes to handle actually resetting the password once the user visits the password reset link that is emailed to them and completes the password reset form.
Requesting the Password Reset Link
The Password Reset Link Request Form
First, we will define the routes that are needed to request password reset links. To get started, we will define a route that returns the screen with the password reset link request form. Your application's screens are Vue components in resources/js/pages (the starter kit has auth/ForgotPassword.vue), so the route returns the props the screen reads:
import { Route } from '@laraflare/framework';
Route.get('/forgot-password', () => ({}))
.middleware('guest')
.name('password.request');
The screen shown for this route should have a form containing an email field, which will allow the user to request a password reset link for a given email address.
Handling the Form Submission
Next, we will define a route that handles the form submission request from the "forgot password" screen. This route will be responsible for validating the email address and sending the password reset request to the corresponding user:
import { back, Password, Route, type Request } from '@laraflare/framework';
Route.post('/forgot-password', async (request: Request) => {
await request.validate({ email: ['required', 'email'] });
const status = await Password.sendResetLink(
request.only('email'),
);
return status === Password.ResetLinkSent
? back().with({ status: __(status) })
: back().withErrors({ email: __(status) });
}).middleware('guest').name('password.email');
Before moving on, let's examine this route in more detail. First, the request's email attribute is validated. Next, we will use laraflare's built-in "password broker" (via the Password facade) to send a password reset link to the user. The password broker will take care of retrieving the user by the given field (in this case, the email address) and sending the user a password reset link via laraflare's built-in notification system.
The sendResetLink method returns a "status" slug. This status may be translated using laraflare's localization helpers in order to display a user-friendly message to the user regarding the status of their request. The translation of the password reset status is determined by your application's lang/{lang}/passwords language file. An entry for each possible value of the status slug is located within the passwords language file.
Note
By default, the laraflare application skeleton does not include the
langdirectory. If you would like to customize laraflare's language files, you may publish them via thelang:publishArtisan command.
You may be wondering how laraflare knows how to retrieve the user record from your application's database when calling the Password facade's sendResetLink method. The laraflare password broker utilizes your authentication system's "user providers" to retrieve database records. The user provider used by the password broker is configured within the passwords configuration object of your config/auth.ts configuration file. To learn more about writing custom user providers, consult the authentication documentation.
Note
When manually implementing password resets, you are required to define the contents of the screens and routes yourself. If you would like scaffolding that includes all necessary authentication and verification logic, check out the laraflare application starter kits.
Resetting the Password
The Password Reset Form
Next, we will define the routes necessary to actually reset the password once the user clicks on the password reset link that has been emailed to them and provides a new password. First, let's define the route that will display the reset password form that is displayed when the user clicks the reset password link. This route will receive a token parameter that we will use later to verify the password reset request:
Route.get('/reset-password/{token}', (token: string) => ({ token }))
.middleware('guest')
.name('password.reset');
The screen shown for this route should display a form containing an email field, a password field, a password_confirmation field, and a hidden token field, which should contain the value of the secret token received by our route.
Handling the Form Submission
Of course, we need to define a route to actually handle the password reset form submission. This route will be responsible for validating the incoming request and updating the user's password in the database:
import {
back,
event,
Password,
PasswordReset,
redirect,
Route,
Str,
type Request,
} from '@laraflare/framework';
import { Hash } from '@laraflare/framework/hashing';
import type { User } from '../app/Models/User';
Route.post('/reset-password', async (request: Request) => {
await request.validate({
token: 'required',
email: ['required', 'email'],
password: ['required', 'min:8', 'confirmed'],
});
const status = await Password.reset(
request.only('email', 'password', 'password_confirmation', 'token'),
async (user: User, password: string) => {
user.forceFill({
password: await Hash.make(password),
}).setRememberToken(Str.random(60));
await user.save();
event(new PasswordReset(user));
},
);
return status === Password.PasswordReset
? redirect().route('login').with('status', __(status))
: back().withErrors({ email: [__(status)] });
}).middleware('guest').name('password.update');
Before moving on, let's examine this route in more detail. First, the request's token, email, and password attributes are validated. Next, we will use laraflare's built-in "password broker" (via the Password facade) to validate the password reset request credentials.
If the token, email address, and password given to the password broker are valid, the closure passed to the reset method will be invoked. Within this closure, which receives the user instance and the plain-text password provided to the password reset form, we may update the user's password in the database.
The reset method returns a "status" slug. This status may be translated using laraflare's localization helpers in order to display a user-friendly message to the user regarding the status of their request. The translation of the password reset status is determined by your application's lang/{lang}/passwords language file. An entry for each possible value of the status slug is located within the passwords language file. If your application does not contain a lang directory, you may create it using the lang:publish Artisan command.
Before moving on, you may be wondering how laraflare knows how to retrieve the user record from your application's database when calling the Password facade's reset method. The laraflare password broker utilizes your authentication system's "user providers" to retrieve database records. The user provider used by the password broker is configured within the passwords configuration object of your config/auth.ts configuration file. To learn more about writing custom user providers, consult the authentication documentation.
Deleting Expired Tokens
If you are using the database driver, password reset tokens that have expired will still be present within your database. However, you may easily delete these records using the auth:clear-resets Artisan command:
npx artisan auth:clear-resets
If you would like to automate this process, consider adding the command to your application's scheduler:
import { Schedule } from '@laraflare/framework';
Schedule.command('auth:clear-resets').everyFifteenMinutes();
Customization
Reset Link Customization
You may customize the password reset link URL using the createUrlUsing method provided by the ResetPasswordNotification notification class. This method accepts a closure which receives the user instance that is receiving the notification as well as the password reset link token. Typically, you should call this method from the boot method of your application's AppServiceProvider:
import { ResetPasswordNotification, ServiceProvider } from '@laraflare/framework';
import type { User } from '../Models/User';
export class AppServiceProvider extends ServiceProvider {
/**
* Bootstrap any application services.
*/
override boot(): void {
ResetPasswordNotification.createUrlUsing((user: User, token: string) => {
return 'https://example.com/reset-password?token=' + token;
});
}
}
Reset Email Customization
You may easily modify the notification class used to send the password reset link to the user. To get started, define a static resetPasswordNotification method on your User model; the CanResetPassword mixin's sendPasswordResetNotification method calls it with the password reset token and sends the notification it returns. Within this method, you may return any notification class of your own creation. You may use the token to build the password reset URL of your choice and pass it to your notification:
import { ResetPasswordNotification } from '../Notifications/ResetPasswordNotification';
/**
* The notification that sends a password reset link to the user.
*/
static resetPasswordNotification(token: string) {
const url = 'https://example.com/reset-password?token=' + token;
return new ResetPasswordNotification(url);
}
If you only want to change the mail message, you may instead call ResetPasswordNotification.toMailUsing from the same boot method with a closure that receives the user and the token and returns a MailMessage.