Login with Laravel 8 and Socialite ,Google, Facebook, GitHub

 

Login with Laravel 8 and Socialite, Google, Facebook, GitHub



Step 1: Install Laravel 8

step: Install UI

Note:

composer require laravel/ui
php artisan ui vue --auth

First, install a new Laravel app just by running the below command in your terminal.

composer create-project --prefer-dist laravel/laravel LaravelSocialite 

Step 2: Update Your Database Credentials

After that update your database credentials in your .env file which is located in your project root.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_custom_auth
DB_USERNAME=root
DB_PASSWORD=#your database password
GOOGLE_CLIENT_ID="your google id"
GOOGLE_CLIENT_SECRET="your secret"

FACEBOOK_CLIENT_ID="your facebook id"
FACEBOOK_CLIENT_SECRET="your secret"

GITHUB_CLIENT_ID="your github id"
GITHUB_CLIENT_SECRET="your secret"

Step 3: Create Laravel Authentication

Now the basic authentication we need to run the auth command of Laravel just running the below command.

php artisan make:auth

After running this your check-in web.php have added auth routes automatically. These routes work Laravel inbuilt function.

Step 4: Download Socialite Package

The Laravel socialite package makes authentification with traditional social networks simple. So download the socialite package just by running the below command.

composer require laravel/socialite
composer self-update --2

now open the config\services.php and add the below code to it.

config\services.php

 'google' => [
        'client_id' => env('GOOGLE_CLIENT_ID'),
        'client_secret' => env('GOOGLE_CLIENT_SECRET'),
        'redirect' => 'http://localhost/Login_Socialite/public/login/google/callback',
    ],

    'facebook' => [
        'client_id' => env('FACEBOOK_CLIENT_ID'),
        'client_secret' => env('FACEBOOK_CLIENT_SECRET'),
        'redirect' => 'http://localhost/Login_Socialite/public/login/facebook/callback',
    ],

    'github' => [
        'client_id' => env('GITHUB_CLIENT_ID'),
        'client_secret' => env('GITHUB_CLIENT_SECRET'),
        'redirect' => 'http://localhost/Login_Socialite/public/login/github/callback',
    ],

I. Facebook: https://developers.facebook.com/

Step 5: Get secrets from Facebook

Here we get CLIENT ID and CLIENT SECRET for the Facebook login button in Laravel based project, So we need to go https://developers.facebook.com/ and create an app. Create an app in the config/service.php file just like below.

1) First Go to My Apps and click create the new app you get a popup just like below. add your new app name and your Facebook email id on it.

2) Next, go to Settings -> Basic, copy your App Id and App Secret, and add in your .env file we have displayed below. Follow the next step before going to the Facebook login step.

3) Now click on the ‘+’ button beside ‘PRODUCTS’, select quickstart you got a window there your see four option (‘ios’, ‘android’, ‘web’, ‘other’) select web option then your see below the image where you need to add your website URL: https://localhost:8000 and click on ‘Save’ as shown below…

4) Then go to Facebook Login -> Settings, scroll down to ‘Valid OAuth Redirect URL’ and add your callback /redirect URL: https://localhost:8000/callback and Save changes as illustrated below…

Now our App settings are done, copy your client id, client secret, and predict you're and save in .env file.

Step 6: Make Migration

Now, open app/database/create_users_table.php and put the below code here.

public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->string('provider_id')->nullable();
            $table->text('avatar')->nullable();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password')->nullable();
            $table->rememberToken();
            $table->timestamps();
        });
    }

After adding the migration file now run the migrate command.

php artisan migrate

Step 7: Add Routes

In this step we create routes for Facebook login, add two routes in your web.php file.

app/routes/web.php

<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
    return view('auth.login');
});

Auth::routes();

Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');

// Google login
Route::get('login/google', [App\Http\Controllers\Auth\LoginController::class, 'redirectToGoogle'])->name('login.google');
Route::get('login/google/callback', [App\Http\Controllers\Auth\LoginController::class, 'handleGoogleCallback']);

// Facebook login
Route::get('login/facebook', [App\Http\Controllers\Auth\LoginController::class, 'redirectToFacebook'])->name('login.facebook');
Route::get('login/facebook/callback', [App\Http\Controllers\Auth\LoginController::class, 'handleFacebookCallback']);

// Github login
Route::get('login/github', [App\Http\Controllers\Auth\LoginController::class, 'redirectToGithub'])->name('login.github');
Route::get('login/github/callback', [App\Http\Controllers\Auth\LoginController::class, 'handleGithubCallback']);

// -----------------------------forget password ------------------------------
Route::get('forget-password', 'App\Http\Controllers\Auth\ForgotPasswordController@getEmail')->name('forget-password');
Route::post('forget-password', 'App\Http\Controllers\Auth\ForgotPasswordController@postEmail')->name('forget-password');

Route::get('reset-password/{token}', 'App\Http\Controllers\Auth\ResetPasswordController@getPassword');
Route::post('reset-password', 'App\Http\Controllers\Auth\ResetPasswordController@updatePassword');

Step 8: Create LoginController

