Integrating System Roles API in Open Event Frontend

The Eventyay system supports different system roles and allows to set panel permissions for every role. The system supports two inbuilt roles namely Admin and Super Admin. The users having access to permissions panel can create new custom system roles and define set of panel permissions for them. Also the users are provided with the option of editing and deleting any system role except the two inbuilt system roles. The feature is implemented using custom-system-roles and panel-permissions API on the server.

Adding route for system-roles

The route for custom-system-system roles is defined which contains a model returning user permissions, system roles and the panel permissions. The model is defined as async so that the execution is paused while fetching the data from the store by adding the await expression.

async model() {
 return {
   userPermissions  : await this.get('store').findAll('user-permission'),
   systemRoles      : await this.get('store').findAll('custom-system-role'),
   panelPermissions : await this.get('store').findAll('panel-permission')
 };
},

The route created above gets all the data for user permissions, system-roles and panel permissions which is later used by the template for rendering of data.

Adding model for system-roles and panel-permissions

The model for system-roles is created which contains the ‘name’ attribute of type string and a relationship with panel permissions. Every system role can have multiple panel permissions, therefore a hasMany relationship is defined in the model.

export default ModelBase.extend({
 name: attr('string'),

 panelPermissions: hasMany('panelPermission')
});

Similarly, the model for panel-permissions is added to the models directory. The defined model contains ‘panelName’ as an attribute of type string and a bool value canAccess, defining if the panel is accessible by any role or not.

export default ModelBase.extend({
 panelName : attr('string'),
 canAccess : attr('boolean')
});

Defining controller for system-roles

The controller for system-roles is defined in the controllers/admin/permissions directory. The action for adding, updating and deleting system roles are defined in the controller. While adding the system roles, all the panels are fetched and checked which panel permissions are selected by the admin. A special property namely ‘isChecked’ is added to every panel permission checkbox which toggles on change. If the property is set true the corresponding panel is added to the panel permissions relationship of corresponding role. If no panel is selected, an error message to select atleast one panel is displayed.

deleteSystemRole(role) {
 this.set('isLoading', true);
 role.destroyRecord()
  ...
  // Notify success or failure
},
addSystemRole() {
 this.set('isLoading', true);
 let panels = this.get('panelPermissions');

 panels.forEach(panel => {
   if (panel.isChecked) {
     this.get('role.panelPermissions').addObject(panel);
   } else {
     this.get('role.panelPermissions').removeObject(panel);
   }
 });
 if (!this.get('role.panelPermissions').length) {
  // Notification to select atleast one panel
 } else {
   this.get('role').save()
    // Notify success or failure
 }
},
updatePermissions() {
 this.set('isLoading', true);
 this.get('model.userPermissions').save()
  ...
  // Notify success or failure
}

The actions defined above in the controller can be used in template by passing the appropriate parameters if required. The addSystemRole action makes a POST request to server for creating a new system role, the updatePermissions action makes a PATCH request for updating the existing system role and the deleteSystemRole action makes a delete request to the server for deleting the role.

Adding data to template for system-roles

The data obtained from the model defined in route is rendered in the template for system-roles. A loop for showing all system roles is added to the template with the name attribute containing the name of system role and another loop is added to display the panel permissions for the corresponding role.

