Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
ExtJS 6: JSON Web Token API Login with Promises
Ext.define('App.security.Firewall', {
singleton: true,
requires: [
'App.security.TokenStorage'
],
isLoggedIn: function() {
return null !== App.security.TokenStorage.retrieve();
},
login: function(username, password) {
var deferred = new Ext.Deferred();
Ext.Ajax.request({
url: App.server.Router.generate('authenticate'),
method: 'POST',
jsonData: {
'username': username,
'password': password
},
success: function (response) {
var data = Ext.decode(response.responseText);
if (data.token) {
App.security.TokenStorage.save(data.token);
deferred.resolve(data, response);
} else {
deferred.reject(data, response);
}
},
failure: function (response) {
var data = Ext.decode(response.responseText);
App.security.TokenStorage.clear();
deferred.reject(data, response);
}
});
return deferred.promise;
},
logout: function(callback) {
App.security.TokenStorage.clear();
// The "old" way of using callbacks. You can easily rewrite this using Promise, too, see login method.
callback();
}
}, function () {
Ext.Ajax.on('beforerequest', function(conn, options) {
if (App.security.Firewall.isLoggedIn()) {
options.headers = options.headers || {};
options.headers['Authorization'] = 'Bearer ' + App.security.TokenStorage.retrieve();
}
});
});
Ext.define('App.view.login.LoginController', {
extend: 'Ext.app.ViewController',
alias: 'controller.login',
onLoginClick: function() {
var data = this.getView().down('form').getValues();
App.security.Firewall.login(data.username, data.password).then(function() {
this.getView().destroy();
Ext.create({
xtype: 'app-main'
});
}.bind(this), function(data) {
Ext.Msg.alert('Error', data.message || 'An error occurred while logging in.');
});
}
});
Ext.define('App.security.TokenStorage', {
singleton: true,
storageKey: 'json-web-token',
clear: function () {
localStorage.removeItem(this.storageKey);
},
retrieve: function() {
return localStorage.getItem(this.storageKey);
},
save: function (token) {
localStorage.setItem(this.storageKey, token);
}
});
@sseyha
Copy link

sseyha commented Aug 2, 2016

Hi,
It nice sample.
But i'm still new with "App.server.Router.generate('authenticate')"???
Could you share this code or sample please????
Thanks,
Seyha

@rattanchauhan
Copy link

rattanchauhan commented Oct 21, 2016

Hi sseyha,

I'm not sure if you still need it, but as I understand , App.server.Router.generate('authenticate') simply returns an endpoint url based on the key provided to it. So I guess the code can look like below:

Ext.define('App.server.Router', {
    singleton: true,
   hostname: 'hostname/api/',

   // method to generate URLs for endpoints
   generate: function (endpoint) {
        return this.hostname + endpoint;
    }
   // other utlity methods for routing


});

@havvg
Copy link
Author

havvg commented Oct 24, 2016

Hi @sseyha,

I'm sorry to reply so late, I didn't notice any comment on this gist. As @rattanchauhan mentioned, it's a pretty simple object:

Ext.define('App.server.Router', {
    singleton: true,
    endpoint: Ext.manifest.server.endpoint,

    routes: {
        'authenticate': '/authenticate'
        // generated list, static list .. your choice :)
    },

    generate: function(route, params) {
        // Whatever logic to determine the full URI.
        // For example, simple lookup:
        return this.endpoint + this.routes[route];
    }
});

Example using http://symfony.com/doc/current/bundles/FOSJsRoutingBundle/usage.html (with Symfony server side):

Ext.define('App.server.Router', {
    singleton: true,

    generate: function(route, params) {
        return Routing.generate(route, params);
    }
});

@albert840702
Copy link

albert840702 commented Nov 24, 2017

Where is the App.security.Firewall.isLoggedIn() ??

@hlkn
Copy link

hlkn commented Jan 21, 2018

I have trouble to store and extract token using the App.security.TokenStorage with localStorage. May you help to look into using localStorage or Do I miss something from your code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment