Automattic\WooCommerce\Internal\MCP\Transport

WooCommerceRestTransport::authenticateprivateWC 1.0

Authenticate user using consumer key and secret.

Method of the class: WooCommerceRestTransport{}

No Hooks.

Returns

Int|\WP_Error. User ID on success, WP_Error on failure.

Usage

// private - for code of main (parent) class only
$result = $this->authenticate( $consumer_key, $consumer_secret );
$consumer_key(string) (required)
Consumer key.
$consumer_secret(string) (required)
Consumer secret.

WooCommerceRestTransport::authenticate() code WC 10.3.3

private function authenticate( $consumer_key, $consumer_secret ) {
	global $wpdb;

	// Hash the consumer key as WooCommerce does.
	$hashed_consumer_key = wc_api_hash( trim( (string) $consumer_key ) );

	// Query the WooCommerce API keys table directly.
	$user_data = $wpdb->get_row(
		$wpdb->prepare(
			"SELECT key_id, user_id, permissions, consumer_key, consumer_secret, nonces
			FROM {$wpdb->prefix}woocommerce_api_keys
			WHERE consumer_key = %s",
			$hashed_consumer_key
		)
	);

	// Check if user data was found.
	if ( empty( $user_data ) ) {
		return new \WP_Error(
			'authentication_failed',
			__( 'Authentication failed.', 'woocommerce' ),
			array( 'status' => 401 )
		);
	}

	// Validate consumer secret using hash_equals for timing attack protection.
	if ( ! hash_equals( $user_data->consumer_secret, trim( (string) $consumer_secret ) ) ) {
		return new \WP_Error(
			'authentication_failed',
			__( 'Authentication failed.', 'woocommerce' ),
			array( 'status' => 401 )
		);
	}

	// Store permissions for tool-level checking.
	self::$current_mcp_permissions = $user_data->permissions;

	// Ensure the user exists before switching context.
	$user = get_user_by( 'id', (int) $user_data->user_id );
	if ( ! $user ) {
		return new \WP_Error(
			'mcp_user_not_found',
			__( 'The user associated with this API key no longer exists.', 'woocommerce' ),
			array( 'status' => 401 )
		);
	}
	wp_set_current_user( $user->ID );

	return $user->ID;
}