0

Tìm hiểu về Socialite trong Laravel

Giới thiệu

Hiện nay, với một trang web thì không thể thiếu được việc sử dụng socialite . Tuy nhiên ở trong doc laravel không hướng dẫn kĩ việc sử dụng nhiều tài khoản xã hội nên bài viết này tôi muốn chia sẻ một chút về socialite trong laravel.

Cài đặt

Đầu tiên, chúng ta add vào file composer.json .

composer require laravel/socialite

Sau đấy , ta sẽ cài đặt thư viện socialite Laravel\Socialite\SocialiteServiceProvider vào trong file config/app.php :

'providers' => [
    // Other service providers...

    Laravel\Socialite\SocialiteServiceProvider::class,
 ],

and alias

 'aliases' => [
    'Socialite' => Laravel\Socialite\Facades\Socialite::class,
 ],

Tiếp đến , chúng ta muốn sử dụng socialite nào thì chúng ta thêm credentials vào trong file config/service . Ví dụ ở đây chúng ta sử dụng facebook hay google . Chúng ta có thể sử dụng nhiều tài khoản xã hội cùng một lúc .

'facebook' => [
    'client_id' => '690344774435367',
    'client_secret' => 'ebc50d3fd1d2f7286e02d247e5751ef4',
    'redirect' => 'http://localhost:8000/callback',
],
'google' => [
    'client_id' => '716438745047-ua94i3snt6s01i0ncn3u33j5h5rvu9rk.apps.googleusercontent.com',
    'client_secret' => '23zeZz1ya9syFMH4ggQM2e-p',
    'redirect' => 'http://localhost:8000/callback/google',
],

Với client_id , client_secret thì tùy vào sử dụng mạng xã hội nào thì ta sẽ vào tạo ứng dụng để lấy ID ứng dụng và mật khẩu cho ứng dụng đấy.Ví dụ như facebook chúng ta sẽ vào trang để tạo ứng ứng:

https://developers.facebook.com/

Việc sử dụng nhiều tài khoản cùng một lúc hoặc có nhiều tài khoản xã hội ví dụ như twiter sẽ không cung cấp email cho chúng ta vì vậy chúng ta cần thiết lập lại cơ sở dữ liệu cho phép trường email có thể null :

$table->string('email')->unique()->nullable();

Với việc sử dụng nhiều tài khoản xã hội thì chúng ta cần có một bảng dữ liệu để lưu lại bằng cách chạy câu lệnh :

php artisan make:migration create_social_accounts_table --create="social_accounts"

php artisan make:model SocialAccount

Add các trường sau trong migration:


<?php

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

class CreateSocialAccountsTable extends Migration {

    public function up()
    {
        Schema::create('social_accounts', function(Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id');
            $table->string('provider_user_id');
            $table->string('provider');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::drop('social_accounts');
    }
}

Trong model SocialAccount ta cần xác định mối quan hệ với bảng User:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Models\User;

class SocialAccount extends Model
{
    protected $fillable = [
        'user_id', 'provider_user_id', 'provider',
    ];

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

Bây giờ, chúng ta cần một service để đăng kí sử dụng hoặc đăng nhâp nếu tài khoản đã tồn tại. Chúng ta tạo SocialAccountService.php trong folder app\Service

<?php

namespace App\Services;

use App\Models\User;
use App\Models\SocialAccount;
use Laravel\Socialite\Contracts\Provider;

class SocialAccountService
{
    public function createOrGetUser(Provider $provider)
    {
        $providerUser = $provider->user();
        $providerName = class_basename($provider);

        $account = SocialAccount::whereProvider($providerName)
            ->whereProviderUserId($providerUser->getId())
            ->first();

        if ($account) {
            return $account->user;
        } else {
            $account = new SocialAccount([
                'provider_user_id' => $providerUser->getId(),
                'provider' => $providerName
            ]);

            $user = User::whereEmail($providerUser->getEmail())->first();

            if (!$user) {
                $user = User::create([
                    'email' => $providerUser->getEmail(),
                    'name' => $providerUser->getName(),
                    'avatar' => $providerUser->getAvatar(),
                ]);
            }

            $account->user()->associate($user);
            $account->save();

            return $user;
        }
    }
}

Chúng ta sử dụng các function getEmail() , getName()...để lấy dữ liệu

Sau đó, chúng ta cần tạo một controller , sử dụng câu lệnh :

php artisan make:controller SocialAuthController

Sử dụng 2 methods redirectToProvider()handleProviderCallback() trong controller này . Ta có ví dụ :

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Services\SocialAccountService;
use Socialite;
use Auth;

class SocialAccountController extends Controller
{

    public function redirectToProvider($provider)
    {
        return Socialite::driver($provider)->redirect();
    }

    public function handleProviderCallback(SocialAccountService $service, $provider)
    {
        $user = $service->createOrGetUser(Socialite::driver($provider));
        Auth::login($user);

        return redirect()->to('/');
    }

}

Cuối cùng ta chỉ cần thêm routing vào file routes.php

    Route::get('login/{social}', [
        'as' => 'login.{social}',
        'uses' => 'SocialAccountController@redirectToProvider'
    ]);

    Route::get('login/{social}/callback', [
        'as' => 'login.{social}.callback',
        'uses' => 'SocialAccountController@handleProviderCallback'
    ]);

Đương nhiên, chúng ta cần tạo link ở view:

<a class="circle facebook" href=" {{ url('login/facebook')}} ">
   <i class="fa fa-facebook-square fa-2x"></i>
</a>
<a class="circle twitter" href=" {{ url('login/twitter')}}">
   <i class="fa fa-twitter-square fa-2x"></i>
</a>
<a class="circle google" href=" {{ url('login/google') }} ">
   <i class="fa fa-google-plus-official fa-2x"></i>
</a>``

Hi vọng ở bài viết này có thể giúp các bạn hiểu thêm về socialite với framwork Laravel . Nếu có ý kiến gì thì mong mọi người góp ý ở comment dưới đây nhé ! Thank you 😗!!

Ngoài ra , mọi người có thể tham khảo thêm ở link sau :

Tài liệu tham khảo


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí