jrean/laravel-user-verification

为 Laravel 的用户邮箱验证


README

jrean/laravel-user-verification 是一个针对 Laravel 5.、6.、7.、8.、9.、10. & 11.* 开发的 PHP 包,用于轻松处理用户验证和验证邮箱。

Latest Stable Version Total Downloads License

版本

此包符合 Laravel 11.0 规范。

关于

  • 为注册用户生成和存储验证令牌
  • 发送或排队带有验证令牌链接的电子邮件
  • 处理令牌验证
  • 将用户设置为已验证
  • 随时重新启动进程

目录

安装

此项目可以通过 Composer 安装。要获取 Laravel User Verification 的最新版本,请将以下行添加到 composer.json 文件的 require 块中

{
    "require": {
        "jrean/laravel-user-verification": "dev-master"
    }

}

然后,您需要运行 composer installcomposer update 以下载包并更新自动加载器。

或者运行以下命令

composer require jrean/laravel-user-verification

添加服务提供者和外观/别名

一旦安装了 Laravel User Verification,您需要在 config/app.php 中注册服务提供器。请确保在 RouteServiceProvider 之前添加以下行。

Jrean\UserVerification\UserVerificationServiceProvider::class,

您可以将以下 别名 添加到 config/app.php 中

'UserVerification' => Jrean\UserVerification\Facades\UserVerification::class,

通过运行以下命令发布包配置文件

php artisan vendor:publish --provider="Jrean\UserVerification\UserVerificationServiceProvider" --tag="config"

配置

表示 User 的模型必须实现可认证接口 Illuminate\Contracts\Auth\Authenticatable,这是 Eloquent User 模型的默认值。

迁移

表示用户的表必须更新为两个新列,verifiedverification_token。此更新将由此包中包含的迁移执行。

这两个列必须在存储用户邮箱的同一张表中。请确保您的用户表上还没有这些字段。

要从此包运行迁移,请使用以下命令

php artisan migrate --path="/vendor/jrean/laravel-user-verification/src/resources/migrations"

此包通过检查 auth 提供者用户设置中设置的值来尝试猜测您的 user 表。如果找不到此键,则将使用默认的 App\User 来获取表名。

要自定义迁移,请使用以下命令发布它

php artisan vendor:publish --provider="Jrean\UserVerification\UserVerificationServiceProvider" --tag="migrations"

中间件

默认中间件

此包提供了一个可选的中间件,它抛出 UserNotVerifiedException。有关如何使用异常处理器的更多信息,请参阅 Laravel 文档

要注册默认中间件,请将以下行添加到 app/Http/Kernel.php 文件中的 $routeMiddleware 数组中

