assada/laravel-user-verification

Laravel 用户邮箱验证


README

jrean/laravel-user-verification 是一个为 Laravel 5.* & 6.* & 7.* 构建的 PHP 包,用于轻松处理用户验证和验证电子邮件。

Latest Stable Version Total Downloads License

版本

此包符合 Laravel 7.0 标准。

关于

  • 为注册用户生成并存储验证令牌
  • 发送或队列包含验证令牌链接的电子邮件
  • 处理令牌验证
  • 将用户设置为已验证
  • 随时重新启动过程

安装

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

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

}

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

或者运行以下命令

composer require jrean/laravel-user-verification

添加服务提供者 & Facade/Alias

一旦安装了 Laravel User Verification,您需要将服务提供者注册到 config/app.php 中。请确保将以下行添加到 RouteServiceProvider 上方。

Jrean\UserVerification\UserVerificationServiceProvider::class,

您可以在 config/app.php 中添加以下 aliases

'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

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

错误视图

默认情况下,将加载 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 检查是否已为用户启动了验证过程。

在您的 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的这篇文章

贡献

请随意评论、贡献和帮助。1个PR = 1个功能。

许可证

Laravel用户验证在MIT许可证(MIT)下授权。