Search code examples
ember.jsember-simple-auth

Why restore doesn't send event authenticationSucceeded when using ember-simple-auth?


I need to get current user when a session is authenticated. I have implemented the service currentUser

import Ember from 'ember';

const { inject: { service }, isEmpty, RSVP } = Ember;

export default Ember.Service.extend({
  store: service(),
  user: null,

  load() {
    return this.get('store').find('user', 'me').then((user) => {
      this.set('user', user);
    });
  }
});

And I call it in route/application.js

import Ember from 'ember';
import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin';

export default Ember.Route.extend(ApplicationRouteMixin, {
  session: Ember.inject.service(),
  currentUser: Ember.inject.service(),

  init: function(){
    return this._super();
  },

  actions: {
    invalidateSession() {
      this.get('session').invalidate();
    }
  },

  sessionAuthenticated() {
    alert("sessionAuthenticated");
    this._super(...arguments);
    this._loadCurrentUser().catch(() => this.get('session').invalidate());
  },

  _loadCurrentUser() {
    return this.get('currentUser').load();
  }

});

When a user login or signup, the event authenticationSucceeded is called but when the session is restored in my authenticator, the event is not called. I need to call it because I need to reload user information.


Solution

  • I don't think that the sessionAuthenticated is triggered on restore. You need to load the user in your beforeModel hook.

    // ...
    beforeModel() {
      return this._loadCurrentUser();
    }
    // ...
    

    You can take a look at the official docs for setting the current user here