”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 掌握 Laravel 密码重置自定义:综合指南

掌握 Laravel 密码重置自定义:综合指南

发布于2024-11-08
浏览:629

Mastering Laravel Password Reset Customization: A Comprehensive Guide

Introduction

Password reset functionality is a critical component of any modern web application. While Laravel provides a robust out-of-the-box solution, there are times when you need to tailor this process to meet specific requirements or enhance user experience. In this tutorial, we'll dive deep into customizing Laravel's password reset workflow, covering everything from basic modifications to advanced techniques.

A Brief History of Laravel Authentication

Before we delve into customization, let's take a quick trip down memory lane to understand how Laravel's authentication solutions have evolved:

  1. Laravel UI: The first iteration of a complete auth solution in Laravel, which served the community well for years.
  2. Laravel Breeze: Born out of the growing popularity of Tailwind CSS, Breeze offered a minimal, lightweight, and modern authentication scaffolding.
  3. Laravel Jetstream: For those needing more advanced features, Jetstream was introduced, covering a wide range of authentication including 2FA and team management functionalities.
  4. Laravel Fortify: A headless authentication backend that can be used with any frontend, providing flexibility for developers to implement their own UI.

Understanding Laravel's Password Reset Flow

Laravel's password reset process typically involves the following steps:

  1. User requests a password reset
  2. A token is generated and stored
  3. An email is sent to the user with a reset link (signed URL)
  4. User clicks the link and enters a new password
  5. The password is updated, and the token is invalidated

While this flow works well for most applications, you might want to customize various aspects of this process to better suit your needs.

What We're Building

In this tutorial, we'll create a bare Laravel SaaS (minimal) application with a customized password reset flow. We'll cover:

  • Setting up a fresh Laravel application with Breeze
  • Customizing the password reset URL
  • Modifying the password reset email content
  • Adding a success notification after password reset
  • Implementing and customizing automated tests for our changes

Getting Started

Let's begin by setting up a new Laravel application:

composer create-project laravel/laravel password-reset-demo
cd password-reset-demo

Before we proceed, let's initialize Git for version control:

git init
git add .
git commit -m "Initial commit"

Now, let's install Laravel Breeze to get the basic authentication scaffolding:

composer require laravel/breeze --dev
php artisan breeze:install

When prompted, choose the stack that best fits your needs. For this tutorial, we'll use Livewire:

php artisan breeze:install

  Which Breeze stack would you like to install?
❯ livewire

  Would you like dark mode support? (yes/no) [no]
❯ no

  Which testing framework do you prefer? [PHPUnit]
❯ Pest

After installation, let's commit our changes:

git add .
git commit -m "Add Authentication and Pages"

Now, set up your database and run migrations:

php artisan migrate

Install and compile your frontend assets:

npm install
npm run dev

At this point, we have a basic Laravel application with authentication functionality. Let's run the tests to ensure everything is working as expected:

php artisan test

You should see all tests passing, giving us a green light to proceed with our customizations.

Customizing the Password Reset URL

By default, Laravel (using Breeze) uses a standard URL for password reset (/reset-password). Let's customize this in our AppServiceProvider:

 $token,
                'email' => $user->getEmailForPasswordReset(),
            ], false));
        });
    }
}

This customization allows you to modify the reset URL structure, add additional parameters, or even point to a completely different domain if needed. For example, you could change it to:

return "https://account.yourdomain.com/reset-password?token={$token}&email={$user->getEmailForPasswordReset()}";

Modifying the Password Reset Email

Next, let's customize the content of the password reset email. We'll do this by adding to our AppServiceProvider:

use Illuminate\Notifications\Messages\MailMessage;

// ...

public function boot(): void
{
    // ... previous customizations

    ResetPassword::toMailUsing(function (User $user, string $token) {
        $url = url(route('password.reset', [
            'token' => $token,
            'email' => $user->getEmailForPasswordReset(),
        ], false));

        return (new MailMessage)
            ->subject(config('app.name') . ': ' . __('Reset Password Request'))
            ->greeting(__('Hello!'))
            ->line(__('You are receiving this email because we received a password reset request for your account.'))
            ->action(__('Reset Password'), $url)
            ->line(__('This password reset link will expire in :count minutes.', ['count' => config('auth.passwords.' . config('auth.defaults.passwords') . '.expire')]))
            ->line(__('If you did not request a password reset, no further action is required.'))
            ->salutation(__('Regards,') . "\n" . config('app.name') . " Team");
    });
}

Note: The __() function is a helper for localization, allowing easy translation of strings in your application.

Adding a Password Reset Success Notification

To enhance user experience and security, let's add a notification that's sent after a successful password reset. First, create a new notification:

php artisan make:notification PasswordResetSuccessfullyNotification

Edit the newly created notification:

subject('Password Reset Successful')
            ->greeting('Hello!')
            ->line('Your password has been successfully reset.')
            ->line('If you did not reset your password, please contact support immediately.')
            ->action('Login to Your Account', url('/login'))
            ->line('Thank you for using our application!');
    }
}

Now, create a listener for the PasswordReset event:

php artisan make:listener SendPasswordResetSuccessfullyNotification --event=PasswordReset

Update the listener:

user->notify(new PasswordResetSuccessfullyNotification());
    }
}

Remember to register this listener in your EventServiceProvider.

Testing Our Customizations

Testing is crucial to ensure our customizations work as expected. Update the existing password reset test in tests/Feature/Auth/PasswordResetTest.php:

create();

        $this->post('/forgot-password', ['email' => $user->email]);

        Notification::assertSentTo($user, ResetPassword::class, function ($notification) use ($user) {
            $response = $this->get($notification->toMail($user)->actionUrl);
            $this->assertStringContainsString('Reset Password', $response->getContent());
            return true;
        });
    }

    public function test_password_can_be_reset_with_valid_token(): void
    {
        Notification::fake();

        $user = User::factory()->create();

        $this->post('/forgot-password', ['email' => $user->email]);

        Notification::assertSentTo($user, ResetPassword::class, function ($notification) use ($user) {
            $token = $notification->token;

            $response = $this->post('/reset-password', [
                'token' => $token,
                'email' => $user->email,
                'password' => 'new-password',
                'password_confirmation' => 'new-password',
            ]);

            $response->assertSessionHasNoErrors();

            Notification::assertSentTo($user, PasswordResetSuccessfullyNotification::class);

            return true;
        });
    }

    public function test_reset_password_email_contains_custom_content(): void
    {
        Notification::fake();

        $user = User::factory()->create();

        $this->post('/forgot-password', ['email' => $user->email]);

        Notification::assertSentTo($user, ResetPassword::class, function ($notification) use ($user) {
            $mailMessage = $notification->toMail($user);
            $this->assertStringContainsString('Hello!', $mailMessage->greeting);
            $this->assertStringContainsString('Regards,', $mailMessage->salutation);
            return true;
        });
    }
}

Conclusion

Customizing Laravel's password reset workflow allows you to create a more tailored and user-friendly experience for your application. We've covered how to modify the reset URL, customize the email content, add a success notification, and ensure everything works through automated testing.

Remember, while customization can be powerful, it's essential to maintain security best practices throughout the process. Always validate user input, use secure token generation and storage methods, and follow Laravel's security recommendations.

Some additional considerations for further improvements:

  1. Implement rate limiting on password reset requests to prevent abuse.
  2. Add logging for successful and failed password reset attempts for security auditing.
  3. Consider implementing multi-channel notifications (e.g., SMS, push notifications) for critical security events like password resets.
  4. Regularly review and update your password policies to align with current security best practices.

For more advanced topics and Laravel insights, check out the official Laravel documentation and stay tuned to the Laravel community resources for more in-depth tutorials and best practices.

