repository = $repository; } /** * Get the OAuth redirect URI for this site. * * @return string */ public function getRedirectUri(): string { return admin_url('admin-post.php?action=oneclickformsync_oauth_callback'); } /** * Get the authorization URL to redirect users to Google. * * @param string $clientId * @param string $state * @return string */ public function getAuthorizationUrl(string $clientId, string $state): string { $scopes = apply_filters('oneclickformsync_google_scopes', [ 'openid', 'email', 'https://www.googleapis.com/auth/spreadsheets' ]); $params = [ 'client_id' => $clientId, 'redirect_uri' => $this->getRedirectUri(), 'response_type' => 'code', 'scope' => implode(' ', $scopes), 'state' => $state, 'access_type' => 'offline', 'prompt' => 'consent', ]; return 'https://accounts.google.com/o/oauth2/v2/auth?' . http_build_query($params); } /** * Get the authorization URL to redirect users to the self-hosted OAuth Proxy. * * @param string $state * @return string */ public function getProxyAuthorizationUrl(string $state): string { $params = [ 'site_url' => $this->getRedirectUri(), 'state' => $state, ]; return 'https://auth-gsheet.fectodigital.com/index.php?' . http_build_query($params); } /** * Get a valid access token for a connection. * Automatically refreshes the token if expired or close to expiration. * * @param Connection $connection * @return string Access token. * @throws GoogleAuthenticationException */ public function getAccessToken(Connection $connection): string { $transientKey = 'oneclickformsync_access_token_' . $connection->getId(); $cachedToken = get_transient($transientKey); if ($cachedToken && is_string($cachedToken)) { return $cachedToken; } return $this->refreshAccessToken($connection); } /** * Exchange authorization code for access and refresh tokens. * * @param Connection $connection * @param string $code * @return Connection Loaded Connection entity. * @throws GoogleAuthenticationException */ public function exchangeCodeForTokens(Connection $connection, string $code): Connection { $response = wp_remote_post('https://oauth2.googleapis.com/token', [ 'body' => [ 'code' => $code, 'client_id' => $connection->getClientId(), 'client_secret' => $connection->getClientSecret(), 'redirect_uri' => $this->getRedirectUri(), 'grant_type' => 'authorization_code', ], 'timeout' => 15, ]); if (is_wp_error($response)) { throw new GoogleAuthenticationException(esc_html($response->get_error_message())); } $body = json_decode(wp_remote_retrieve_body($response), true); $statusCode = wp_remote_retrieve_response_code($response); if ($statusCode !== 200 || empty($body['access_token'])) { $errorDesc = $body['error_description'] ?? ($body['error'] ?? 'Unknown token exchange error'); throw new GoogleAuthenticationException(esc_html($errorDesc)); } $connection->setAccessToken($body['access_token']); if (!empty($body['refresh_token'])) { $connection->setRefreshToken($body['refresh_token']); } // Set email by decoding id_token if available. if (!empty($body['id_token'])) { $email = $this->getEmailFromIdToken($body['id_token']); if ($email) { $connection->setEmail($email); } } else { // Fallback: Fetch email using OAuth userinfo API. $email = $this->fetchEmailUsingToken($body['access_token']); if ($email) { $connection->setEmail($email); } } $connection->setStatus('active'); $connection->setLastError(null); // Cache access token inside transient. $expiresIn = (int)($body['expires_in'] ?? 3600); set_transient('oneclickformsync_access_token_' . $connection->getId(), $body['access_token'], $expiresIn - 60); $this->repository->save($connection); return $connection; } /** * Refresh access token using refresh token. * * @param Connection $connection * @return string The new access token. * @throws GoogleAuthenticationException */ public function refreshAccessToken(Connection $connection): string { if (!$connection->getRefreshToken()) { $connection->setStatus('error'); $connection->setLastError('Missing refresh token.'); $this->repository->save($connection); throw new GoogleAuthenticationException('Connection does not have a refresh token.'); } if (!$connection->getClientId()) { // Refresh token via the self-hosted proxy $response = wp_remote_post('https://auth-gsheet.fectodigital.com/refresh.php', [ 'body' => [ 'refresh_token' => $connection->getRefreshToken(), ], 'timeout' => 15, ]); } else { // Refresh token directly using local custom credentials $response = wp_remote_post('https://oauth2.googleapis.com/token', [ 'body' => [ 'refresh_token' => $connection->getRefreshToken(), 'client_id' => $connection->getClientId(), 'client_secret' => $connection->getClientSecret(), 'grant_type' => 'refresh_token', ], 'timeout' => 15, ]); } if (is_wp_error($response)) { throw new GoogleAuthenticationException(esc_html($response->get_error_message())); } $body = json_decode(wp_remote_retrieve_body($response), true); $statusCode = wp_remote_retrieve_response_code($response); if ($statusCode !== 200 || empty($body['access_token'])) { $errorDesc = $body['error_description'] ?? ($body['error'] ?? 'Unknown token refresh error'); // Handle revoked grants. if (isset($body['error']) && in_array($body['error'], ['invalid_grant', 'unauthorized_client', 'access_denied'], true)) { $connection->setStatus('revoked'); } else { $connection->setStatus('error'); } $connection->setLastError($errorDesc); $this->repository->save($connection); throw new GoogleAuthenticationException(esc_html($errorDesc)); } $accessToken = $body['access_token']; $connection->setAccessToken($accessToken); // Preserve old refresh token if Google does not return a new one. if (!empty($body['refresh_token'])) { $connection->setRefreshToken($body['refresh_token']); } $connection->setStatus('active'); $connection->setLastError(null); // Cache access token inside transient. $expiresIn = (int)($body['expires_in'] ?? 3600); set_transient('oneclickformsync_access_token_' . $connection->getId(), $accessToken, $expiresIn - 60); $this->repository->save($connection); return $accessToken; } /** * Decode id_token JWT. * * @param string $idToken * @return string Email if found. */ private function getEmailFromIdToken(string $idToken): string { $parts = explode('.', $idToken); if (count($parts) >= 2) { $payload = base64_decode(str_replace(['-', '_'], ['+', '/'], $parts[1])); if ($payload) { $data = json_decode($payload, true); if (isset($data['email']) && is_string($data['email'])) { return $data['email']; } } } return ''; } /** * Fetch user email using access token from userinfo. * * @param string $accessToken * @return string Email. */ private function fetchEmailUsingToken(string $accessToken): string { $response = wp_remote_get('https://www.googleapis.com/oauth2/v2/userinfo', [ 'headers' => [ 'Authorization' => 'Bearer ' . $accessToken, ], 'timeout' => 10, ]); if (!is_wp_error($response) && wp_remote_retrieve_response_code($response) === 200) { $body = json_decode(wp_remote_retrieve_body($response), true); return $body['email'] ?? ''; } return ''; } }