get_app_url() . '/api/v1/oauth/authorize'; } /** * Get OAuth token URL */ private function get_oauth_token_url() { return Agents24x7_Config::get_api_url() . '/api/v1/oauth/token'; } /** * Option names */ const OPTION_API_TOKEN = 'agents24x7_api_token'; const OPTION_USER_DATA = 'agents24x7_user_data'; /** * Constructor */ public function __construct() { // Load configuration file require_once AGENTS24X7_PLUGIN_DIR . 'config.php'; add_action( 'admin_init', array( $this, 'handle_oauth_callback' ) ); } /** * Get the OAuth authorization URL * * @return string */ public function get_connect_url() { // Create a composite state parameter containing both OAuth state nonce and WordPress nonce // This satisfies WordPress plugin review requirements while maintaining OAuth security $state_data = array( 'oauth_nonce' => wp_create_nonce( 'agents24x7_oauth' ), 'wp_nonce' => wp_create_nonce( 'agents24x7_callback' ), ); $state = base64_encode( wp_json_encode( $state_data ) ); $callback_url = $this->get_callback_url(); $auth_url = $this->get_oauth_authorize_url(); // Debug: Log the URLs being used Agents24x7_Logger::debug( 'APP_URL: ' . ( defined('AGENTS24X7_APP_URL') ? AGENTS24X7_APP_URL : 'NOT DEFINED' ) ); Agents24x7_Logger::debug( 'Auth URL: ' . $auth_url ); return $auth_url . '?' . http_build_query( array( 'client_id' => self::CLIENT_ID, 'redirect_uri' => $callback_url, 'response_type' => 'code', 'state' => $state, 'scope' => 'wordpress:all', ) ); } /** * Handle OAuth callback from Agents24x7. * * This method implements dual nonce verification: * 1. WordPress nonce check (satisfies WordPress plugin requirements) * 2. OAuth state nonce check (standard OAuth security) * Both are embedded in the state parameter to maintain OAuth compatibility. */ public function handle_oauth_callback() { // Only proceed on our plugin's settings page and OAuth action. if ( empty( $_GET['page'] ) || $_GET['page'] !== 'agents24x7' || empty( $_GET['action'] ) || $_GET['action'] !== 'oauth_callback' ) { return; } $this->popup_callback = isset( $_GET['a24x7_popup'] ) && '1' === $_GET['a24x7_popup']; // Only administrators can complete this OAuth flow. if ( ! current_user_can( 'manage_options' ) ) { wp_die( esc_html__( 'Unauthorized', 'agents24x7' ) ); } // Sanitize external inputs - nonce verification happens below after decoding state $code = isset( $_GET['code'] ) ? sanitize_text_field( wp_unslash( $_GET['code'] ) ) : ''; $state = isset( $_GET['state'] ) ? sanitize_text_field( wp_unslash( $_GET['state'] ) ) : ''; if ( ! $code || ! $state ) { Agents24x7_Logger::debug( 'Missing code or state' ); $this->redirect_with_error( esc_html__( 'Invalid OAuth response', 'agents24x7' ) ); return; } // Decode the composite state parameter $state_json = base64_decode( $state ); if ( $state_json === false ) { Agents24x7_Logger::debug( 'Failed to decode state parameter' ); $this->redirect_with_error( esc_html__( 'Invalid state parameter', 'agents24x7' ) ); return; } $state_data = json_decode( $state_json, true ); if ( ! is_array( $state_data ) || ! isset( $state_data['oauth_nonce'] ) || ! isset( $state_data['wp_nonce'] ) ) { Agents24x7_Logger::debug( 'Invalid state parameter structure' ); $this->redirect_with_error( esc_html__( 'Invalid state parameter', 'agents24x7' ) ); return; } // Verify WordPress nonce (for plugin review compliance) if ( ! wp_verify_nonce( $state_data['wp_nonce'], 'agents24x7_callback' ) ) { Agents24x7_Logger::debug( 'Invalid WordPress nonce' ); $this->redirect_with_error( esc_html__( 'Security check failed', 'agents24x7' ) ); return; } // Verify OAuth state nonce (standard OAuth security) if ( ! wp_verify_nonce( $state_data['oauth_nonce'], 'agents24x7_oauth' ) ) { Agents24x7_Logger::debug( 'Invalid OAuth state nonce' ); $this->redirect_with_error( esc_html__( 'Invalid state parameter', 'agents24x7' ) ); return; } // All checks passed—exchange the code for an access token. Agents24x7_Logger::debug( 'Exchanging OAuth code for token' ); $this->exchange_code_for_token( $code ); } /** * Exchange authorization code for access token * * @param string $code Authorization code */ private function exchange_code_for_token( $code ) { $callback_url = $this->get_callback_url(); $token_url = $this->get_oauth_token_url(); $response = wp_remote_post( $token_url, array( 'headers' => array( 'Content-Type' => 'application/x-www-form-urlencoded', ), 'body' => array( 'grant_type' => 'authorization_code', 'code' => $code, 'redirect_uri' => $callback_url, 'client_id' => self::CLIENT_ID, ), 'timeout' => 30, ) ); if ( is_wp_error( $response ) ) { $error_message = 'Network Error: ' . $response->get_error_message(); Agents24x7_Logger::error( 'OAuth token exchange failed before receiving an HTTP response.' ); $this->redirect_with_error( $error_message ); return; } $response_code = wp_remote_retrieve_response_code( $response ); $response_body = wp_remote_retrieve_body( $response ); // Check for HTTP error status codes if ( $response_code >= 400 ) { $error_message = 'HTTP Error ' . $response_code . ' from OAuth server'; Agents24x7_Logger::error( 'OAuth token exchange failed with HTTP status ' . $response_code . '.' ); $this->redirect_with_error( $error_message ); return; } $data = json_decode( $response_body, true ); if ( ! $data ) { $error_message = 'Invalid JSON response from OAuth server'; Agents24x7_Logger::error( 'OAuth token exchange returned invalid JSON (HTTP status ' . $response_code . ').' ); $this->redirect_with_error( $error_message ); return; } if ( isset( $data['error'] ) ) { $error_message = isset( $data['error_description'] ) ? $data['error_description'] : ( 'OAuth Error: ' . $data['error'] ); $candidate_error_code = is_string( $data['error'] ) ? sanitize_key( $data['error'] ) : ''; $known_error_codes = array( 'invalid_request', 'invalid_client', 'invalid_grant', 'unauthorized_client', 'unsupported_grant_type', 'invalid_scope', 'server_error', 'temporarily_unavailable', ); $error_code = in_array( $candidate_error_code, $known_error_codes, true ) ? $candidate_error_code : 'other'; Agents24x7_Logger::error( sprintf( 'OAuth server returned error (HTTP status %d, code %s).', $response_code, $error_code ?: 'unknown' ) ); $this->redirect_with_error( $error_message ); return; } if ( ! isset( $data['access_token'] ) ) { $error_message = 'No access token received from OAuth server'; Agents24x7_Logger::error( 'OAuth token exchange returned no access token (HTTP status ' . $response_code . ').' ); $this->redirect_with_error( $error_message ); return; } // Log successful token exchange Agents24x7_Logger::success( 'Successfully received access token from OAuth server' ); // Store the token $this->store_token( $data ); // Existing agents skip onboarding, so consent must refresh their site credentials here. $integration = new Agents24x7_Integration(); $credentials = $integration->get_wordpress_credentials(); if ( is_wp_error( $credentials ) ) { $this->redirect_with_error( $credentials->get_error_message() ); return; } $reconnect = wp_remote_post( Agents24x7_Config::get_api_url() . '/wordpress/api', array( 'headers' => array_merge( $this->get_auth_headers(), array( 'Content-Type' => 'application/json', 'X-WordPress-Site' => home_url(), 'X-WordPress-WooCommerce' => class_exists( 'WooCommerce' ) ? 'true' : 'false', ) ), 'body' => wp_json_encode( array( 'type' => 'action', 'functionName' => 'wordpress/plugin:reconnectFromPlugin', 'args' => array( 'siteUrl' => $credentials['baseUrl'], 'username' => $credentials['username'], 'password' => $credentials['password'], 'hasWoocommerce' => class_exists( 'WooCommerce' ) ), ) ), 'timeout' => 60, ) ); $reconnect_data = is_wp_error( $reconnect ) ? null : json_decode( wp_remote_retrieve_body( $reconnect ), true ); if ( is_wp_error( $reconnect ) || wp_remote_retrieve_response_code( $reconnect ) !== 200 || ! is_array( $reconnect_data ) || ! isset( $reconnect_data['data']['reconnected'] ) ) { $integration->finish_password_rotation( $credentials['rotationId'], false ); $this->redirect_with_error( esc_html__( 'Could not reconnect the site. Please try again.', 'agents24x7' ) ); return; } $finished = $integration->finish_password_rotation( $credentials['rotationId'], ! empty( $reconnect_data['data']['reconnected'] ) ); if ( is_wp_error( $finished ) ) { $integration->release_password_rotation_lock( $credentials['rotationId'] ); } $this->redirect_with_success(); } /** * Store the API token * * @param array $token_data Token response data */ private function store_token( $token_data ) { update_option( self::OPTION_API_TOKEN, array( 'token' => $token_data['access_token'], 'type' => $token_data['token_type'], 'scope' => isset( $token_data['scope'] ) ? $token_data['scope'] : 'wordpress:all', 'created_at' => time(), ) ); } /** * Get the stored API token * * @return string|null */ public function get_token() { $token_data = get_option( self::OPTION_API_TOKEN ); if ( ! $token_data || ! isset( $token_data['token'] ) ) { return null; } return $token_data['token']; } /** * Check if authenticated * * @return bool */ public function is_authenticated() { return ! is_null( $this->get_token() ); } /** * Disconnect (remove token) */ public function disconnect() { do_action( 'agents24x7_disconnecting' ); delete_option( self::OPTION_API_TOKEN ); delete_option( self::OPTION_USER_DATA ); } /** * Redirect with error message * * @param string $message Error message */ private function redirect_with_error( $message ) { // Store error message in transient (expires in 30 seconds) set_transient( 'agents24x7_message', array( 'type' => 'error', 'text' => $message, ), 30 ); if ( $this->popup_callback ) { $this->return_to_popup( false ); } wp_redirect( admin_url( 'admin.php?page=agents24x7' ) ); exit; } /** * Redirect with success message */ private function redirect_with_success() { // Store success message in transient (expires in 30 seconds) set_transient( 'agents24x7_message', array( 'type' => 'success', 'text' => 'Successfully connected to Agents24x7!', ), 30 ); if ( $this->popup_callback ) { $this->return_to_popup( true ); } wp_redirect( admin_url( 'admin.php?page=agents24x7' ) ); exit; } /** Build the exact callback URI used for both authorization and exchange. */ private function get_callback_url() { return admin_url( 'admin.php?page=agents24x7&action=oauth_callback&a24x7_popup=1' ); } /** Send the popup result to the same WordPress admin origin, then close. */ private function return_to_popup( $ok ) { $admin_url_parts = wp_parse_url( admin_url() ); $origin = $admin_url_parts['scheme'] . '://' . $admin_url_parts['host']; if ( ! empty( $admin_url_parts['port'] ) ) { $origin .= ':' . $admin_url_parts['port']; } nocache_headers(); status_header( 200 ); $target_origin = wp_json_encode( $origin ); $fallback_url = wp_json_encode( admin_url( 'admin.php?page=agents24x7' ) ); $result = $ok ? 'true' : 'false'; echo 'Agents24x7'; echo '

' . esc_html__( 'Returning to WordPress…', 'agents24x7' ) . '

'; echo ''; echo ''; exit; } /** * Get authorization header for API requests * * @return array */ public function get_auth_headers() { $token = $this->get_token(); if ( ! $token ) { return array(); } return array( 'Authorization' => 'Bearer ' . $token, ); } }