简体   繁体   中英

Ember-simple-auth ApplicationRoute model function

I have classic setup of Ember-simple-auth, in ApplicationRoute I use

model: function () {
  return Ember.RSVP.hash({
    user: this.store.find('gsUser').then(function(data) {
      return data.get('content')[0]
    })
  });
},

setupController: function(controller, model) {
  this.controllerFor('user').set('content', model.user);
}

When user losts authorization, and you open the page. ApplicationRoute::model is fired first, server returns 401 and other execution is stopped.

GET http://localhost:8000/app_dev.php/api/1/users.json 401 (Unauthorized)
Error while loading route: undefined 

model should be fired only when authentication is successfull.

I saw that there is sessionAuthenticationSucceeded but I've tried all the ways to listen to it, noone worked. How to listen to this event and get data from server when user is successfully authenticated?

11/06 22:57 UPDATE: enter code here

One solution for this problem that I've managed to achieve, but it seems totally not ember way :

App.ApplicationRoute = Ember.Route.extend(Ember.SimpleAuth.ApplicationRouteMixin, {
  skipModelLoading: false,

  beforeModel: function() {
    this.set('skipModelLoading', !this.get('session').get('isAuthenticated'));
  },

  model: function () {
    if (this.get('skipModelLoading')) {
      return;
    }

    return Ember.RSVP.hash({
      user: this.store.find('gsUser').then(function(data) {
        return data.get('content')[0]
      })
    });
  },

  setupController: function(controller, model) {
    if (this.get('skipModelLoading')) {
      return;
    }

    this.controllerFor('user').set('content', model.user);
  }
});

I assume you're loading the authenticated user in that model method. I'd do it differently and attach that property to the session as shown in this example: https://github.com/simplabs/ember-simple-auth/blob/master/examples/4-authenticated-account.html#L101

I think I found a more ember-way solution for my problem:

App.ApplicationRoute = Ember.Route.extend(Ember.SimpleAuth.ApplicationRouteMixin, {
  onSessionIsAuthenticated: function () {
    var isAuthenticated = this.get('session').get('isAuthenticated');

    if (!isAuthenticated) {
      return false;
    }

    var userController = this.controllerFor('user');

    return Ember.RSVP.hash({
      user: this.store.find('gsUser').then(function (data) {
        userController.set('content', data.get('content')[0]);
      })
    });
  }.observes('session.isAuthenticated').on('init')
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM