Skip to content

Instantly share code, notes, and snippets.

@jgwhite
Created August 19, 2012 20:28
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save jgwhite/3397497 to your computer and use it in GitHub Desktop.
Save jgwhite/3397497 to your computer and use it in GitHub Desktop.
Ember.js Routing With Authentication Example
var App = Em.Application.create();
App.ApplicationController = Em.Controller.extend();
App.ApplicationView = Em.View.extend({ templateName: 'application' });
App.HomeController = Em.Controller.extend();
App.HomeView = Em.View.extend({ templateName: 'home' });
App.AuthController = Em.Controller.extend({
authenticated: false,
failedAttempts: 0,
authenticate: function() {
if (this.credentialsValid()) {
this.set('authenticated', true);
} else {
this.incrementProperty('failedAttempts');
}
},
credentialsValid: function() {
return this.get('email') === 'jamie@jgwhite.co.uk'
&& this.get('password') === 'ilovejam';
},
authenticatedDidChange: function() {
if (this.get('authenticated')) {
this.get('target').send('becomeAuthenticated');
}
}.observes('authenticated')
});
App.AuthView = Em.View.extend({
tagName: 'form',
templateName: 'auth'
});
App.TextField = Em.TextField.extend({
attributeBindings: ['type', 'value', 'size', 'autofocus']
})
App.Router = Em.Router.extend({
root: Em.Route.extend({
// The unknown default state; neither authenticated nor unauthenticated.
// The router knows to enter this state by default, then the unknown
// state can decide whether to enter authenticated or unauthenticated mode.
default: Em.Route.extend({
route: '/',
enter: function(router) {
var authenticated = router.get('authController').get('authenticated');
// It's not at all obvious why this works :(
Em.run.next(function() {
if (authenticated) {
router.transitionTo('authenticated');
} else {
router.transitionTo('unauthenticated');
}
})
}
}),
authenticated: Em.Route.extend({
initialState: 'home',
home: Em.Route.extend({
route: '/home',
connectOutlets: function(router) {
router.get('applicationController').connectOutlet('home');
}
})
}),
unauthenticated: Em.Route.extend({
initialState: 'auth',
auth: Em.Route.extend({
route: '/auth',
connectOutlets: function(router) {
router.get('applicationController').connectOutlet('auth');
}
}),
authenticate: function(router) {
router.get('authController').authenticate();
},
becomeAuthenticated: function(router) {
router.transitionTo('authenticated');
}
})
})
});
App.initialize();
@diosney
Copy link

diosney commented Dec 21, 2012

Hi, thanks for this example, is very useful.

Maybe can you publish also the template for this example?

Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment