我想让使用第三方帐户(在我的例子中是 Google 帐户)创建新用户而无需填写普通用户注册表,但我在创建记录时遇到了问题。
在我的 register.blade.php 页面中有以下按钮,必须使用第三方帐户创建新用户:
register.blade.php
<div class="ml-3">
<a href="{{ route('google.signup') }}" class="inline-flex items-center px-4 py-2 bg-gray-800 border border-transparent
rounded-md font-semibold text-xs text-white uppercase tracking-widest hover:bg-gray-700 active:bg-gray-900 focus:outline-none
focus:border-gray-900 focus:ring ring-gray-300 disabled:opacity-25 transition ease-in-out duration-150'">
<i class="fa fa-google"></i>Google signup</a>
</div>
route('google.signup')
转到 Route::get('/auth/google/signup', [RegisteredUserController::class, 'redirectGoogleRegister'])->name('google.signup');
,它可以让用户正确地验证他们的 Google 帐户以创建用户。
问题出在
Route::get('/auth/google/callback', [RegisteredUserController::class, 'callbackGoogleRegister'])->name('google.callback');
,它永远不会重定向到callbackGoogleRegister()
,而是转到登录页面并显示消息无法验证不在您记录中的Google帐户。
services.php
'google' => [ // Google account
'client_id' => env('GOOGLE_CLIENT_ID'),
'client_secret' => env('GOOGLE_CLIENT_SECRET'),
'redirect' => env('GOOGLE_REDIRECT_URL'),
],
.env
GOOGLE_CLIENT_ID = "XXXXX"
GOOGLE_CLIENT_SECRET = "XXXXX"
GOOGLE_REDIRECT_URL = "http://127.0.0.1:8000/auth/google/callback"
RegisteredUserController.php
public function redirectGoogleRegister()
{
return Socialite::driver('google')->redirect();
}
public function callbackGoogleRegister()
{
$user = Socialite::driver('google')->user();
$exists_user = User::where('email', $user->email)->first();
if ($existe_user) {
return redirect('login')->with('success-destroy',"$user->name already linked this Google account when registering in the system.");
} else {
$new_user = new User();
$new_user->name = $user->name;
$new_user->email = $user->email;
$new_user->password = Hash::make(Str::random(24));
$new_user->save();
Auth::login($new_user, true);
}
return redirect(RouteServiceProvider::HOME);
}
web.php
// Sign up using Laravel Socialite
Route::get('/auth/google/signup', [RegisteredUserController::class,'redirectGoogleRegister'])->name('google.signup');
Route::get('/auth/google/callback', [RegisteredUserController::class,'callbackGoogleRegister'])->name('google.callback'); // Don't work route
// Login using Laravel Socialite (All worked)
Route::get('/auth/google/redirect', function () {
return Socialite::driver('google')->redirect();
})->name('google.login');
Route::get('/auth/google/callback', function () {
try {
$user = Socialite::driver('google')->user();
$user = User::firstOrCreate([
'email' => $user->email
],[
'name' => $user->name,
'password' => Hash::make(Str::random(24))
]);
Auth::login($user, true);
return redirect('dashboard');
} catch (\Exception $e) {
return redirect('login')->with('danger', "Unable to authenticate a Google account that is not on your record.");
}
});
我如何解决这个路线问题?