protected $routeMiddleware = [
    // …
    'isVerified' => \Jrean\UserVerification\Middleware\IsVerified::class,

在您的路由上应用中间件

Route::group(['middleware' => ['isVerified']], function () {
    // …

自定义中间件

使用以下 artisan 命令创建您自己的自定义中间件

php artisan make:middleware IsVerified

有关中间件更详细的信息,请参阅Laravel 文档

电子邮件

本软件包提供了一种发送包含验证令牌链接的电子邮件的方法。

  • send(AuthenticatableContract $user, $subject, $from = null, $name = null)

默认情况下,软件包将使用在config/mail.php文件中定义的fromname值。

    'from' => ['address' => '', 'name' => ''],

如果您想覆盖这些值,只需设置$from和(可选)$name参数。

有关正确配置电子邮件组件的说明,请参阅Laravel 文档

电子邮件视图

用户将收到一封电子邮件,其中包含链接到getVerification()方法(端点)。视图将接收一个包含用户详情(如验证令牌)的$user变量。

本软件包允许您使用传统的blade视图文件和Markdown。

默认情况下,将加载一个示例电子邮件视图以供您开始使用。

Click here to verify your account: <a href="{{ $link = route('email-verification.check', $user->verification_token) . '?email=' . urlencode($user->email) }}">{{ $link }}</a>

如果您想使用Markdown,请更新config目录中的软件包配置文件user-verification.php,并替换以下内容:

'email' => [
    'type' => 'default',
],

'email' => [
    'type' => 'markdown',
],

如果您想自定义电子邮件视图,请运行以下命令以发布并编辑它们以满足您的需求:

URL必须包含作为参数的验证令牌以及(强制)包含用户电子邮件的查询字符串。

php artisan vendor:publish --provider="Jrean\UserVerification\UserVerificationServiceProvider" --tag="views"

视图将在resources/views/vendor/laravel-user-verification/目录中可用。

错误

本软件包抛出多个异常。您可以使用try/catch语句或依赖Laravel内置的异常处理程序。

  • ModelNotCompliantException

提供的模型实例与该软件包不兼容。它必须实现Illuminate\Contracts\Auth\Authenticatable认证接口。

  • TokenMismatchException

错误的验证令牌。

  • UserIsVerifiedException

指定的用户已经验证。

  • UserNotVerifiedException

指定的用户尚未验证。

  • UserNotFoundException

没有找到给定电子邮件地址的用户。

  • UserHasNoEmailException

用户电子邮件属性为空或不存在。

错误视图

默认情况下,对于验证错误路由/email-verification/error,将加载user-verification.blade.php视图。如果发生错误,用户将被重定向到该路由,并渲染此视图。

要自定义视图,请使用以下命令发布它:

php artisan vendor:publish --provider="Jrean\UserVerification\UserVerificationServiceProvider" --tag="views"

视图将在resources/views/vendor/laravel-user-verification/目录中可用,并可进行自定义。

用法

路由

默认情况下,本软件包提供了两个路由。

Route::get('email-verification/error', 'Auth\RegisterController@getVerificationError')->name('email-verification.error');
Route::get('email-verification/check/{token}', 'Auth\RegisterController@getVerification')->name('email-verification.check');

覆盖包路由

要定义您自己的自定义路由,请将软件包服务提供者调用放在config/app.php文件中的RouteServiceProvider调用之前。

   /*
    * Package Service Providers...
    */
    Jrean\UserVerification\UserVerificationServiceProvider::class,

   /*
    * Application Service Providers...
    */
    // ...
    App\Providers\RouteServiceProvider::class,

然后,在您的路由文件中添加您的自定义路由。

特质

本软件包提供三个(3)特性以快速实现。只有VerifiesUsers特性是必需的,并且包括RedirectsUsers

Jrean\UserVerification\Traits\VerifiesUsers

Jrean\UserVerification\Traits\RedirectsUsers

Jrean\UserVerification\Traits\UserVerification

最后一个特性提供了两个可以添加到User模型中的方法。

  • isVerified检查用户是否被标记为已验证。
  • isPendingVerification检查是否已为用户启动了验证过程。

User模型中添加使用语句,并在类中使用UserVerification

端点

以下两个方法包含在VerifiesUsers特性中,并由默认软件包路由调用。

  • getVerification(Request $request, $token)

处理用户验证。

  • getVerificationError()

如果验证失败,执行某些操作。

API

本软件包公共API提供八个(8)方法。

  • generate(AuthenticatableContract $user)

为指定的用户生成并保存验证令牌。

  • send(AuthenticatableContract $user, $subject = null, $from = null, $name = null)

通过电子邮件发送包含验证令牌的链接。

  • sendQueue(AuthenticatableContract $user, $subject = null, $from = null, $name = null)

将包含验证令牌的链接放入队列并通过电子邮件发送。

  • sendLater($seconds, AuthenticatableContract $user, $subject = null, $from = null, $name = null)

将包含验证令牌的链接通过电子邮件发送,延迟执行。

  • process($email, $token, $userTable)

处理给定电子邮件和令牌的令牌验证。

对于 sendQueuesendLatersendLaterOn 方法,在使用此功能之前,您必须配置您的队列

外观

该软件包提供了一个门面 UserVerification::

属性/属性

为了自定义软件包行为和重定向,您可以实现并自定义六个(6)属性/属性

  • $redirectIfVerified = '/';

如果已验证的用户已通过验证,则重定向到此处。

  • $redirectAfterVerification = '/';

验证令牌验证成功后重定向到此处。

  • $redirectIfVerificationFails = '/email-verification/error';

令牌验证失败后重定向到此处。

  • $verificationErrorView = 'laravel-user-verification::user-verification';

getVerificationError方法返回的视图名称。

  • $verificationEmailView = 'laravel-user-verification::email'

默认电子邮件视图名称。

  • $userTable = 'users';

用于管理用户的默认表名称。

翻译

要自定义翻译,可以使用以下命令将文件发布到您的 resources/lang/vendor 文件夹

php artisan vendor:publish --provider="Jrean\UserVerification\UserVerificationServiceProvider" --tag="translations"

这将把 laravel-user-verification/en/user-verification.php 添加到您的软件包文件夹中。通过创建新的语言文件夹,如 defr,并将包含翻译的 user-verification.php 放入其中,您可以添加其他语言的翻译。您可以在Laravel 文档中找到有关本地化的更多信息。

自动登录

如果您希望在验证过程后自动登录用户,请更新配置目录中的软件包配置文件 user-verification.php 并替换以下内容

'auto-login' => false,

'auto-login' => true,

自定义

您可以通过覆盖/覆盖公共方法和属性/属性来自定义软件包行为。深入了解源代码。

指南

此软件包不需要用户登录即可执行验证。您可以根据自己的需求自由实现。

此软件包希望在提供预设路径的同时让您发挥创意。以下指南假定您已根据此文档以及之前的记录步骤配置了 Laravel 以及创建了并迁移了迁移。

请注意,默认情况下,Laravel 的行为是在注册步骤之后返回已验证的用户。

示例

以下代码示例旨在展示一个快速而基本的实现,遵循 Laravel 逻辑。您可以自由地实现您想要的方式。强烈建议您阅读并理解 Laravel 实现注册/验证的原理。

  • 定义电子邮件视图。

编辑 app\Http\Controllers\Auth\RegisterController.php 文件。

  • 导入 VerifiesUsers 特性(必需)
  • 覆盖并自定义 VerifiesUsers 特性包含的 RedirectsUsers 特性中的重定向属性/属性路径。(非必需)
  • 覆盖构造函数(非必需)
  • 覆盖 register() 方法(必需)
    namespace App\Http\Controllers\Auth;

    use App\User;
    use App\Http\Controllers\Controller;
    use Illuminate\Support\Facades\Validator;
    use Illuminate\Foundation\Auth\RegistersUsers;

    use Illuminate\Http\Request;
    use Illuminate\Auth\Events\Registered;
    use Jrean\UserVerification\Traits\VerifiesUsers;
    use Jrean\UserVerification\Facades\UserVerification;

    class RegisterController extends Controller
    {
        /*
        |--------------------------------------------------------------------------
        | Register Controller
        |--------------------------------------------------------------------------
        |
        | This controller handles the registration of new users as well as their
        | validation and creation. By default this controller uses a trait to
        | provide this functionality without requiring any additional code.
        |
        */

        use RegistersUsers;

        use VerifiesUsers;

        /**
         * Where to redirect users after registration.
         *
         * @var string
         */
        protected $redirectTo = '/home';

        /**
         * Create a new controller instance.
         *
         * @return void
         */
        public function __construct()
        {
            // Based on the workflow you need, you may update and customize the following lines.

            $this->middleware('guest', ['except' => ['getVerification', 'getVerificationError']]);
        }

        /**
         * Get a validator for an incoming registration request.
         *
         * @param  array  $data
         * @return \Illuminate\Contracts\Validation\Validator
         */
        protected function validator(array $data)
        {
            return Validator::make($data, [
                'name' => 'required|max:255',
                'email' => 'required|email|max:255|unique:users',
                'password' => 'required|min:6|confirmed',
            ]);
        }

        /**
         * Create a new user instance after a valid registration.
         *
         * @param  array  $data
         * @return User
         */
        protected function create(array $data)
        {
            return User::create([
                'name' => $data['name'],
                'email' => $data['email'],
                'password' => bcrypt($data['password']),
            ]);
        }

        /**
         * Handle a registration request for the application.
         *
         * @param  \Illuminate\Http\Request  $request
         * @return \Illuminate\Http\Response
         */
        public function register(Request $request)
        {
            $this->validator($request->all())->validate();

            $user = $this->create($request->all());

            event(new Registered($user));

            $this->guard()->login($user);

            UserVerification::generate($user);

            UserVerification::send($user, 'My Custom E-mail Subject');

            return $this->registered($request, $user)
                            ?: redirect($this->redirectPath());
        }
    }

在此阶段,注册后,会向用户发送电子邮件。点击电子邮件中的链接,用户将通过令牌进行验证。

如果您想要针对已验证用户执行验证,您必须更新中间件异常,允许 getVerificationgetVerificationError 路由被访问。

$this->middleware('guest', ['except' => ['getVerification', 'getVerificationError']]);

随时重新启动进程

如果您想重新生成并发送验证令牌,可以使用以下两行代码实现:

UserVerification::generate($user);
UserVerification::send($user, 'My Custom E-mail Subject');

使用 generate 方法将为指定用户生成新的令牌并将 verified 列设置为 0。使用 send 方法将向用户发送新的电子邮件。

Laravel Spark

关于 Laravel Spark 集成,请参考 Ian Fagg 的这篇文章:Laravel Spark 用户验证

贡献

请随意评论、贡献和帮助。1 PR = 1 特性。

许可证

Laravel 用户验证遵循 MIT 许可证 (MIT)