Orchestrating Login and Roles-Based Security in Ext JS and Sencha Touch

The issue of logins and roles-based security often comes up in my Ext JS and Sencha Touch classes. The sad reality is that anyone who knows how to open the browser’s JavaScript debugger is able to “hack” your application. Therefore, security is something that *must& be handled at the application-server level as there is no current method to adequately secure your JavaScript code.

Having said that, most corporate apps still require logins and roles-based security as functional requirements. A user must enter credentials and their button/menu selections need to be tailored to a specified role as illustrated by the following video:

Typically, your app.js file simply invokes a login dialog as illustrated by the following code snippet:

// code listing 1: app.js
Ext.application({
    controllers: ["Main"],
    views: ["Main"],
    name: 'LoginAppDemo',
    autoCreateViewport: false,
    launch: function() {
    	Ext.create("LoginAppDemo.view.LoginForm")
    }
});

Let’s also assume that we’re going to put together a simple login form inside of a floating window. Why a floating window, you ask? Because login forms are always cooler if they float and are draggable, of course!

// code listing 2: LoginForm.js
Ext.define("LoginAppDemo.view.LoginForm", {
 extend: 'Ext.window.Window',
 alias: 'widget.loginform',
 requires: ['Ext.form.Panel'],
 title: 'Please Log In',
 autoShow: true,
 height: 150,
 width: 300,
 closable: false,
 resizable: false,
 layout: 'fit',
 items: [
  {
   xtype: 'form',
   bodyPadding: 5,
   defaults: {
    xtype: 'textfield',
    anchor: '100%'
   },
   items: [
    {
     fieldLabel: 'User Name:',
     name: 'username',
     allowBlank: false
    },
    {
     fieldLabel: 'Password:',
     name: 'password',
     allowBlank: false
    },
   ],
   buttons: [
    {
     text: 'Log in',
     formBind: true,
     disabled: true,
     handler: function(b,e) {
      var formDialog = b.up('loginform');
      var form = b.up('form');
      
      // fire custom event for the controller to handle
      formDialog.fireEvent('login',formDialog,form,form.getValues());
     } // handler
    } // login button
   ] // buttons 
  } // form
 ] // items
}) 

Note that in the preceding example, when the user clicks the ‘Log in’ button, I fire a custom ‘login’ event and pass references to the login window, the login credentials form, and the data that the user entered into the form up to the controller (listed below).

From within the login handler, I make an Ajax call to the server in order to retrieve information about the user profile. In a production environment you would make this call via HTTPS to your application server (.php,.aspx,.jsp,.cfc, etc.).

// code listing 3
Ext.define('LoginAppDemo.controller.Main', {
 extend: 'Ext.app.Controller',
 requires: ['LoginAppDemo.user.Profile'],
 views: ['LoginForm','Viewport'],
    
 init: function(application) {
  this.control({
   "loginform": {
     login: this.onLogin
    }
  });
 },

 onLogin: function(loginDialog,loginForm,loginCredentials) {
   
   var me = this;

   // authenticate
   Ext.Ajax.request({
    url: 'resources/sampledata/cred.json',
    params: {
     username: loginCredentials.username,
     password: loginCredentials.password
    },
    success: function(response) {
     
     // convert text response to javascript object
     var data = Ext.decode(response.responseText);
    
     // if server response contains "firstName" node, then success!			
     if (data.firstName) {
      // instantiate user info in global scope for easy referencing
      LoginAppDemo.User = Ext.create("LoginAppDemo.user.Profile", {
    					firstName: data.firstName,
    					lastName: data.lastName,
    					roles: data.roles
      });
     
      // destroy login dialog
      loginDialog.destroy();


      Ext.Msg.alert("Login Successful",
    		    Ext.String.format("Welcome {0} {1}",
    				      LoginAppDemo.User.getFirstName(),
    				      LoginAppDemo.User.getLastName())
      );

      // load main UI
      Ext.create("LoginAppDemo.view.Viewport");


  } else { // login failed
    Ext.Msg.alert("Invalid credentials",
                  "You entered invalid credentials.", 
                  function() {
    		   loginForm.getForm().reset();
                  }
    );
  }
 }
});
}
});

Your app server would subsequently run a custom sql query to ensure that the passed username and password were valid and return a response similar to the following:

// code listing 4: cred.json
{
 firstName: 'Steve',
 lastName: 'Drucker',
 roles: 'admin'
}

Your app server would also set up session management for the user, typically consisting of some sort of session-based cookie hack since not every browser supports the establishment of persistent (html5 websocket) connections. Each subsequent data request to the server would use this cookie to determine whether the user had the appropriate rights to download the data that was requested.

From a UI perspective, however, we are simply concerned with caching the user’s identity and roles information in a location that could be easily accessed by our view and controller logic. Lines 33-37 of code listing 3 above instantiate the custom component described in code listing 5 at the root of your application’s namespace for easy global access.

// code listing 5
Ext.define("LoginAppDemo.user.Profile", {
	
  config: {
    firstName: '',
    lastName: '',
    roles: []
  },

  isUserInRole: function(roles) {
   for (var i=0; i<roles.length; i++) {
    if (Ext.Array.contains(this.getRoles(),roles[i])) {
     return true
    }
   }
   return false;
  },

  constructor: function(config) {
    this.initConfig(config);
    this.callParent(arguments);
  }

});

As illustrated by the following toolbar class, once the framework described above is in place, you can simply test the features of your app before outputting them to the user.

Ext.define("LoginAppDemo.view.MainToolbar", {
 extend: 'Ext.toolbar.Toolbar',
 alias: 'widget.maintoolbar',
 requires: ['Ext.toolbar.TextItem'],
	
 initComponent: function() {
  var items = [
   {
    xtype: 'tbtext',
    text: 'Login and Roles-Based Security Simulator'
   }, 
   {
    xtype: 'tbfill'
   }
  ];

  if (LoginAppDemo.User.isUserInRole(["admin"])) {
   items.push({ xtype: 'button', text: 'For Admins'});
  }

  if (LoginAppDemo.User.isUserInRole(["admin","users"])) {
   items.push({xtype: 'button', text: 'For Admins or Users' });
  }

  if (LoginAppDemo.User.isUserInRole(["nobody"])) {
   items.push({xtype: 'button', text: 'For nobody' });
  }

  Ext.apply(this, {items: items});
  this.callParent(arguments);
 }
});

6 thoughts on “Orchestrating Login and Roles-Based Security in Ext JS and Sencha Touch

  1. Bert Van den Eynde

    This a very good example of the login form for EXTJS 4!!!
    Do you have the source code for this?

    Reply
  2. Pingback: Securing ExtJS Using Java |

  3. Pingback: login ext js 4

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s