Search code examples
javascriptajaxextjsextjs3

Prevent AJAX calls when users are not logged in


ExtJS version: 3.2.1 (I know it's old... I cannot change this yet)

I am trying to prevent ajax calls once a user's authentication is no longer valid (either timed out or logged out)

When I override Ext.Ajax.response globally, that gets overwritten when I create a new Ext.Ajax call.

Ext.override(Ext.Ajax.request, {
    success: function(response, opts) {
        console.log('Override function');
        /* redirects to login page */
    }
});

/* lots of other code */

Ext.Ajax.request({
    url: '/my_ajax_url',
    params: {type: 'producer'},
    success: function(r) {
        console.log('my function that does lots of stuff');
    }
});

I am trying to prevent myself from going through hundreds of files (130MB of nothing but code) changing all Ext.Ajax and Ext.data.JsonStore instances to call some sort of 'parent' function before everything.

I have also tried changing the response from returning a JSON object to returning an http error "HTTP/1.1 419 Authentication Timeout". I think this should be the way to go but I cannot get the 419 error to be 'caught' (I don't know exactly what to override to achieve this.)


Solution

  • There are a couple of events on Ext.Ajax, where you can attach global listeners.

    To prevent requests from being fired you can use beforerequest and return false in your listener:

    Ext.Ajax.on({
        'beforerequest': function() {
            if (!loggedIn) {
                return false; // prevents request
            }
        }
    });
    

    There's also requestcomplete and requestexception, where you could check for the HTTP status code (don't know which of the two a HTTP 419 would fire):

    Ext.Ajax.on({
        'requestcomplete': function(conn, response) {
            if (response.status == 419) {
                // redirection to login page
            }
        }
    });
    

    (documentation links are for 3.4.0, but all events should be available in 3.2.1 as well)

    Edit: Documentation for ExtJS v3.2.1