LoginSignup
1
0

More than 5 years have passed since last update.

laravel Auth Twitter 連携

Last updated at Posted at 2019-01-05

条件

https://qiita.com/ma7ma7pipipi/items/f41b41aa53d05653ad3d
https://qiita.com/ma7ma7pipipi/items/848d54293968c502150d

の準備が完了していること。

まずは socials情報を格納するテーブルを作りましょう。

テーブル作成


--
-- テーブルの構造 `socials`
--

CREATE TABLE `socials` (
  `id` bigint(20) NOT NULL,
  `user_id` bigint(20) NOT NULL DEFAULT 0,
  `name` varchar(255) NOT NULL,
  `screen_name` varchar(255) DEFAULT NULL,
  `verified` int(11) NOT NULL DEFAULT 0,
  `token` varchar(255) DEFAULT NULL,
  `token_secret` varchar(255) DEFAULT NULL,
  `img` varchar(255) DEFAULT NULL,
  `profile_banner_url` varchar(255) DEFAULT NULL,
  `profile_image_url_https` varchar(255) DEFAULT NULL,
  `expired` int(11) NOT NULL DEFAULT 0,
  `updated_at` datetime NOT NULL DEFAULT current_timestamp(),
  `created_at` datetime NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `socials`
--
ALTER TABLE `socials`
  ADD UNIQUE KEY `id` (`id`);
COMMIT;


モデルの関連付け

user 1 に対し、 social は 多

User.php

    public function socials()
    {
        return $this->hasMany('App\Social');
    }

Social.php

    public function user()
    {
        return $this->belongsTo('App\User');
    }

Twitterでログインしてきたら

すでに登録されている場合はそのままログイン。
まだ登録されていない場合は新規登録画面へ飛ばす。

Http/Controllers/OAuthLoginController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;
use App\Social;


use Socialite;
use Auth;

class OAuthLoginController extends Controller
{
    public function getTwitterAuth($provider)
    {
        return Socialite::driver($provider)->redirect();
    }

//
    public function authTwitterCallback()
    {
        $data = Socialite::driver('twitter')->user();

        $res = Social::query()
            ->where('id',$data->id)
            ->get();

        if(!empty($res[0]->user->id)){
            //ログインしている場合
            Auth::login($res[0]->user);
            return redirect('/')->with('status', 'ログインしました');
        } else {
            //まだログインしたことない場合 情報をセッションに保存し新規会員登録へ
            session(['twitter' => $data]);
            return redirect('register')->with('status', 'Twitter連携しました');
        }

    }
}




新規登録

新規登録成功し、且つ
twitter の セッションを持っていたら関連テーブルに格納。

Http/Controllers/Auth/RegisterController.php

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\User
     */
    protected function create(array $data)
    {

        $res = User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => $data['password'],
        ]);


        if(session('twitter')){

            $social = session('twitter');

            Social::create([
                'id' => $social->id,
                'user_id' => $res->id,
                'name' => $social->name,
                'screen_name' => $social->nickname,
                'verified' => $social->user['verified'],
                'token' => $social->token,
                'token_secret' => $social->tokenSecret,
                'img' => $social->avatar,
                'profile_banner_url' => $social->user['profile_banner_url'],
                'profile_image_url_https' => $social->user['profile_image_url_https'],
                'expired' => 0
            ]);

            session()->forget('twitter');
        }

        return $res;


    }

・Twitterでログインしてきた場合、ユーザー新規登録時にセッションを自動で読み込み、Socialテーブルに保存する。

・また、Twitterログイン時もしくはメールアドレスログイン時、データがすでにあれば自動的にログイン。

ログインした時に情報にアクセスしたい場合


        $u = Auth::user();
        dd($u->name);
        dd($u->socials[0]->name);


1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0