4
votes

I would like to implement authentication with ember.js. So, when the application start, before the Router handles the requested url, I want to check the user status. If the user isn't authenticated, I want to save the requested url and redirect to a specific url (/login). I tried to implement this overloading Ember.Route but I don't think it's a good practice. For example, if i do:

var AuthRoute = Ember.Route.extend({  
    redirect: function() {  
        var controller = App.userController;  
            if (!controller.get("userAuth")) {  
                controller.set("lastFilter", this.routeName);  
                this.transitionTo("index");
            }  
        }  
    }  
});

If, the url is '/admin/foobar', the admin route will redirect instead of foobar.

Can I process redirection before the Router to start?

3

3 Answers

1
votes

I use something like this

Ember.SecureRoute = Ember.Route.extend({
  role: null,

  redirect: function (model) {
    if (!this.controllerFor('login').get('authenticated')) {
        this._routeToLogin();
    }

    var role = this.get('role');
    if (!Ember.isEmpty(role) && !this.controllerFor('login').hasRole(role)) {
        this._routeToLogin();
    } 
  },

  _routeToLogin: function () {
    var infos = this.get('router.router.currentHandlerInfos');

    this.router.router.didTransition(infos);

    var routeName = !this.router.router.hasRoute(this.routeName) ? this.routeName + '.index' : this.routeName;
    var params = infos.filter(function (item, index, enumerable) { return item.context !== undefined; }).map(function (item) { return item.context; })
    var url = Ember.Router.prototype.generate.apply(this.router, params.insertAt(0, routeName))
    this.router.location.setURL(url);

    this.transitionTo("login");
  }
});

in your loginController you can then use the browser history to go back to your original route

APP.LoginController = Ember.Controller.extend({
  //other stuff

  authenticate: function (username, password) {
    //do the authentication
    history.go(-1);
  }
});
1
votes

The way that I do it is I pass down the authenticated user with my data. and I have an initConfiguration function inside of my main App

so inside of index file (in this case I am showing you jade) I have this:

// initialize ember settings
script(type='text/javascript')
    App.initConfiguration('!{currentUser}')

and inside of my App file I have (coffeescript here)

window.App = Ember.Application.create

  currentUser: null

  initConfiguration: (currentUser) ->
    if currentUser? and currentUser.length > 0
      @set 'currentUser', currentUser

If you are using ember-data, then you have to change the application file to

window.App = Ember.Application.create

  currentUser: null

  tempCurrentUser: null

  initConfiguration: (currentUser) ->
    ##
    # set the tempCurrentUser to the currentUser passed in, this is then
    # set in the ApplicationRoute to the App.currentUser
    # and destroyed (this is necessary as the ember store is not initialzed yet
    # and just setting it here will result in an error)     
    if currentUser? and currentUser.length > 0
      @set 'tempCurrentUser', currentUser

and then inside your application route do the following

App.ApplicationRoute = Ember.Route.extend

  setupController: (controller) ->
    if App.tempCurrentUser?
      App.setCurrentUser(App.tempCurrentUser)
0
votes

Ember has a fantastic guide on preventing and retrying authentication: http://emberjs.com/guides/routing/preventing-and-retrying-transitions/

A simple way to do transitions based on whether or not a user is logged in:

App.ApplicationRoute = Ember.Route.extend({
    willTransition: function () {
        var session = this.controllerFor('session');
        if (!session.get('authed')) {
            this.transitionTo('login');
        }
    }
});

The example above assumes you have some kind of session controller or object managing the active sessions. This works because the ApplicationRoute is the very first route that is hit whenever you enter your application (from any URL).