oauthManager = $oauthManager; $this->stateManager = $stateManager; $this->connectionRepository = $connectionRepository; } /** * Process the Google OAuth redirect callback. * * @return void */ public function handleCallback(): void { // 1. Verify capability. if (!current_user_can('manage_options')) { wp_die(esc_html__('You do not have permission to access this page.', '1-click-form-sync'), 403); } $state = sanitize_text_field($_GET['state'] ?? ''); $code = sanitize_text_field($_GET['code'] ?? ''); $accessToken = sanitize_text_field($_GET['access_token'] ?? ''); $refreshToken = sanitize_text_field($_GET['refresh_token'] ?? ''); $expiresIn = (int)($_GET['expires_in'] ?? 3600); $email = sanitize_email($_GET['email'] ?? ''); if (!$state || (!$code && !$accessToken)) { $this->redirectWithError('missing_parameters'); return; } // 2. Verify state parameter (CSRF check). $connectionId = $this->stateManager->verifyState($state); if (!$connectionId) { $this->redirectWithError('invalid_state'); return; } $connection = $this->connectionRepository->find($connectionId); if (!$connection) { $this->redirectWithError('connection_not_found'); return; } try { if ($accessToken) { // 3. One-Click authorization tokens received directly from the Proxy. $connection->setAccessToken($accessToken); if ($refreshToken) { $connection->setRefreshToken($refreshToken); } if ($email) { $connection->setEmail($email); } $connection->setClientId(''); // Empty client ID flags it as proxy-based $connection->setClientSecret(''); $connection->setStatus('active'); $connection->setLastError(null); // Cache access token inside transient. set_transient('oneclickformsync_access_token_' . $connection->getId(), $accessToken, $expiresIn - 60); $this->connectionRepository->save($connection); } else { // 3. Exchange OAuth authorization code locally (custom credentials). $this->oauthManager->exchangeCodeForTokens($connection, $code); } // Redirect back on success. wp_safe_redirect( add_query_arg( [ 'page' => '1-click-form-sync-connections', 'oneclickformsync_oauth_success' => '1', ], admin_url('admin.php') ) ); exit; } catch (Exception $e) { $this->redirectWithError('exchange_failed', $e->getMessage()); } } /** * Redirect to the settings page with error details. * * @param string $errorType * @param string $message * @return void */ private function redirectWithError(string $errorType, string $message = ''): void { $args = [ 'page' => '1-click-form-sync-connections', 'oneclickformsync_oauth_error' => $errorType, ]; if ($message !== '') { $args['oneclickformsync_oauth_msg'] = urlencode(substr($message, 0, 200)); } wp_safe_redirect(add_query_arg($args, admin_url('admin.php'))); exit; } }