User Permissions

Let’s say I have a user model, and a user has many permissions

App.User = DS.Model.extend({username: DS.attr('string'),permissions: DS.hasMany('permission', {async: true})});
App.Permission = DS.Model.extend({name: DS.attr('string')});

So I can get user permissions with the following:

user.get('permissions').forEach(function(p){console.log(p.get('name'));});

I want to check a user’s permissions before displaying a section of a template

{{#if has_permission(current_user, "edit_schedules")}}
  "Button to edit schedules here"
{{/if}}

I’m having trouble with the has_permission funciton: the data I need to access is inside of a promise, so it can’t resolve right away:

function has_permission(user, permission_name){
  user.get('permissions').foreach(function(p){
    if (p.get('name') == permission_name){
      // too late to return true here.
    }
  });
  // callback hasn't yet fired here, don't know whether to return true or false.
}

What can I do instead to make this work?

Have you tried converting has permission in a computed property? But probably you’ll end up needing as many computed properties as permissions you have. If you don’t have much is the best solution, due to CP caching.

Otherwise just define permissions as embedded so that you received JSON looks like:

users:[{
  name: 'first user',
  permissions:[
    {permission_name: 'edit'},
    {permission_name: 'delete'},
    etc
 ]

]}

then when you use a user.get('permissions') it will return you an array and not a promise.

permissions are user definable, so I don’t know at design time what they are, so computed property is out. I guess I could embed them instead.