LoginSignup
1
1

More than 1 year has passed since last update.

【Laravel】socialiteとsanctumを使った新規登録・ログイン機能

Last updated at Posted at 2022-05-23

環境

Laravel v9.5.1 (PHP v8.1.3)

新規登録・ログインの流れ

Slackに近い新規登録・ログイン機能の実装をやりたかった。

Googleアカウントでログイン
(未登録の場合)
->Googleアカウントの名前とメールアドレスで自動的に新規登録される
->トークンが発行される
->ログイン

(登録済みの場合)
->トークンが発行される
->ログイン

実装

/auth/google/redirectにアクセスしたら/auth/google/callbackにリダイレクトされる。

routes/web.php
Route::get('/auth/google/redirect', function () {
  return Socialite::driver('google')->redirect();
});

Route::controller(OAuthController::class)->group(function() {
  Route::get('/auth/google/callback', 'googleAuthCallback');
});

Socialite::driver('google')->user();でGoogleアカウント情報が取れるので、nameとemailを使って新規登録またはログイン処理。
そのユーザーでトークンを発行。
returnでとりあえずtokenを返しておいた。(ここは仕様次第で変わる)

app/Http/Controllers/Auth/OAuthController.php
class OAuthController extends Controller
{
  public function googleAuthCallback()
  {
    DB::transaction(function () {
      $google_user = Socialite::driver('google')->user();
       
      $user = User::firstOrCreate([
          'email' => $google_user->email,
      ], [
          'name' => $google_user->name,
          'email' => $google_user->email,
      ]);

      $token = $user->createToken('api token')->plainTextToken;
      Auth::login($user);

      return $token;
    });
  }
}

参考

socialiteのテストの記事はこちら

1
1
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
1