Search code examples
ruby-on-railsember.jsember-simple-auth

ember get current user information from session and setting currentUser to use inside template


I am using ember-simple-auth library with rails token based authentication in the backend. ember version is:

ember-cli: 2.6.2
node: 6.3.0
ember-simple-auth: 1.1.0

I was successfully able to logged in a user. But can't able to access current user information. The following code is working:

    {{#if session.isAuthenticated}}
      <p>i m logged in</p>
      <a href="#" {{action 'logout'}}>Logout</a>
    {{else}}
      <p>i m not logged in</p>
    {{/if}}

but the following code is not working

{{session.store.authenticated.email}}

I wanted to get user information but failed. So, I dig into the mater and used ember helper as:

<p>{{log session}}</p>

It helped me and I was able to get current user information like:

<p>{{session.session.content.authenticated.email}}</p>

which is good but I want something like the following:

<p>{{session.currentUser.email}}</p> 

or simply:

<p>{{currentUser.email}}</p>

how can I change my application controller, so that it will be able to get current user information in a better way. My application controller code is:

// /app/controllers/application.js

import Ember from 'ember';

export default Ember.Controller.extend({
  session: Ember.inject.service('session'),

  actions: {
    logout() {
      this.flash.success('Successfully logged out!', 5000);
      this.get('session').invalidate();
    }
  }
});

Solution

  • Your session data is available in the session object data property. Check out the "authenticate" method in the docs for more info.

    So you can access it i.e {{session.data.authenticated.email}} . Depending on your session data you could make a computed property in your controller so it looks better in your template...

      currentUser: Ember.computed('session.data', function() {
        return this.get('session.data.authenticated.currentUser');
      })