Search code examples
ember.jsember-simple-auth

Saving a user to a session as a computed property


I've seen other questions about this (like this one), and I believe this should be working

import Ember from 'ember';
import Session from 'simple-auth/session';

export default {
  name: 'session-with-me',
  before: 'simple-auth',
  initialize: function() {
    Session.reopen({
      me: function() {
        if (this.get('isAuthenticated')) {
          return this.container.lookup('service:store').find('me', { singleton: true });
        }
      }.property('isAuthenticated')
    });
  }
};

the find('me', { singleton: true }) is a working patch of ember-jsonapi-resources. While debugging I can see the request being sent, and the payload comes through. I use the same find call elsewhere in the app, and can confirm a model gets instantiated fine.

On the inspector, under container > simple-auth-session I can see me as a session property, but it shows as { _id: 68, _label: undefined ...}

Has the way to set a session property changed? I may have seen a mention about this somewhere, but I can't find it anymore.

This is in the same domain of another question I asked earlier, but I'm giving up on that approach and trying simply to fetch the user independently of the authentication process.


Solution

  • Set up a custom session like that:

    export default Session.extend({
      me: function() {
        var accessToken = this.get('secure.access_token');
        if (!Ember.isEmpty(accessToken)) {
          return DS.PromiseObject.create({
            promise: this.container.lookup('service:me').find({});
          });
        }
      }.property('secure.access_token')
    });
    
    // app/config/environment.js
    ENV['simple-auth'] = {
      session: 'session:me'
    }
    

    DS.PromiseObject is actually part of Ember Data which you're not using - I don't know whether there's an equivalent in the library you chose.