Chủ Nhật, 2 tháng 10, 2016

Laravel 5 Tutorial : Login with Twitter & Facebook Socialite in Laravel 5.3


Laravel 5 tutorial for beginners - This lessons is continued how to working with laravel 5 socialite package, create login page in laravel using media social twitter login & facebook login.

Before create this project, we recomended you to read previews lesson about login using facebook, please read Create Socialite Facebook Login in laravel 5.3.

Create Twitter & Facebook Login in Laravel 5.3

First, we need to create Twitter App from this link https://apps.twitter.com/app/new
setting and configuration your app looking like this images

Twitter & Facebook Socialite in Laravel 5.3

Login with Twitter & Facebook Socialite in Laravel 5.3
Than Click on Create your Twitter application.

Project Twitter Login Configuration

Go back to our "sociallogin" project, we need to add new services (Twitter services) into services.php that stored on config/services.php

Add Twitter services

'twitter' => [
    'client_id' => '5oU7CJpoTQF7CbUuJfvQdo7Cf', // configure with your app id
    'client_secret' => 'm2stErEz85bcWPPamZTsX8UUyq5SxgrxbYtG4DWoF1N3cQeS8S', // your app secret
    'redirect' => 'http://localhost:8080/callback/twitter', // leave blank for now
    ],
Information :
client_id : is Consumer Key (API Key) stored on Keys and Access Token your twitter app
clent_secret : is Consumer Secret (API Secret) stored on Keys and Access Token your twitter app

Facebook Services
Please update your facebook services with new redirect target url's.

'facebook' => [
    'client_id' => '765774933545982', // configure with your app id
    'client_secret' => 'c79c7a2d24d3f828e62272cc51acdaaf', // your app secret
    'redirect' => 'http://localhost:8080/callback/facebook', // we will change this callback url

Next, we need to configured our new routes, so we can use login page with multi social media account like Twitter, facebook, google plus, linkedin, github, etc.

Routes Configuration

Route::get('/redirect/{provider}','SocialAuthController@redirect');
Route::get('/callback/{provider}','SocialAuthController@callback');

Next, the callback method in our controller, SocialAuthController.php needs to use that new parameter to tell the socialite packages what driver to use. than we will create new function to get redirect method from all media social login provider.  So, please update your controller with this source code.

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\SocialAccountService;
use Socialite; // socialite namespace
class SocialAuthController extends Controller
{
    // redirect function
    public function redirect($provider){
      return Socialite::driver($provider)->redirect();
    }
    // callback function
    public function callback(SocialAccountService $service, $provider){
      // when facebook call us a with token
      // we need to change this method too
      $user = $service->createOrGetUser(Socialite::driver($provider));
      auth()->login($user);
      return redirect()->to('/home');
    }
}

Next, Go to the SocialAccountService.php. we will to pass $provider parameter to the createOrGetUser() method function. We will use class name of the provider to differentiate between them before we save SocialAccount to the database.

<?php
namespace App;
// use LaravelSocialiteContractsUser as ProviderUser;
use LaravelSocialiteContractsprovider;
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(),
                ]);
            }
            $account->user()->associate($user);
            $account->save();
            return $user;
        }
    }
}

Next, we will add new Twitter login link and new facebook link login into our views that stored on resources\views\auth\login.blade.php

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                <div class="panel-heading">Login</div>
                <div class="panel-body">
                    <form class="form-horizontal" role="form" method="POST" action="{{ url('/login') }}">
                        {{ csrf_field() }}

                        <div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
                            <label for="email" class="col-md-4 control-label">E-Mail Address</label>

                            <div class="col-md-6">
                                <input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}" required autofocus>

                                @if ($errors->has('email'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('email') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
                            <label for="password" class="col-md-4 control-label">Password</label>

                            <div class="col-md-6">
                                <input id="password" type="password" class="form-control" name="password" required>

                                @if ($errors->has('password'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('password') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="col-md-6 col-md-offset-4">
                                <div class="checkbox">
                                    <label>
                                        <input type="checkbox" name="remember"> Remember Me
                                    </label>
                                </div>
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="col-md-8 col-md-offset-4">
                                <button type="submit" class="btn btn-primary">
                                    Login
                                </button>

                                <a class="btn btn-link" href="{{ url('/password/reset') }}">
                                    Forgot Your Password?
                                </a>
                            </div>
                            <div class="col-md-8 col-md-offset-4">
                              <a class="btn btn-link" href="redirect/facebook">
                                  Facebook Login
                              </a>
                              <a class="btn btn-link" href="redirect/twitter">
                                  Twitter Login
                              </a>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Next, try to open our media social login apps followig by this url

http://localhost:8080/login

Video tutorial Login with Twitter & Facebook Socialite in Laravel 5.3


See you next lessons...

Không có nhận xét nào:

Đăng nhận xét