Skip to content

Instantly share code, notes, and snippets.

@lukes
Last active August 29, 2015 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lukes/89688e7b81f3cbb69c31 to your computer and use it in GitHub Desktop.
Save lukes/89688e7b81f3cbb69c31 to your computer and use it in GitHub Desktop.
Reliably return the currentUser after login or app reload (with Ember simple-auth-devise)
// Save as routes/application.js
import Ember from 'ember';
import ApplicationRouteMixin from 'simple-auth/mixins/application-route-mixin';
export default Ember.Route.extend(ApplicationRouteMixin, {
beforeModel: function(transition) {
this._super(transition);
// Called when the app first loads, and will block until the Promise
// resolves. Fetch the currentUser.
if (this.session.get('isAuthenticated')) {
return this.session.setCurrentUser();
}
}
});
// Save as initializers/custom-session.js
// Allow Session to fetch and return the currentUser.
//
// Modified from http://blog.willrax.com/fetching-the-current-user-with-simple-auth/
import Ember from "ember";
import Session from "simple-auth/session";
export default {
name: "custom-session",
before: "simple-auth",
initialize: function(container) {
Session.reopen({
// Called when we want to query Rails for data about the logged in
// user. Fetches the data, assigning it to a currentUser property.
setCurrentUser: function() {
// Build the URI and push the response into the store manually,
// since Ember Data doesn't support singular resource endpoints
var adapter = this.container.lookup('adapter:application');
var url = adapter.buildURL() + '/current_user';
var store = container.lookup("store:main");
return Ember.$.get(url).then((data) => {
store.pushPayload('current_user', data);
var user = store.find('current_user', data.current_user.id);
this.set("currentUser", user);
});
}
});
}
};
// Save as controllers/login.js
//
// authenticate handles a login form POST.
import Ember from "ember";
export default Ember.Controller.extend({
actions: {
authenticate: function() {
var data = this.getProperties('identification', 'password');
return this.get('session').authenticate('simple-auth-authenticator:devise', data).then(() => {
return this.session.setCurrentUser();
});
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment