javascriptember.jsember-addon

Ember.js - How to get current user properties in abilities source file while using ember-can addon


How to get user object in abilities source file in Ember-can addon. This is how my abilities file looks like.

import Ember from 'ember';
import { Ability } from 'ember-can';

export default Ability.extend({
    canWrite: Ember.computed('user.isAdmin', function() {
       return this.get('user.isAdmin');
    })
});

Solution

  • According to the official documentation:

    Injecting the user

    How does the ability know who's logged in? This depends on how you implement it in your app!

    If you're using an Ember.Service as your session, you can just inject it into the ability:

    // app/abilities/foo.js
    import Ember from 'ember';
    import { Ability } from 'ember-can';
    
    export default Ability.extend({
      session: Ember.inject.service()
    });
    

    If you're using ember-simple-auth, you'll probably want to inject the simple-auth-session:main session into the ability classes.

    To do this, add an initializer like so:

    // app/initializers/inject-session-into-abilities.js
    export default {
      name: 'inject-session-into-abilities',
      initialize(app) {
        app.inject('ability', 'session', 'simple-auth-session:main');
      }
    };
    

    The ability classes will now have access to session which can then be used to check if the user is logged in etc...