Skip to content

Instantly share code, notes, and snippets.

@rattanchauhan rattanchauhan/Security.js
Last active Nov 25, 2017

Embed
What would you like to do?
Extjs Security plugin
/**
* Hides/Disables a component based on the user roles provided and user roles required for a component
* Example usage :
* 1. Default behavior to prevent rendering of component if required role is not present. Suitable for small components like button, textfields and other form controls
* plugins: [
* {
* ptype: 'security',
* roles: ['ROLE_ADMIN', 'ROLE_SUBADMIN', 'APP_ROLE1'],
* }
* ]
*
* 2. Hide of component if required role is not present. Suitable for small components like button, textfields and other form controls
* plugins: [
* {
* ptype: 'security',
* hideComponent: true,
* roles: ['ROLE_ADMIN', 'ROLE_SUBADMIN', 'APP_ROLE1'],
* }
* ]
*
* Configs :
* roles => List of roles which are required for this component
* disableComponent => Boolean (Optional) : If true, disables the component instead of preventing render
* hideComponent => Boolean (Optional) : If true, component is present in dom but hidden
* failureCallback => Function (Optional) : Callback function to be called if required role is not present
*
* Note :
* => For panel with header buttons, tabpanels and similar card based views, please use hideComponent: true config and implement logic to switch to correct card to achieve consistent behavior
* => disableComponent config might not behave properly for containers
*/
Ext.define('App.common.Security', {
extend: 'Ext.AbstractPlugin',
alias: [
'plugin.security'
],
userRoles: [],
roles: [],
disableComponent: false,
init: function (component) {
// init defaults
this.disableComponent = this.disableComponent || false;
this.userRoles = User.getRoles() || [];
this.roles = this.roles || [];
this.failureCallback = this.failureCallback || function (component) { };
// check access
var hasAccess = this.userHasAccess();
if (!hasAccess) {
if (this.disableComponent) {
component.disable();
this.failureCallback(component);
return;
}
// hide if no access
if (this.hideComponent) {
component.hide();
this.failureCallback(component);
return;
}
// default prevent render
component.on({
beforerender: function () {
this.failureCallback(component);
return false;
},
scope: this
});
}
},
userHasAccess: function () {
var userRoles = this.userRoles,
roles = this.roles;
if (userRoles.length === 0 && roles.length > 0) {
return false;
}
if (userRoles.length === 0 && roles.length == 0) {
return true;
}
var matchingRoles = roles.filter(function (role) {
return Ext.Array.contains(this.userRoles, role);
}, this);
return matchingRoles.length > 0;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.