Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best approach to show/hide content based on users permission

I'm looking for the best way to show or hide content for a user, based on their permissions. I could easily check if the current user is an admin, or something like that, but let's say a user wants to edit their post. Then both the admin and the author need to be able to see the edit button.

What's the best solution for this?

Before, I used this custom 'can' helper, but after an update in Ember Auth, this solution stopped working. See here.

like image 728
Timmie Sarjanen Avatar asked Nov 11 '22 19:11

Timmie Sarjanen


1 Answers

I usually create a service that keeps a permission table, user roles and some helpers like can(), isAdmin().

For example: app/services/user-rights.js

import Ember from 'ember';

export default Ember.Service.extend({
  setData(roles, rightsTable){
    this.set('rightsTable', rightsTable);
    this.set('roles', roles);
  },
  can: function (action) {
    let roles = this.get('roles');
    if (!roles /*|| !this.get('rightsTable')*/) {
      return false;
    }
    let rolesToAssignOrder = [
      'ceo',
      'partner'
    ];

    let rolesToReceiveOrder = [
      'senior_broker',
      'broker',
      'junior_broker'
    ];

    let buildingsModeration = [
      'ceo',
      'partner',
      'updaters_manager'
    ];
    let seeBuildingsModeration = Array.prototype.concat(buildingsModeration, ['office_manager']);

    switch (action) {
      case 'canAssignOrder':
        return this.checkRoles(rolesToAssignOrder);
      case 'canReceiveOrder':
        return this.checkRoles(rolesToReceiveOrder);
      case 'canModerateBC':
        return this.checkRoles(buildingsModeration);
      case 'canSeeModeratingBC':
        return this.checkRoles(seeBuildingsModeration);
      case 'canChangeBroker':
        return this.checkRoles(['ceo']);
      default:
        return false;
    }
  },
  checkRoles(allowedRoles){
    let can = false;
    this.get('roles').forEach(el=>{
      if(allowedRoles.indexOf(el.name) > -1){
        can = true;
      }
    });
    return can;
  }
});
like image 178
Costa Avatar answered Jan 04 '23 02:01

Costa