0

I've run into an odd situation with user capabilities. I have set up a rest endpoint on my local computer and am the super admin. The rest endpoint is called and the first thing it does is see if users can make posts (as this is what will happen with this call).

I used the following code:

    if(!current_user_can('publish_posts')){
        return array('reply'=>0,'error'=>'Forbidden','code'=>'403');
    }

I get back the Forbidden message. I know I am logged in as the form is hidden behind the exact same check.

Client side:

    var idata = {};
    idata['url']    = form.find('#attachment').val();
    idata['nOnce']  = form.find('#nOnce').val();
    // snip (etc.)
    jQuery.ajax({
        type: "POST",
        url: vars.path+'/post',
        data: JSON.stringify(idata),
        contentType: "application/json; charset=utf-8",
        crossDomain: true,
        dataType: "json",
        success: function (data, status, jqXHR) {
            // snip
        },

        error: function (jqXHR, status) {
            // snip
        }
    });

Are cookies not sent with the AJAX call (I'm using jQuery client-side) and if not how do I make sure they send too?

How can I make sure that the user using my form is recognised as the current user?

1

No, you are not passing cookies with jQuery AJAX calls .. certainly not via Cross-domain access.

If you're going to use jQuery to pass data, you need to pass the current user ID and use get_userdata($userid) to determine whether the user has the correct capabilities.

Server side:

$jQuery_user = get_userdata($_POST['user_id']);
if(!user_can($jQuery_user,'publish_posts')){
   return array('reply'=>0,'error'=>'Forbidden','code'=>'403');
}

Client side:

// Be sure your form can somehow provide the currently logged in user id, hidden or otherwise.
var idata = {};
idata['url']    = form.find('#attachment').val();
idata['nOnce']  = form.find('#nOnce').val();
// if you have a nonce, you should be able to get user_id
iData['user_id'] = jQuery('#user_id').val(); 
// snip (etc.)
jQuery.ajax({
    type: "POST",
    url: vars.path+'/post',
    data: JSON.stringify(idata),
    contentType: "application/json; charset=utf-8",
    crossDomain: true,
    dataType: "json",
    success: function (data, status, jqXHR) {
        // snip
    },

    error: function (jqXHR, status) {
        // snip
    }
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.