bkstar123/social-auth

这是一个Socialite包的轻量级封装,用于简化Laravel应用程序中社交登录的实现

1.0.8 2019-08-10 05:29 UTC

This package is auto-updated.

Last update: 2024-09-10 16:32:30 UTC


README

Laravel提供了一个名为Socialite的官方包,用于实现社交登录功能。尽管它非常方便简单,但仍需要一些非平凡的代码。

有时,重复性的工作可能会让你难以开始一个新项目。为了消除这个问题,快速获得新想法的动力,这个包被构建来提供对Socialite包的薄层封装,以简化Laravel应用程序中社交登录的实现。

1 要求

建议使用PHP版本7.1.3+和Laravel框架版本5.5+安装此包

2 安装

composer require bkstar123/social-auth

3 使用

3.1 默认使用

默认情况下,此包假定与Laravel的默认认证守护者(如config/auth.php中指定)和App\User模型一起使用。

  • 修改Laravel的默认用户迁移 yyyy-mm-dd-xxxxxxxx_create_users_table 确保它包含以下行
$table->string('name')->nullable();
$table->string('avatar')->nullable();
$table->string('email')->unique();
$table->string('password')->nullable();

注意:如果你已经运行了用户迁移,你应该创建另一个迁移来更新users表,并添加新的列avatar,并将passwordname列设置为可空(emailname已经在Laravel默认用户迁移中提供),例如

运行: php artisan make:migration update_users_table

yyyy_mm_dd_xxxxxxxx_update_users_table.php:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class UpdateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('password')->nullable()->change();
            $table->string('name')->nullable()->change();
            $table->string('avatar')->nullable();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function(Blueprint $table) {
            \DB::statement('SET FOREIGN_KEY_CHECKS=0;');
            \DB::table('users')->truncate();
            $table->dropColumn('avatar');
            $table->string('name')->nullable(false)->change();
            $table->string('password')->nullable(false)->change();
            \DB::statement('SET FOREIGN_KEY_CHECKS=1;');
        });
    }
}
  • 运行: composer require doctrine/dbal

  • 运行迁移命令: php artisan migrate

  • app/User.php中导入并使用Bkstar123\SocialAuth\Traits\SocialLinkable特质。将avatar添加到$fillable数组中,例如

protected $fillable = [
    'name', 'email', 'password', 'avatar'
];
  • app/Http/Controllers/Auth/LoginController.php中,使其实现Bkstar123\SocialAuth\Contracts\SocialAuthentication接口,然后导入并使用Bkstar123\SocialAuth\Traits\SocialAuthenticable特质
  • routes/web.php中添加以下路由
Route::get('/login/{provider}', 'Auth\LoginController@redirectToSocialProvider')
     ->name('login.social');
Route::get('/login/{provider}/callback', 'Auth\LoginController@handleSocialProviderCallback')
     ->name('login.social.callback');
  • 在包含登录表单的视图文件中,添加社交登录链接,例如
<!-- For Google login -->
<a href="{{ route('login.social', ['provider' => 'google']) }}" 
   class="btn btn-danger">
    <i class="fa fa-google"></i>&nbsp; Google 
</a>
  • 在.env文件中,添加必要的环境密钥/值
[PROVIDER_NAME]_CLIENT_ID  
[PROVIDER_NAME]_CLIENT_SECRET  
[PROVIDER_NAME]_CLIENT_REDIRECT 

其中[PROVIDER_NAME]可以是GOOGLE, FACEBOOK, TWITTER, LINKEDIN, GITHUB, GITLAB, BITBUCKET

3.2 自定义使用

