laravie/authen

Laravel 用户认证标识

v3.1.0 2023-02-08 03:20 UTC

README

tests Latest Stable Version Total Downloads Latest Unstable Version License Coverage Status

想象一下,你需要使用“电子邮件”、“用户名”或“电话号码”来登录用户,就像Facebook一样。由于Laravel限制只能使用一个唯一的用户名/标识键,这不可能实现。此包试图通过允许使用统一的键“标识符”来解决这个问题,并且你可以自定义Laravel在认证期间应检查哪些属性。

安装

要使用composer安装,请在终端中运行以下命令

composer require "laravie/authen"

用法

服务提供者

首先,你可以在 App\Providers\AuthServiceProvider 上附加认证提供者

<?php

namespace App\Providers;

use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Laravie\Authen\BootAuthenProvider;

class AuthServiceProvider extends ServiceProvider
{
    use BootAuthenProvider;

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        $this->bootAuthenProvider();
    }
}

用户模型

其次,你需要更新相关的 App\User(或用于认证的Eloquent模型)。

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravie\Authen\AuthenUser;

class User extends Authenticatable
{
    use Notifiable, AuthenUser;

    /**
     * Get the name of the unique identifier for the user.
     *
     * @return array<int, string>
     */
    public function getAuthIdentifiersName()
    {
        return ['email', 'username', 'phone_number'];
    }
}

使用此设置,你现在可以在认证期间检查 emailusernamephone_number

配置

最后,你需要更新配置 config/auth.php

<?php

return [

    // ...

    'providers' => [
        'users' => [
            'driver' => 'authen',
            'model'  => App\User::class,
        ],
    ],

    // ...
];

示例

以下是一个登录示例。

<?php 

use Illuminate\Support\Facades\Auth;
use Laravie\Authen\Authen;

$data = [Authen::getIdentifierName() => 'crynobone@gmail.com', 'password' => 'foobar'];

if (Auth::attempt($data)) {
    // you can logged in, you can also pass your phone number of username to `identifier`.
}