matthanley/laravel-polyauth

Laravel的多态认证

dev-master 2018-08-24 18:53 UTC

This package is not auto-updated.

Last update: 2024-09-29 06:28:30 UTC


README

允许在Laravel 5中使用多个用户模型进行认证。

安装

安装通过Composer执行

composer require matthanley/laravel-polyauth

配置

通过在app/Providers/AuthServiceProvider.php中的boot()方法中添加以下内容来注册认证驱动

\Auth::provider('polymorphic', function ($app) {
    return $app->make(\PolyAuth\Providers\UserProvider::class);
});

更新config/auth.php以将认证驱动设置为polymorphic并定义您希望进行认证的模型

'providers' => [
    'users' => [
        'driver' => 'polymorphic',
        'models' => [
            App\User::class,
            App\Admin::class,
        ],
    ],
],

确保您的用户模型使用全局唯一标识符,并为全局唯一的电子邮件/用户名等添加事件以强制执行。例如

/**
 * Migrations
 */

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->uuid('id')->unique();
            $table->primary('id');
            /* ... */
        });
    }
}

/**
 * Models
 */

use Illuminate\Support\Facades\Auth;
use Ramsey\Uuid\Uuid;

class User extends Authenticatable
{

    /**
     * Indicates if the IDs are auto-incrementing.
     *
     * @var bool
     */
    public $incrementing = false;

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            // Generate an ID
            $model->setAttribute($model->getKeyName(), Uuid::uuid1()->toString());
            // Make sure email is globally unique
            if (Auth::getProvider()->retrieveByCredentials(['email' => $model->email])) {
                throw new \Exception();
            }
        });
    }

    /* ... */
}