Happy coding, and may your Laravel applications be ever secure and user-friendly!

版本声明 本文转载于:https://dev.to/alphaolomi/mastering-laravel-password-reset-customization-a-comprehensive-guide-24p3?1如有侵犯,请联系[email protected]删除
最新教程 更多>
  • 插入数据时如何修复“常规错误:2006 MySQL 服务器已消失”?
    插入数据时如何修复“常规错误:2006 MySQL 服务器已消失”?
    插入记录时如何解决“一般错误:2006 MySQL 服务器已消失”介绍:将数据插入 MySQL 数据库有时会导致错误“一般错误:2006 MySQL 服务器已消失”。当与服务器的连接丢失时会出现此错误,通常是由于 MySQL 配置中的两个变量之一所致。解决方案:解决此错误的关键是调整wait_tim...
    编程 发布于2024-12-27
  • 如何使用 MySQL 查找今天生日的用户?
    如何使用 MySQL 查找今天生日的用户?
    如何使用 MySQL 识别今天生日的用户使用 MySQL 确定今天是否是用户的生日涉及查找生日匹配的所有行今天的日期。这可以通过一个简单的 MySQL 查询来实现,该查询将存储为 UNIX 时间戳的生日与今天的日期进行比较。以下 SQL 查询将获取今天有生日的所有用户: FROM USERS ...
    编程 发布于2024-12-27
  • HTML 格式标签
    HTML 格式标签
    HTML 格式化元素 **HTML Formatting is a process of formatting text for better look and feel. HTML provides us ability to format text without us...
    编程 发布于2024-12-27
  • 在 Go 中使用 WebSocket 进行实时通信
    在 Go 中使用 WebSocket 进行实时通信
    构建需要实时更新的应用程序(例如聊天应用程序、实时通知或协作工具)需要一种比传统 HTTP 更快、更具交互性的通信方法。这就是 WebSockets 发挥作用的地方!今天,我们将探讨如何在 Go 中使用 WebSocket,以便您可以向应用程序添加实时功能。 在这篇文章中,我们将介绍: WebSoc...
    编程 发布于2024-12-27
  • 除了“if”语句之外:还有哪些地方可以在不进行强制转换的情况下使用具有显式“bool”转换的类型?
    除了“if”语句之外:还有哪些地方可以在不进行强制转换的情况下使用具有显式“bool”转换的类型?
    无需强制转换即可上下文转换为 bool您的类定义了对 bool 的显式转换,使您能够在条件语句中直接使用其实例“t”。然而,这种显式转换提出了一个问题:“t”在哪里可以在不进行强制转换的情况下用作 bool?上下文转换场景C 标准指定了四种值可以根据上下文转换为的主要场景bool:语句:if、whi...
    编程 发布于2024-12-26
  • 如何修复 macOS 上 Django 中的“配置不正确:加载 MySQLdb 模块时出错”?
    如何修复 macOS 上 Django 中的“配置不正确:加载 MySQLdb 模块时出错”?
    MySQL配置不正确:相对路径的问题在Django中运行python manage.py runserver时,可能会遇到以下错误:ImproperlyConfigured: Error loading MySQLdb module: dlopen(/Library/Python/2.7/site-...
    编程 发布于2024-12-26
  • 大批
    大批
    方法是可以在对象上调用的 fns 数组是对象,因此它们在 JS 中也有方法。 slice(begin):将数组的一部分提取到新数组中,而不改变原始数组。 let arr = ['a','b','c','d','e']; // Usecase: Extract till index p...
    编程 发布于2024-12-26
  • 尽管代码有效,为什么 POST 请求无法捕获 PHP 中的输入?
    尽管代码有效,为什么 POST 请求无法捕获 PHP 中的输入?
    解决 PHP 中的 POST 请求故障在提供的代码片段中:action=''而不是:action="<?php echo $_SERVER['PHP_SELF'];?>";?>"检查 $_POST数组:表单提交后使用 var_dump 检查 $_POST 数...
    编程 发布于2024-12-26
  • Bootstrap 4 Beta 中的列偏移发生了什么?
    Bootstrap 4 Beta 中的列偏移发生了什么?
    Bootstrap 4 Beta:列偏移的删除和恢复Bootstrap 4 在其 Beta 1 版本中引入了重大更改柱子偏移了。然而,随着 Beta 2 的后续发布,这些变化已经逆转。从 offset-md-* 到 ml-auto在 Bootstrap 4 Beta 1 中, offset-md-*...
    编程 发布于2024-12-26
  • 如何在 PHP 中组合两个关联数组,同时保留唯一 ID 并处理重复名称?
    如何在 PHP 中组合两个关联数组,同时保留唯一 ID 并处理重复名称?
    在 PHP 中组合关联数组在 PHP 中,将两个关联数组组合成一个数组是一项常见任务。考虑以下请求:问题描述:提供的代码定义了两个关联数组,$array1和$array2。目标是创建一个新数组 $array3,它合并两个数组中的所有键值对。 此外,提供的数组具有唯一的 ID,而名称可能重合。要求是构...
    编程 发布于2024-12-26
  • 为什么 C 和 C++ 忽略函数签名中的数组长度?
    为什么 C 和 C++ 忽略函数签名中的数组长度?
    将数组传递给 C 和 C 中的函数 问题:为什么 C 和C 编译器允许在函数签名中声明数组长度,例如 int dis(char a[1])(当它们不允许时)强制执行?答案:C 和 C 中用于将数组传递给函数的语法是历史上的奇怪现象,它允许将指针传递给第一个元素详细说明:在 C 和 C 中,数组不是通...
    编程 发布于2024-12-26
  • 如何删除 MySQL 中的重音符号以改进自动完成搜索?
    如何删除 MySQL 中的重音符号以改进自动完成搜索?
    在 MySQL 中删除重音符号以实现高效的自动完成搜索管理大型地名数据库时,确保准确和高效至关重要数据检索。使用自动完成功能时,地名中的重音可能会带来挑战。为了解决这个问题,一个自然的问题出现了:如何在 MySQL 中删除重音符号以改进自动完成功能?解决方案在于为数据库列使用适当的排序规则设置。通过...
    编程 发布于2024-12-26
  • 如何在MySQL中实现复合外键?
    如何在MySQL中实现复合外键?
    在 SQL 中实现复合外键一种常见的数据库设计涉及使用复合键在表之间建立关系。复合键是多个列的组合,唯一标识表中的记录。在这个场景中,你有两个表,tutorial和group,你需要将tutorial中的复合唯一键链接到group中的字段。根据MySQL文档,MySQL支持外键映射到复合键。但是,要...
    编程 发布于2024-12-26
  • 为什么我的 JComponent 隐藏在 Java 的背景图像后面?
    为什么我的 JComponent 隐藏在 Java 的背景图像后面?
    调试背景图像隐藏的 JComponent在 Java 应用程序中使用 JComponent(例如 JLabels)时,必须确保正确的行为和可见度。如果遇到组件隐藏在背景图像后面的问题,请考虑以下方法:1。正确设置组件透明度:确保背景面板是透明的,以允许底层组件透过。使用setOpaque(false...
    编程 发布于2024-12-26
  • 如何在 PHP 中转换所有类型的智能引号?
    如何在 PHP 中转换所有类型的智能引号?
    在 PHP 中转换所有类型的智能引号智能引号是用于代替常规直引号(' 和 ")的印刷标记。它们提供了更精致和然而,软件应用程序通常会在不同类型的智能引号之间进行转换,从而导致不一致。智能引号中的挑战转换转换智能引号的困难在于用于表示它们的各种编码和字符,不同的操作系统和软件程序采用...
    编程 发布于2024-12-26

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3