Louay Alakkad
Louay Alakkad

Reputation: 7408

How should I store current user details in EmberJS?

I have an EmberJS application generated using ember-cli. I'm currently using simple-auth with a custom authenticator.

In the authenticator, when the user logs in I want to save his details so that I can use it later. I have the following code:

authenticate: function(options) {
  var self = this;
  return new Ember.RSVP.Promise(function(resolve, reject){
    API.user.login(options.username, options.password, true).done(function(data) {
      // @TODO: Save current user
      resolve(data.id);
    }).fail(function() {
      reject();
    });
  });
},

User data is available in the variable data.user.

I tried using Ember.set('App.currentUser', data.user); but it's not working. What should I do?

Upvotes: 4

Views: 220

Answers (2)

Louay Alakkad
Louay Alakkad

Reputation: 7408

I ended up creating a custom Sessions controller and setting the current user object there, and then creating an alias from the application controller.

Something like what's in this article.

Upvotes: 0

David Duncan
David Duncan

Reputation: 1858

I think it works easiest to use an initializer. Theres several ways you can resolve the user, I think it is easiest if you pass the user_email alongside the grant token from the API

//initializers/session-user.js

import Ember from "ember";
import Session from "simple-auth/session";
export function initialize(container) {
  Session.reopen({
    setCurrentUser: function() {
      var accessToken = this.get('access_token');
      var self = this;
        if (!Ember.isEmpty(accessToken)) {
          return container.lookup('store:main').find('user', {
            email: self.get('user_email')
          }).then(function (users){
            self.set('currentUser', users.get('firstObject'));
          });
        }
      }.observes('access_token')
   });
}

export default {
  name: 'session-user',
  before: 'simple-auth',
  initialize: initialize
};

Check this thread for where the idea of this came from: http://discuss.emberjs.com/t/best-practice-for-loading-and-persisting-current-user-in-an-authenticated-system/6987

And if you are using simple-auth > 0.8.0-beta.1 you will need to adjust the initializer

Upvotes: 1

Related Questions