Differentiating current logged in user and other users


#1

How do people usually handle this problem in DS.Model? The model is probably both called User, but there are significant difference in what they can do and probably different attributes.


#2

You could inject the currently logged in user into all controllers and routes. Then you can always do the check if a user is the currentUser.

http://emberjs.com/guides/understanding-ember/dependency-injection-and-service-lookup/#toc_dependency-injection-with-code-register-inject-code


#3

I’m currently in the midst of writing a little post about how I solved this today but the gist of it is this:

I made a mixin that fetches some preloaded JSON from a meta-tag (but you could just as well GET api/users/me or something like that) and stores it on the ApplicationController. The code looks roughly like this:

LS.CurrentUserMixin = Ember.Mixin.create({
  needs: ['application'],

  init: function () {
    this._super();

    if (!this._application().get('currentUser')) {
      var payload = this._rawUserData();
      this.store.pushPayload('user', { user: payload.user });
      this._application().set('currentUser',
                              this.store.getById('user', payload.user.id));
    }
  },

  currentUser: function () {
    return this._application().get('currentUser');
  }.property(),

  // private

  _application: function () {
    return this.get('controllers.application');
  },

  _rawUserData: function () {
    return JSON.parse($('meta[name="current-user"]').attr('content'));
  }
});

Then you could use this in your controllers like so:

LS.UserIndexController = Ember.ObjectController.extend(  
  LS.CurrentUserMixin, {

  isCurrentUser: function () {
    return this.get('currentUser') === this.get('model');
  }.property('model'),
});

Hope that helps, if anyone has any tips I’d love to hear them ^^