[ Laravel ]facebook Loginを実装する

Laravelを使う機会がきたので、実装しながら理解した経緯を記す。


# ◆ 今日やること

- facebook Loginを実装する
    - [Authentication \- Laravel \- The PHP Framework For Web Artisans](https://laravel.com/docs/5.3/authentication)
    - [laravel/socialite](https://github.com/laravel/socialite）
    - [Laravelでソーシャル認証\(Twitter, Facebook, Google\)を実装してみた \| urashita\.com](http://urashita.com/archives/8848)

# ◆ バージョン

```bash
 $ php artisan --version
Laravel Framework version 5.3.28

 $ php --version
PHP 7.1.0 (cli) (built: Dec  2 2016 03:30:24) ( NTS )
Copyright (c) 1997-2016 The PHP Group
Zend Engine v3.1.0-dev, Copyright (c) 1998-2016 Zend Technologies

```

# ◆ 実装編

### > FacebookのアプリIDとapp_secretを取得する

- https://developers.facebook.com/apps
    - 新しいアプリを追加して、Facebookログインを有効にします
- 有効なOauthリダイレクトIDを取得する、ここではテスト用のリダイレクトURLを設定する
    - http://localhost:8000/auth/facebook/callback
    
<img width="1521" alt="facebook_dev.png" src="https://qiita-image-store.s3.amazonaws.com/0/32215/6793e624-cd7f-b25c-f0cf-26360bf3e7ff.png">


### > laravel/socialiteのインストール

laravel/socialiteはFacebook, Twitter, Google, LinkedIn, GitHub and BitbucketのOauthログインインターフェイスを提供します

- [laravel/socialite](https://github.com/laravel/socialite)

```
composer require laravel/socialite
```

### > configurationの追加

- config/app.php

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

    Laravel\Socialite\SocialiteServiceProvider::class,
],
```
   
- aliases array in your app configuration file:


```php
'Socialite' => Laravel\Socialite\Facades\Socialite::class,
```

- .env & config/services.php

```php
#Social Login
FACEBOOK_APP_ID=XXXXXXX
FACEBOOK_APP_SECRET=XXXXXXXXXXXXXXXXXX
FACEBOOK_CALLBACK_URL=http://localhost:8000/auth/facebook/callback
```

```php
    'facebook' => [
        'client_id' =>  env('FACEBOOK_APP_ID'),
        'client_secret' => env('FACEBOOK_APP_SECRET'),
        'redirect' =>  env('FACEBOOK_CALLBACK_URL'),
    ],

```

### > Router & Controller

- routes/web.php

```php
Route::get('auth/login', 'Auth\SocialController@viewLogin');
Route::get('auth/login/facebook', 'Auth\SocialController@redirectToFacebookProvider');
Route::get('auth/facebook/callback', 'Auth\SocialController@handleFacebookProviderCallback');
```

- Http/Controllers/Auth/SocialController.php

```php
<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;

use Socialite;

class SocialController extends Controller
{
        /**
     * Redirect the user to the GitHub authentication page.
     *
     * @return Response
     */
    public function viewLogin()
    {
        return view('auth.login');
    }

    /**
     * Redirect the user to the GitHub authentication page.
     *
     * @return Response
     */
    public function redirectToFacebookProvider()
    {
        return Socialite::driver('facebook')->redirect();
    }

    /**
     * Obtain the user information from GitHub.
     *
     * @return Response
     */
    public function handleFacebookProviderCallback()
    {
        try{
            $user = Socialite::driver('facebook')->user();

            if($user){
                dd($user);
                // OAuth Two Providers
                $token = $user->token;
                $refreshToken = $user->refreshToken; // not always provided
                $expiresIn = $user->expiresIn;

                // All Providers
                $user->getId();
                $user->getNickname();
                $user->getName();
                $user->getEmail();
                $user->getAvatar();

            }
        }catch(Exception $e){
            return redirect("/");
        }
       
        // $user->token;
    }
}
```

- resources/view/auth/login.blade.php

```php
<a href="facebook">Sign in with Facebook</a>
```


### > facebookから取得したユーザー情報


```
User {#178 ▼
  +token: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
  +refreshToken: null
  +expiresIn: "5183964"
  +id: "XXXXXXXXXXX"
  +nickname: null
  +name: "XXXXXX XXXXX"
  +email: "XXXXXX@gmail.com"
  +avatar: "https://graph.facebook.com/v2.8/XXXXXXXXX/picture?type=normal"
  +user: array:6 [▼
    "name" => "XXXXX XXXXXX"
    "email" => "XXXXXX@gmail.com"
    "gender" => "female"
    "verified" => true
    "link" => "https://www.facebook.com/app_scoped_user_id/XXXXXXX/"
    "id" => "XXXXXXXX"
  ]
  +"avatar_original": "https://graph.facebook.com/v2.8/XXXXXX/picture?width=1920"
  +"profileUrl": "https://www.facebook.com/app_scoped_user_id/XXXXXXX/"
}
```