3.2.1 如果你不希望使用包默认的迁移

  • 将以下键值对放入.env文件中
    BKSTAR123_SOCIALAUTH_LOAD_MIGRATION=false

  • 然后,你必须创建自己的迁移文件来构建存储社交账户的表,例如
    yyyy_mm_dd_xxxxxxxx_create_customer_social_accounts_table.php:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateCustomerSocialAccountsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('customer_social_accounts', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->bigInteger('customer_id')->unsigned()->index();
            $table->string('provider_name');
            $table->string('provider_user_id');
            $table->timestamps();
            $table->foreign('customer_id')->references('id')->on('customers')->onDelete('cascade');
            $table->unique(['provider_name', 'provider_user_id']);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('customer_social_accounts');
    }
}

注意provider_nameprovider_user_id必须在迁移中命名为它们在迁移中的名称,外键(如上面的示例中的customer_id)可以根据你的用例适当命名。

或者,你可以将包的默认迁移发布到database/migrations/,并将其用作定制的起点。
=> 运行: php artisan vendor:publish --provider="Bkstar123\SocialAuth\SocialAuthServiceProvider"

  • 运行 php artisan migrate

3.2.2 你可以定义一个自定义的社交账户模型,它与你的自定义用户模型有一个belongsTo关系

app/Models/CustomerSocialAccount.php:

<?php

namespace App;

use App\Models\Customer;
use Bkstar123\SocialAuth\Models\Abstracts\SocialAccountBase;

class CustomerSocialAccount extends SocialAccountBase
{
    public function getUserModelClass()
    {
    	return Customer::class;
    }
}

3.2.3 你也可以告诉包使用你的自定义社交账户和用户模型

例如

  • 在你的用户模型如app/Models/Customer.php

在导入并使用 Bkstar123\SocialAuth\Traits\SocialLinkable 特性后,添加以下方法

protected function getSocialAccountModelClass()
{
    return CustomerSocialAccount::class; // Surely, you must autoload this class 
}
  • 在处理登录逻辑的控制器中
    实现 Bkstar123\SocialAuth\Contracts\SocialAuthentication 接口后,导入并使用 Bkstar123\SocialAuth\Traits\SocialAuthenticable 特性。添加以下方法
protected function getUserModelClass()
{
    return Customer::class; // Surely, you must autoload this class 
}

protected function getSocialAccountModelClass()
{
    return CustomerSocialAccount::class; // Surely, you must autoload this class 
}

3.2.4 您可以更改要将哪种社交数据映射到要持久化到数据库中的用户

例如
假设您的 users 表有 social_avataremail。然后在处理登录逻辑的控制器中,添加以下方法

protected function mapUserWithSocialData($socialUser)
{
    return [
        'social_avatar' => $socialUser->getAvatar(),
        'email' => $socialUser->getEmail(),
    ];
}

3.2.5 您可以使用 beforeFirstSocialLogin() 钩子,在用户首次使用社交账户登录之前添加更多业务逻辑

例如,如果您的应用程序强制要求所有用户在使用某些功能之前必须经过验证,那么在用户首次使用社交账户登录之前,您可能需要为该用户设置 email_verified_at

为了做到这一点,在处理登录逻辑的控制器中,添加以下方法

protected function beforeFirstSocialLogin($user, $socialUser)
{
    if (!$user->email_verified_at) {
        $user->email_verified_at = Carbon::now();
        $user->save();
    }
}

3.2.6 您可以自定义在用户使用社交账户成功登录后要采取的操作

例如:您可能想将已认证的用户明确重定向到仪表板

protected function postSocialLogIn()
{
    return redirect()->route('dashboard');
}

3.2.7 您可以自定义在应用程序无法从社交提供者获取数据时要采取的操作

例如:在这种情况下,您可能想将用户重定向到客户登录页面

protected function actionIfFailingToGetSocialData()
{
    return redirect()->route('customer.login');
}

默认情况下,该包使用Laravel的默认认证守卫,该守卫在 config/auth.php 中指定。
这种行为可以通过您控制器中定义的 guard() 方法覆盖

例如:您可能希望该包使用名为 customer 的自定义认证守卫

protected function guard()
{
    return Auth::guard('customer');
}