{{#each model.systemRoles as |role|}}
 <tr>
   <td>{{role.name}}</td>
   <td>
     <div class="ui bulleted list">
       {{#each role.panelPermissions as |permission|}}
         <div class="item">{{concat permission.panelName ' panel'}}</div>
       {{/each}}
     </div>
   </td>
   <td>
    // Buttons for editing and deleting roles
   </td>
 </tr>
{{/each}}

A modal is to the component for creating and editing system roles. The data from this template is passed to the modal where the existing permissions are already checked and can be modified by the admins.

Resources

Continue ReadingIntegrating System Roles API in Open Event Frontend

Integrating Event Roles API in Open Event Frontend

The Eventyay system supports different type of roles for an event like Attendee, organizer, co-organizer, track-organizer, moderator and the registrar. Every role has certain set of permissions such as Create, Read, Update, Delete. The Admin of the system is allowed to change the permissions for any role. The interface for updating the even role permissions was already available on the server but was not integrated on the frontend. The system is now integrated with the API and allows admin to change event role permission for any role.

Adding model for event role permissions

The model for event role permissions is added to the models directory. The model contains the attributes like canDelete, canUpdate, canCreate, canRead and the relationship with event role and the service.

export default ModelBase.extend({
 canDelete : attr('boolean'),
 canUpdate : attr('boolean'),
 canCreate : attr('boolean'),
 canRead   : attr('boolean'),

 role        : belongsTo('role'),
 service     : belongsTo('service'),
 serviceName : computed.alias('service.name')
});

The above defined model ensures that every permission belongs to a role and service. An alias is declared in the model using the computed property which is later used in the controller to sort the permissions according to service name in lexicographical order.

Adding route for event roles

The route for event role is created which contains model returning an object containing the list of roles, services and permissions. The model is defined as async so that the execution is paused while fetching the data from the store by adding the await expression.

export default Route.extend({
 titleToken() {
   return this.get('l10n').t('Event Roles');
 },
 async model() {
   return {
     roles       : ['Attendee', 'Co-organizer', 'Moderator', 'Organizer', 'Track Organizer', 'Registrar'],
     services    : await this.get('store').query('service', {}),
     permissions : await this.get('store').query('event-role-permission', { 'page[size]': 30 })
   };
 }
});

The route created above queries the data for roles, services and permissions which is later used by the template for rendering of the data obtained.

Adding controller for event roles

The controller for event roles is added to the controllers/admin/permissions directory. The computed property is used to sort the services obtained from model lexicographically and the permissions are sorted by the help of alias created in the model.

services: computed('model', function() {
 return this.get('model.services').sortBy('name');
}),
sortDefinition : ['serviceName'],
permissions    : computed.sort('model.permissions', 'sortDefinition'),
actions        : {
 updatePermissions() {
   this.set('isLoading', true);
   this.get('model.permissions').save()
     .then(() => {
       // Notify success and add Error handler
      }
   }
}

An action named updatePermissions is defined which is triggered when the admin updates and saves the permissions for any role where a PATCH request is made to the server in order to update the permissions.

Rendering data in the template

The data obtained from the model is manipulated in the controller and is rendered to the table in the event-roles template. Every role is fetched from the model and added to the template, all the permissions in sorted order are obtained from the controller and matched with the current role name. The relationship of permissions with role is used to check if its title is equal to the the current role. The permissions are updated accordingly, if the role title is equal to current role.

<tbody>
 {{#each model.roles as |role|}}
   <tr>
     <td>{{role}}</td>
     {{#each permissions as |permission|}}
       {{#if (eq permission.role.titleName role)}}
         <td>
           {{ui-checkbox label=(t 'Create') checked=permission.canCreate onChange=(action (mut permission.canCreate))}}
           <br>
           {{ui-checkbox label=(t 'Read') checked=permission.canRead onChange=(action (mut permission.canRead))}}
           <br>
           {{ui-checkbox label=(t 'Update') checked=permission.canUpdate onChange=(action (mut permission.canUpdate))}}
           <br>
           {{ui-checkbox label=(t 'Delete') checked=permission.canDelete onChange=(action (mut permission.canDelete))}}
         </td>
       {{/if}}
     {{/each}}
   </tr>
 {{/each}}
</tbody>

After rendering the data as shown above, the checkbox for permissions of different services for different roles are checked or unchecked depending upon the bool value of corresponding permission. The admin can update the permissions by checking or unchecking the checkbox and saving the changes made.

Resources

Continue ReadingIntegrating Event Roles API in Open Event Frontend

Displaying name of users in Users tab in Admin Panel

In the Users tab in the Admin Panel, we have a lot of user information displayed in a tabular form. This information is fetched from the accounting objects of each user. As the users are now able to also store their name in their respective accounting object, hence we needed to implement a feature to display the name of the users in the Users table in a separate column. This blog post explains how the user names are fetched from the respective accounting objects and are then displayed in the Users table in the Admin Panel.

How is name of user stored on the server?

The name of any user is stored in the user’s accounting object. All the settings of a user are stored in a JSONObject with the key name as ‘settings’. The name of a user is also stored in ‘settings’ JSONObject. This is shown as follows:

Modifying GetUsers.java to return name of users

The endpoint /aaa/getUsers.json is used to return the accounting info of all users. This includes their signup time, last login time, last login IP, etc. We needed to modify it to return the name of users also along with the already returned data. This is implemented as follows:

   if(accounting.getJSON().has("settings")) {
        JSONObject settings = accounting.getJSON().getJSONObject("settings");
        if(settings.has("userName")) {
            json.put("userName", settings.get("userName"));
        }
        else {
            json.put("userName", "");
        }
    } else {
        json.put("userName", "");
    }
    accounting.commit();

 

Fetching names of all users from the server

We need to make an AJAX call to ‘/aaa/getUsers.json’ as soon as we switch to the Users tab in the Admin Panel. We need to extract all the required data from the JSON response object and put them in state variables so that they can further be used as data indexes for different columns of the table. The implementation of the AJAX call is as follows:

   let url =
      `${urls.API_URL}/aaa/getUsers.json?access_token=` +
      cookies.get('loggedIn') +
      '&page=' +
      page;
    $.ajax({
      url: url,
      dataType: 'jsonp',
      jsonp: 'callback',
      crossDomain: true,
      success: function(response) {
        let userList = response.users;
        let users = [];
        userList.map((data, i) => {
          let user = {
            userName: data.userName,
          };
          users.push(user);
          return 1;
        });
        this.setState({
          data: users,
        });
      }.bind(this)
    });

 

Displaying name of users in Users tab in Admin Panel

We needed to add another column titled ‘User Name’ in the Users table in the Admin Panel. The ‘dataIndex’ attribute of the Ant Design table component specifies the data value which is to be used for that particular column. For our purpose, our data value which needs to be displayed in the ‘User Name’ column is ‘userName’. We also specify a width of the column as another attribute. The implementation is as follows:

   this.columns = [
      // other columns
      {
        title: 'User Name',
        dataIndex: 'userName',
        width: '12%',
      }
      // other columns
    ];

 

This is how the names of users are fetched from their accounting object and are then being displayed in the Users tab in Admin Panel.

Resources

Continue ReadingDisplaying name of users in Users tab in Admin Panel

Skills tab of SUSI AI Admin Panel

The Skills tab in SUSI.AI Admin Panel displays all the skills of SUSI in a tabular form. The table is created using the Table component of Ant Design. It’s preferred because we’re going to handle a lot of data here and that can turn out to be heavy if we use Google’s Material-ui.

Displaying the data:

The data is rendered in the form of a table which has seven columns – Name, Group, Language, Type, Author, Status and Action. The first 5 columns displays basic details of a skill. The “Status” column shows whether the skill has been reviewed by admin or not. All the reviewed skills are either “Approved” or “Not Approved”. The final column “Action” contains all the actions that admin can perform on the skill. Currently, an admin can change the review status of a skill. More actions will be added in future as this is still in beta.

All the column names are stored in a variable in the form of an array. The following code will demonstrate the way of making three columns – Name, Group, Language.

this.columns = [
  {
    title: 'Name',
    dataIndex: 'skill_name',
    sorter: false,
    width: '20%',
  },
  {
    title: 'Group',
    dataIndex: 'group',
    width: '15%',
  },
  {
    title: 'Language',
    dataIndex: 'language',
    width: '10%',
  },
];

All the skills are also stored in an array which is a state variable. These columns and skills are then passed to the Table component as props. The following code will demonstrate that:

<Table
  columns={this.columns}
  rowKey={record => record.registered}
  dataSource={this.state.skillsData}
/>

Fetching all the skills from SUSI Server:

All the public skills can be fetched from ListSkillService API of SUSI Server. We can filter all the skills using various filters. We want to display the skills alphabetically on Skills tab in Admin Panel. Hence, we filter the skills accordingly. To do this, we pass three parameters in the GET request. They are as follows:

  • applyFilter: true
  • filter_name: ascending
  • filter_type: lexicographical

This returns all the skills in an alphabetical order. The API request url looks like this:

https://api.susi.ai/cms/getSkillList.json?applyFilter=true&filter_name=ascending&filter_type=lexicographical

After fetching the skills, we put all the parameters of these skills required for our table in an object which is then pushed into an array. One object is created for each skill.
If the API call fails for some reason then a Google’s Material-ui Snackbar appears with a message that an error occurred.

Changing review status of a skill:

An admin can change the review status of any skill. This is done by making a GET request to ChangeSkillStatusService API. The request contains five parameters. They are as follows:

  1. Model: Model of the skill is passed here (string)
  2. Group: Group of the skill is passed here (string)
  3. Language: Language of the skill is passed here (string)
  4. Reviewed: true is passed is skill has been approved and false if skill is not approved. (boolean)
  5. Access_token: The access token of user is passed here. This is for verifying the user’s BASE ROLE. This is taken from cookies using cookies.get(‘loggedIn’). (string)

The call url looks like this:

https://api.susi.ai/cms/changeSkillStatus.json?model=general&group=Knowledge&language=en&skill=aboutsusi&reviewed=true&access_token=yourAccessTokenHere

If the API call is successful, then the review status of a skill is successfully changed. Otherwise, an error message is thrown.

References:

Continue ReadingSkills tab of SUSI AI Admin Panel