Files
glastree/app/Http/Controllers/GoogleOAuthController.php
T

68 lines
2.2 KiB
PHP
Raw Normal View History

2026-06-15 11:14:35 +02:00
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Enums\GoogleService;
use App\Services\GoogleOAuthService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
class GoogleOAuthController extends Controller
{
public function __construct(
private readonly GoogleOAuthService $oauthService,
) {}
public function connect(GoogleService $service): RedirectResponse
{
$url = $this->oauthService->getAuthorizationUrl($service);
return redirect()->away($url);
}
public function callback(Request $request): RedirectResponse
{
$request->validate([
'code' => 'required|string',
'state' => 'required|string|in:' . implode(',', array_column(GoogleService::cases(), 'value')),
]);
$service = GoogleService::from($request->state);
try {
$this->oauthService->handleCallback($request->code, $service);
return redirect()->route('impostazioni.index', ['#google-services'])
->with('success', "Google {$service->label()} connected successfully.");
} catch (\Exception $e) {
return redirect()->route('impostazioni.index', ['#google-services'])
->with('error', 'Google OAuth error: ' . $e->getMessage());
}
}
public function revoke(GoogleService $service): RedirectResponse
{
try {
$this->oauthService->revoke($service);
return redirect()->route('impostazioni.index', ['#google-services'])
->with('success', "Google {$service->label()} revoked successfully.");
} catch (\Exception $e) {
return redirect()->route('impostazioni.index', ['#google-services'])
->with('error', 'Revocation error: ' . $e->getMessage());
}
}
public function status(): View
{
$services = [];
foreach (GoogleService::cases() as $service) {
$services[] = [
'service' => $service,
'authorized' => $this->oauthService->isAuthorized($service),
];
}
return view('google-oauth.status', ['services' => $services]);
}
}