rodshaffer/laravel-user-verification

Laravel 5.6.* 用户邮箱验证

1.0.0 2018-06-15 15:49 UTC

This package is not auto-updated.

Last update: 2024-09-23 06:35:53 UTC


README

rodshaffer/laravel-user-verification 是一个用于 Laravel 5.6.* 的 PHP 包,用于轻松处理用户验证和验证电子邮件。此包是基于 "Jean Ragouin's" / jrean/laravel-user-verification 包的 6.0 分支修改的克隆版本,并已修改以支持使用 Gravatar 来处理用户头像。例如,验证过程可以重新启动以验证新的电子邮件地址,并且在验证成功后,用户的 Gravatar 将被重新哈希。

此包仅支持 Laravel 5.6。

关于

  • 为注册用户生成并存储验证令牌
  • 发送或排队带有验证令牌链接的电子邮件
  • 处理令牌验证
  • 将用户设置为已验证
  • 重新哈希用户的 Gravatar(如果已启用)
  • 随时重新启动流程

安装

该项目可以通过 Composer 安装。要获取 rodshaffer/laravel-user-verification 的最新版本,请将以下行添加到 composer.json 文件中的 require 块

{
    "require": {
        "rodshaffer/laravel-user-verification": "^1.0"
    }

}

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

或者运行以下命令

composer require rodshaffer/laravel-user-verification

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

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 提供程序的 users 设置中设置的内容来猜测您的 user 表。如果找不到此密钥,则将使用默认的 App\User 来获取表名。

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

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

请注意:当使用 Gravatar 时,代表用户的表必须更新为一个新列,gravatar,为了完成此操作,请使用上述 artisan 命令发布迁移,并通过添加以下内容来自定义迁移。

$table->string('gravatar')->nullable()->default(null);

还请确保将 gravatar 配置值设置为 true

中间件

默认中间件

此包提供了一个可选的中间件,抛出 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

用户电子邮件属性为null或空。

错误视图

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

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

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检查是否已为用户启动验证过程。

将use语句添加到您的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用户验证在MIT许可证(MIT)下授权。