mirror of
https://github.com/henry4682/finance_app.git
synced 2026-07-16 08:20:00 +00:00
All checks were successful
Laravel-Oracle-Deploy / redeploy (push) Successful in 6s
51 lines
1.8 KiB
PHP
51 lines
1.8 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers\Auth;
|
|
|
|
use App\Http\Controllers\Controller;
|
|
use App\Models\User;
|
|
use Illuminate\Support\Facades\Auth;
|
|
use Laravel\Socialite\Facades\Socialite;
|
|
|
|
class GoogleAuthController extends Controller
|
|
{
|
|
// 導向 Google 登入頁
|
|
public function redirect()
|
|
{
|
|
return Socialite::driver('google')
|
|
->scopes(['https://www.googleapis.com/auth/gmail.readonly'])
|
|
->with([
|
|
'access_type' => 'offline', // 💡 極其重要:強制要求 Google 回傳長期有效的 refresh_token
|
|
'prompt' => 'consent' // 💡 強制跳出授權提示,確保每次都能順利拿到憑證
|
|
])
|
|
->redirect();
|
|
}
|
|
|
|
// Google 打回來後處理
|
|
public function callback()
|
|
{
|
|
$googleUser = Socialite::driver('google')->stateless()->user();
|
|
|
|
$user = User::updateOrCreate(
|
|
['email' => $googleUser->getEmail()],
|
|
[
|
|
'name' => $googleUser->getName(),
|
|
'google_id' => $googleUser->getId(),
|
|
'avatar' => $googleUser->getAvatar(),
|
|
'password' => bcrypt(str()->random(24)),
|
|
'google_access_token' => $googleUser->token,
|
|
'google_refresh_token' => $googleUser->refreshToken, // 💡 只有第一次授權或加了 prompt=consent 才會給
|
|
'google_token_expires_at' => now()->addSeconds($googleUser->expiresIn),
|
|
]
|
|
);
|
|
|
|
if ($googleUser->refreshToken) {
|
|
$user->update(['google_refresh_token' => $googleUser->refreshToken]);
|
|
}
|
|
|
|
$token = $user->createToken('auth_token')->plainTextToken;
|
|
|
|
// 把 token 帶回前端
|
|
return redirect(env('APP_URL') . "/#/auth/callback?token={$token}&name=" . urlencode($user->name));
|
|
}
|
|
} |