lundi 15 février 2016

Is it possible to restrict loading model until some condition?

I have model called posts. And component called posts-list

app/templates/components/posts-list.hbs:

{{#each posts as |post|}}
  {{post.title}}
{{/each}}

main template:

{{posts-list posts=model}}

app/routes/posts.js:

export default Ember.Route.extend({
  model() {
    return this.store.findAll('post');
  }
});

Issue description: Those posts can be loaded if user authorised or not, but when user authorised titles will be a bit different (data comes from server using JWT).

I'm using ember-simple-auth with custom authorizer and authenticator. Auth process looks like - user clicks link and going to backend, then it redirects back to main page with token as GET param. I overrided setupController in app/routes/application.js and calling

this.get('session').authenticate('authenticator:custom', token);

In authenticator i have function:

  authenticate: function(token) {
    return new Ember.RSVP.Promise((resolve, reject) => {
      Ember.$.ajax({
        url: ENV.APP.API_HOST + '/api/users',
        type: 'GET',
        contentType: 'application/json',
        dataType: 'json',
        headers: {
          'Accept': 'application/json',
          'Authorization': token
        }
      }).then(function(response) {
        Ember.run(function() {
          resolve({ token: token });
        });
      }, function(xhr, status, error) {
        var response = xhr.responseText;
        Ember.run(function() {
          reject(response);
        });
      });
    });
  }

So i'm trying to get current user using token and if it success, then user is authorized.

Everything works fine except one thing. Posts is requested before requesting current user, so even if user actually authorized he will see non authorized content. Is it possible to tell Ember about loading order (or reload data after auth, but this will produce second request which is not preferred).




Aucun commentaire:

Enregistrer un commentaire