For a simple Extjs app it would be desirable to have a dedicated User class which captures the logged in user details so that certain components that should be visible/hidden based on the user roles. So we can define such a User class and initialize the user’s roles and other details just after login. Below is one way to implement such a functionality where user details are captured and re-used for checking current logged in user roles.
1. Create a new singleton Extjs User class (User.js).
2. Get the User rights through ajax call (this can be done at the app startup in the launch method, or just after a successful login) and save them for reuse (app.js).
3. Use saved user to check whether logged in user has certian role or not. Lets say we want to show certain menu items based on roles (usage.js)
Ext.Ajax.request({ | |
url: 'userEndpointUrl', | |
failure: function(data, operation) { | |
console.log('failure while trying to fetch roles for user..'); | |
console.log(operation); | |
}, | |
success: function(data, operation) { | |
console.log('success fetching roles....'); | |
var response = Ext.JSON.decode(data.responseText); | |
// initialize User in the app | |
User.initUser(response.userName, response.rights); | |
} | |
}); |
onMenuPanelRenderer : function() { | |
var hasWebRole = User.hasRole(Config.role.web); | |
var hasAdminRole = User.hasRole(Config.role.admin); | |
if (hasWebRole) { | |
// set mentu item visible true based on role | |
} | |
if (hasAdminRole) { | |
// set mentu item visible true based on role | |
} | |
} |
Ext.define('AppName.app.User', { | |
singleton: true, | |
alternateClassName: ['User'], | |
constructor: function(config) { | |
this.initConfig(config); | |
}, | |
config: { | |
username: null, | |
rights: null | |
// probably some more details | |
}, | |
initUser : function(username, rights) { | |
this.username = username; | |
this.rights = rights; | |
return this; | |
}, | |
getRights: function() { | |
return this.rights; | |
}, | |
hasRole: function(role) { | |
var rights = User.getRights(); | |
for (i = 0; i < rights.length; i++) { | |
if (rights[i] === role) { | |
return true; | |
} | |
} | |
return false; | |
} | |
}); |