Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access user's account info with Ember Simple Auth

I'm using ember-simple-auth in my application and it's working well, but I would like to be able to display properties from the current user (such as email or name) in the UI. In the past I've used an application initializer to do this and essentially inject all controllers with the currentUser, but that required the current user to be known when the application was initialized. Since I'm using OAuth, the user is not known when the application loads.

Is there a way to get properties from the currently logged in user?

like image 489
Peter Brown Avatar asked May 07 '14 20:05

Peter Brown


1 Answers

It turned out the version of ember-simple-auth I was using was out of date and needed to upgrade to 0.3.x (from 0.2.x). From there, I was able to add a custom authenticator which I pulled almost directly from the project's example files. Note that I'm on Ember 1.6.0 beta 2.

With the code below, I can access the currentUser in routes and controllers using this.get('session.currentUser') or in templates using {{session.currentUser}}.

The only change I had to make to my API was including the user_id with the OAuth response.

Updated from the previous answer to support 0.4.0

Then I updated my initializer to be the following:

App.initializer({
  name: 'authentication',

  initialize: function(container, application) {
    Ember.SimpleAuth.Authenticators.OAuth2.reopen({
      serverTokenEndpoint: '/api/oauth/token'
    });

    Ember.SimpleAuth.Session.reopen({
      currentUser: function() {
        var userId = this.get('user_id');
        if (!Ember.isEmpty(userId)) {
          return container.lookup('store:main').find('current-user', userId);
        }
      }.property('user_id')
    });

    Ember.SimpleAuth.setup(container, application, {
      authorizerFactory: 'ember-simple-auth-authorizer:oauth2-bearer',
      routeAfterAuthentication: 'main.dashboard'
    });
  }
});

My login controller now looks like this:

export default Ember.Controller.extend(Ember.SimpleAuth.LoginControllerMixin, {
  authenticatorFactory: 'ember-simple-auth-authenticator:oauth2-password-grant'
});
like image 144
Peter Brown Avatar answered Oct 23 '22 20:10

Peter Brown