ember-simple-auth session.isAuthenticated is false after refresh page

I'm using ember-simple-auth with Cookie based authentication. When i login the {{session.isAuthenticated}} is true, but when i reload the page this is FALSE, but the localStore didn't change.

This is my custom.js authenticator:

import Base from 'ember-simple-auth/authenticators/base';
import config from '../config/environment';

export default Base.extend({
    tokenEndpoint: config.apiUrl + '/user/signIn',
    restore(data) {      
      console.log(data);
      return RSVP.resolve(data);
    },
    authenticate(username, password) {
      return Ember.$.ajax({
          url: this.tokenEndpoint,
          type: 'POST',
          data: JSON.stringify({
            username: username,
            password: password,
          }),
          contentType: 'application/json;charset=utf-8',
          dataType: 'json',
      });

    },
    invalidate: function () {
      return Ember.RSVP.resolve();
    },
  });

I'm using the {{session.isAuthenticated}} in the application.hbs. So i'm injecting the session in application controller:

session: Ember.inject.service('session')

Upvotes: 2

Views: 872

Answers (1)

omair azam
omair azam

Reputation: 580

You are making a mistake. 'restore ' method is called each time we refresh our page or open another tab. Note that RSVP.resolve removes your local storage so all is unauthenticated. We use this when we want to log user out and by that it means Ember Simple Auth will remove its local storage cookie and when this cookie is not found, it always send false for isAuthenticated method.

RSVP.resolve(data);

change your restore function from this

restore(data) {      
  console.log(data);
  return RSVP.resolve(data);
},

to this

restore(data) { 
    return new Promise((resolve, reject) => {
      resolve(data);
    });
},

Note that this 'restore' method is like a method which we have to override based on our site rules e.g if you have token authentication we will write this method as

restore(data) {
  return new Promise((resolve, reject) => {
    if (!Ember.isEmpty(data.token)) {
      console.log(data);
      resolve(data);
    } else {
      reject();
    }
});
},

Note that how we are handling things with our own logic to see if localstorage has token attribute present in it.

Similarly we can do by getting session cookie in this method and check if it exists. If it exists then we resolve else we reject. Note that these resolve and reject are promise methods etc.

Upvotes: 7

Related Questions