php artisan make:controller LoginController

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = RouteServiceProvider::HOME;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    // Google login
    public function redirectToGoogle()
    {
        return Socialite::driver('google')->redirect();
    }

    // Google callback
    public function handleGoogleCallback()
    {
        $user = Socialite::driver('google')->user();

        $this->_registerOrLoginUser($user);

        // Return home after login
        return redirect()->route('home');
    }

    // Facebook login
    public function redirectToFacebook()
    {
        return Socialite::driver('facebook')->redirect();
    }

    // Facebook callback
    public function handleFacebookCallback()
    {
        $user = Socialite::driver('facebook')->user();

        $this->_registerOrLoginUser($user);

        // Return home after login
        return redirect()->route('home');
    }

    // Github login
    public function redirectToGithub()
    {
        return Socialite::driver('github')->redirect();
    }

    // Github callback
    public function handleGithubCallback()
    {
        $user = Socialite::driver('github')->user();

        $this->_registerOrLoginUser($user);

        // Return home after login
        return redirect()->route('home');
    }

    protected function _registerOrLoginUser($data)
    {
        $user = User::where('email', '=', $data->email)->first();
        if (!$user) {
            $user = new User();
            $user->name = $data->name;
            $user->email = $data->email;
            $user->provider_id = $data->id;
            $user->avatar = $data->avatar;
            $user->save();
        }

        Auth::login($user);
    }
}

Step 9: Add Button in Login Page

Add the below code in your login.blade.php file.

Resources/Views/passwords/Auth/login.blade.php

@extends('layouts.app')
@section('content')
    <div class="login-form">
        <form method="POST" action="{{ route('login') }}">
            @csrf
            <div class="text-center">
                <a href="" aria-label="Space">
                    <img class="mb-3 logo-image" src="{{URL::to('assets/images/logo_log.png')}}" alt="Logo" width="60" height="60">
                </a>
            </div>
            <div class="text-center mb-4">
                <h1 class="h3 mb-0">Please sign in</h1>
                <p>Signin to manage your account.</p>
            </div>
            @if(session()->has('error'))
                <div class="alert alert-danger">
                    {{ session()->get('error') }}
                </div>
            @endif
    
            
            <div class="js-form-message mb-3">
                <div class="js-focus-state input-group form">
                <div class="input-group-prepend form__prepend">
                    <span class="input-group-text form__text">
                    <i class="fa fa-envelope form__text-inner"></i>
                    </span>
                </div>
                <input type="email" class="form-control form__input @error('email') is-invalid @enderror" name="email" value="{{ old('email') }}"  placeholder="Email" autocomplete="email">
                @error('email')
                    <span class="invalid-feedback" role="alert">
                        <strong>{{ $message }}</strong>
                    </span>
                @enderror
                </div>
            </div>
        <div class="form-group">
                <div class="input-group">
                    <div class="input-group-prepend">
                        <span class="input-group-text">
                            <i class="fa fa-lock"></i>
                        </span>
                    </div>
                    <input type="password" class="form-control @error('password') is-invalid @enderror" name="password"  placeholder="Password" autocomplete="new-password">
                    @error('password')
                        <span class="invalid-feedback" role="alert">
                            <strong>{{ $message }}</strong>
                        </span>
                    @enderror
                </div>
            </div>
            <div class="row mb-3">
                <div class="col-6">
                  <!-- Checkbox -->
                  <div class="custom-control custom-checkbox d-flex align-items-center text-muted">
                    <input class="custom-control-input"type="checkbox" name="remember" id="remember" {{ old('remember') ? 'checked' : '' }}>
                    <label class="custom-control-label" for="remember">
                      Remember Me
                    </label>
                  </div>
                  <!-- End Checkbox -->
                </div>
            </div>
            
            <div class="form-group mb-3">
                <button type="submit" class="btn btn-primary login-btn btn-block">Signup</button>
            </div>
            <div class="text-center mb-3">
                <p class="text-muted">Have an account? <a href="{{route('register')}}">Signin</a></p>
            </div>
            <div class="or-seperator"><i>OR</i></div>
            <div class="row mx-gutters-2 mb-4">
                <div class="col-sm-4">
                    <a href="{{ route('login.google') }}">
                        <button type="button" class="btn btn-block btn-google">
                            <i class="fa fa-google mr-2"></i>Google
                        </button>
                    </a>
                </div>
                <div class="col-sm-4">
                    <a href="{{ route('login.facebook') }}">
                        <button type="button" class="btn btn-block btn-facebook">
                            <i class="fa fa-facebook mr-2"></i>Facebook
                        </button>
                    </a>
                </div>
                <div class="col-sm-4">
                    <a href="{{ route('login.github') }}">
                        <button type="button" class="btn btn-github">
                            <i class="fa fa-github mr-2"></i>Github
                        </button>
                    </a>
                </div>
            </div>
            <p class="small text-center text-muted mb-0">All rights reserved. © Space. 2021 soengsouy.com.</p>
        </form>
    </div>
@endsection

Step 9: Run Development Server

After successfully update all run the development server just adding the below command in the terminal.

php artisan serve

After this go to the browser and check using the login page.

http://localhost/Login_Socialite/public/
Reactions

Post a Comment

0 Comments