From 535dbda6b48171f8115b455e54790de94d97d42a Mon Sep 17 00:00:00 2001 From: Murilo Ijanc Date: Sun, 26 Jul 2026 16:41:48 -0300 Subject: Initial import --- includes/class-cepis-woo-rest.php | 120 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 120 insertions(+) create mode 100644 includes/class-cepis-woo-rest.php (limited to 'includes/class-cepis-woo-rest.php') diff --git a/includes/class-cepis-woo-rest.php b/includes/class-cepis-woo-rest.php new file mode 100644 index 0000000..561ca7e --- /dev/null +++ b/includes/class-cepis-woo-rest.php @@ -0,0 +1,120 @@ +[A-Za-z0-9]{1,64})/(?P[0-9]{8})', + array( + 'methods' => WP_REST_Server::READABLE, + 'callback' => array( self::class, 'lookup' ), + 'permission_callback' => array( self::class, 'permitted' ), + 'args' => array( + 'token' => array( + 'type' => 'string', + 'required' => true, + 'sanitize_callback' => 'sanitize_key', + ), + 'cep' => array( + 'type' => 'string', + 'required' => true, + 'sanitize_callback' => 'sanitize_key', + 'validate_callback' => static fn( $value ): bool => 1 === preg_match( '/^[0-9]{8}$/', (string) $value ), + ), + ), + ) + ); + } + + /** + * Reject anything that does not carry a live token. + * + * @param WP_REST_Request $request Incoming request. + * + * @return true|WP_Error True when the token checks out. + */ + public static function permitted( WP_REST_Request $request ): bool|WP_Error { + if ( Cepis_Woo_Token::verify( (string) $request['token'] ) ) { + return true; + } + + return new WP_Error( + 'cepis_invalid_token', + __( 'Lookup token missing, invalid or expired. Reload the page.', 'cepis-woocommerce' ), + array( 'status' => 403 ) + ); + } + + /** + * Answer one lookup. + * + * @param WP_REST_Request $request Incoming request. + */ + public static function lookup( WP_REST_Request $request ): WP_REST_Response { + $result = Cepis_Woo_Lookup::resolve( (string) $request['cep'] ); + + $response = new WP_REST_Response( $result['body'], $result['status'] ); + $response->header( 'Cache-Control', 'no-store' ); + + if ( null !== $result['retry_after'] ) { + $response->header( 'Retry-After', (string) $result['retry_after'] ); + } + + return $response; + } + + /** + * The API root to hand the browser, with a live token already in it. + * + * Shaped so that appending `/{cep}` to it reaches this route, which is what + * the widget does with its `baseUrl`. + */ + public static function base_url(): string { + return untrailingslashit( rest_url( self::NAMESPACE_V1 . '/lookup/' . Cepis_Woo_Token::create() ) ); + } +} -- cgit v1.3