• Resolved b3hr4d

    (@b3hr4d)


    i have read wordpress page about this but didn’t find my solution ( because im stupid ?? )
    here is my problem details:

    schema :

    public function user_playtime_meta_schema() {
        if ( $this->playtime_schema ) {
            return $this->playtime_schema;
        }
        $this->playtime_schema = array(
            'type' => array(
                'type'       => 'object',
                'properties' => array(
                    'song'     => array(
                        'type'       => 'object',
                        'properties' => array(
                            'name'  => array(
                                'type' => 'string',
                            ),
                            'id'    => array(
                                'type' => 'number',
                            ),
                            'notes' => array(
                                'type' => 'number',
                            ),
                        ),
                    ),
                    'time'     => array(
                        'type' => 'string',
                    ),
                    'date'     => array(
                        'type' => 'string',
                    ),
                    'score'    => array(
                        'type' => 'string',
                    ),
                    'progress' => array(
                        'type' => 'string',
                    ),
                ),
            ),
        );
        return $this->playtime_schema;
    }

    register rest route:

    register_rest_route(
                '/jwt-auth/v1',
                '/user',
                array(
                    'methods'             => array( 'GET', 'POST', 'PUT' ),
                    'callback'            => array( $this, 'user_get_information' ),
                    'permission_callback' => function() {
                        return is_user_logged_in();
                    },
                ),
            );

    user function :

    public function user_get_information( $request ) {
        $user_id = get_current_user_id();
        $data    = array();
        if ( filter_input( INPUT_SERVER, 'REQUEST_METHOD' ) === 'POST' ) {
            $params = array(
                'nickname',
                'first_name',
                'last_name',
                'mobile',
                'favorites',
                'playtime',
            );
    
            $allreq = $request->get_params();
    
            foreach ( $allreq as $req => $val ) {
                if ( ! empty( $val ) && in_array( $req, $params, true ) ) {
                    if ( 'favorites' === $req ) {
                        // do somthing
                    } elseif ( 'playtime' === $req ) { 
    
    // i want this json data sanitized then save into database
    
                        $meta      = get_user_meta( $user_id, 'playtime', true );
                        $schema    = $this->user_playtime_meta_schema();
                        if ( rest_validate_value_from_schema( $val, $schema ) ) {
                            $sanitized = rest_sanitize_value_from_schema( $val, $schema );
                        }
                        if ( ! is_array( $meta ) ) {
                            $meta = array();
                        }
                        $meta[] = $sanitized;
                        // $meta = array();
                    } else {
                        $meta = $val;
                    }
                    $user_meta = update_user_meta( $user_id, 'playtime', $meta );
                }
            }
        }
        if ( is_wp_error( $user_meta ) ) {
            $error_string = $user_meta->get_error_message();
            return $error_string;
        } else {
            $info   = get_user_by( 'ID', $user_id );
            $meta   = get_user_meta( $user_id );
            $img_id = $meta['image_select'][0];
            if ( $img_id ) {
                $img_url = wp_get_attachment_url( $img_id );
            }
            $data['id']           = $info->ID;
            $data['login']        = $info->user_login;
            $data['email']        = $info->user_email;
            $data['display_name'] = $info->display_name;
            $data['image']        = $img_url;
            $data['nickname']     = $meta['nickname'][0];
            $data['first_name']   = $meta['first_name'][0];
            $data['last_name']    = $meta['last_name'][0];
            $data['mobile']       = $meta['mobile'][0];
            $data['favorites']    = get_user_meta( $user_id, 'favorites', true );
            $data['playtime']     = get_user_meta( $user_id, 'playtime', true );
            return $data;
        }
    }

    try send data like this:

    {"playtime":{"song": {
            "name": "Training New",
            "id": 758,
            "notes": 65
        },
        "time": "10:27:19 PM",
        "score": "[[76,\"perfect\"],[74,\"perfect\"],[77,\"perfect\"],[76,\"perfect\"],[74,\"late\"],[72,\"late\"],[74,\"perfect\"],[76,\"perfect\"],[76,\"perfect\"],[76,\"perfect\"],[74,\"perfect\"],[77,\"perfect\"],[76,\"late\"],[74,\"late\"],[72,\"perfect\"],[74,\"perfect\"],[76,\"perfect\"],[76,\"perfect\"],[74,\"perfect\"],[72,\"perfect\"],[71,\"perfect\"],[67,\"perfect\"],[74,\"perfect\"],[72,\"perfect\"],[74,\"perfect\"],[71,\"perfect\"],[72,\"perfect\"],[74,\"late\"],[71,\"perfect\"],[72,\"perfect\"],[71,\"late\"],[67,\"perfect\"]]",
        "date": "8/17/2020",
        "progress": "4%"}
    }

    everything works , but if i send some bad information like this :

        {"playtime":{"wrong": {
            "number": "1",
            "notes": 525
        },
        "time": "10:27:19 PM",
        "progress": "4%"}
    }

    also works and wrong data would be saved in database!

    sorry about messy question , any help thanks in advance.

Viewing 4 replies - 1 through 4 (of 4 total)
  • Moderator bcworkz

    (@bcworkz)

    Ha! Based on the information provided, you couldn’t possibly be stupid. Bewildered maybe ??

    You cannot effectively validate JSON containing multiple fields as JSON. Minimal sanitation might be feasible, but for validation and sanitation to be most effective, you should parse the JSON into an array or object and validate and sanitize each field according to what sort of data it is supposed to contain. As you are probably aware, there are a number of sanitize_*() functions for various data types. But nothing for JSON because that’s not really a data type, but a data format.

    Thread Starter b3hr4d

    (@b3hr4d)

    Omg thank you so much, that’s relief ??

    So how can i use wordpress logic to make this works ?

    I did this on default REST API and it works so good!

    register_meta(
    	'user',
    	'playtime',
    	array(
    	'type'         => 'object',
    	'single'       => false,
    	'show_in_rest' => array(
    		'schema' => $this->user_playtime_meta_schema(),
    	   ),
    	)
    );

    What’s your suggestion for doing in custom endpoint?

    • This reply was modified 3 years, 11 months ago by b3hr4d.
    Moderator bcworkz

    (@bcworkz)

    If you’ve not seen it yet, review this:
    https://developer.www.ads-software.com/rest-api/extending-the-rest-api/adding-custom-endpoints/

    TBH, I’ve limited experience with custom API routes/endpoints, so the following may be inaccurate. It’s my understanding the API engine decodes the sent JSON data for you. You’ll be dealing with individual object properties in a collection. You would assign validation and sanitation callbacks according to each individual property. At least that’s what it looks like at the end of the final example on the above linked page, the get_collection_params() method.

    The API engine then re-encodes the response data into JSON when appropriate. Within your custom endpoint code you never deal directly with JSON data even though that’s how the API communicates.

    Thread Starter b3hr4d

    (@b3hr4d)

    Thank you so much for your patience!

    Yes this example should work for me.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘What is poper way to validate and sanitize json post from rest api’ is closed to new replies.