I have a simple Ember app (repo) with authentication using ember-simple-auth (i followed this article https://medium.com/@benhansen/token-based-authentication-with-jwt-ember-and-rails-af54b03fe237). After logging in I have access to currentUser in my routes, controllers and templates. However, if I navigate to any route besides my ApplicationRoute and reload the browser, I can no longer access currentUser in that route, but it's available in the template. If I navigate back to application route and navigate to different one again, then I can access the currentUser. How can I fix this, i.e. I want to be able to access currentUser in any route even after reload?
ApplicationRoute:
import Ember from 'ember';
import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin';
export default Ember.Route.extend(ApplicationRouteMixin, {
sessionAccount: Ember.inject.service(),
beforeModel() {
this.get('sessionAccount').loadCurrentUser();
}
});
SessionAccount service:
import Ember from 'ember';
const { inject: { service }, RSVP } = Ember;
export default Ember.Service.extend({
session: service('session'),
store: service(),
loadCurrentUser() {
if (this.get('session.isAuthenticated')) {
this.get('store')
.queryRecord('user', { me: true })
.then((user) => {
this.set('currentUser', user);
});
} else {
return RSVP.resolve();
}
}
});
Bookings route - the 'other' route:
import Ember from 'ember';
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';
export default Ember.Route.extend(AuthenticatedRouteMixin, {
sessionAccount: Ember.inject.service(),
model() {
const currentUser = this.get('sessionAccount.currentUser');
return this.get('store').query('booking', {
filter: {
'user_id': currentUser.id
},
include: 'rental,rental.rental-ratings'
});
}
});
Ended just following the tutorial form Ember simple auth github repo. Who would have thought this would work:) Had to change code in app/routes/application.js, also changed the name of my service from 'sessionAccount' to 'currentUser':
// app/routes/application.js
import Ember from 'ember';
import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin';
const { service } = Ember.inject;
export default Ember.Route.extend(ApplicationRouteMixin, {
currentUser: service(),
beforeModel() {
return this._loadCurrentUser();
},
sessionAuthenticated() {
this._super(...arguments);
this._loadCurrentUser();
},
_loadCurrentUser() {
return this.get('currentUser').load().catch(() => this.get('session').invalidate());
}
});