samedi 2 décembre 2017

InvalidAuthenticityToken, Ajax, Rails 5 with Device

I am using Ajax authentication with Rails 5 and Devise. The table users has column blocked and if the user is blocked he will be logged out. I have set header for Ajax globally:

$(document).ajaxSend(function(e, xhr, options) {
    var token = $("meta[name='csrf-token']").attr("content");
    xhr.setRequestHeader("X-CSRF-Token", token);
});

This is the replaced create method in SessionsController:

def create  
    if warden.authenticate(:scope => resource_name)
        if current_user.blocked
            sign_out(@user)
            return render json: {blocked: true}
        else
            return render json:{success: true}
        end
    else
        return render json: {error: true}
    end
end

If the user is blocked and he tries to authenticate the response from the server is {blocked: true}. Without refreshing the page, if he tries again the response is an error :

ActionController::InvalidAuthenticityToken in Users::SessionsController#create ActionController::InvalidAuthenticityToken Extracted source (around line #195):

I see in the headers that the token is send every time when user tries to login. I know that may be the problem is because after first time login the token is changed, but because the request is with Ajax it can get the new token, but I don't know how to fix that.

Aucun commentaire:

Enregistrer un commentaire