6

I am trying to create a Facebook JS-SDK based auto login feature. When user is "Connected" passing FbID and aother user data to an ajax function which creates the session cookie. Cookie is created (I can see "wordpress_logged_in_.... cookie" in the browser inspector) but when I reload the page the user is still logged out.

Do you have idea why?

JavaScript

function ajaxloginFB(uid,email,first_name,last_name) {
    data =  "uid=" + uid + "&" + "name=" + last_name + " " + first_name + "&" + "email=" + email + "&" + $.param({ action: 'facebook_login', nonce: ajax_object.ajaxnonce });
    $.ajax({
        url : ajax_object.ajaxurl,
        type: "post",
        data : data,
        success:function(response){
            var response = $.parseJSON(response);
            if (response.success == true){
                window.location.reload();
            }
        }
    });
}

PHP

add_action( 'wp_ajax_facebook_login', 'facebook_ajax_login_or_register' );
add_action( 'wp_ajax_nopriv_facebook_login', 'facebook_ajax_login_or_register' );

function facebook_ajax_login_or_register(){
  $uid = sanitize_text_field( $_POST['uid'] );
  $args = array(
    'meta_key'     => 'fbuid',
    'meta_value'   => $uid,
    'meta_compare' => '=',
  );
  $fb_user = get_users($args);
  $current_user_id = $fb_user[0];
  wp_set_auth_cookie( $current_user_id, true );
  $response[success] = true;
  echo json_encode($response);
  die();
}
  • For one you need to use wp_signon() before setting the auth cookie. Second, it may not work in ajax because cookies are set by sending headers. – Tim Hallman Oct 17 '16 at 18:39
2

I add one function wp_set_current_user for setting up current user.

add_action( 'wp_ajax_facebook_login', 'facebook_ajax_login_or_register' );
add_action( 'wp_ajax_nopriv_facebook_login', 'facebook_ajax_login_or_register' );

function facebook_ajax_login_or_register(){
  $uid = sanitize_text_field( $_POST['uid'] );
  $args = array(
    'meta_key'     => 'fbuid',
    'meta_value'   => $uid,
    'meta_compare' => '=',
  );
  $fb_user = get_users($args);
  $current_user_id = $fb_user[0];
  wp_set_current_user($current_user_id);//Set current user
  wp_set_auth_cookie( $current_user_id, true );
  $response[success] = true;
  echo json_encode($response);
  die();
}

I'm not tested this so let me know if still you facing same issue.

0

I use ajax with xhr authentication header for my custom wp login

$.ajax({
     url : ajax_object.ajaxurl,
    type: "post",
    data: data,
    contentType: 'application/x-www-form-urlencoded',
    xhrFields: {withCredentials: true}
});

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.