How to serve 2 routes from the same URL (e.g. public and private home)


#1

Hello,

Can someone please recommend a good design for serving 2 different routes at the root url?

For example, when I go to www.facebook.com/ it will show a sign up page if I am not authenticated, or my private dashboard if I am authenticated.

My first thought would be to render different templates in renderTemplate(), depending on whether the user is authenticated or not.

Thank you, Andrei


#2

Yeah that’s exactly right… assuming you’ve injected your currentUser into every route, you’d do something like this:

App.IndexRoute = Ember.Route.extend({
  afterModel: function(model) {
    var theContext = this;
    var isAuthorized = this.get("currentUser");
    if(isAuthorized) {
      theContext.transitionTo("pages");
    } else {
      theContext.transitionTo("unauthorized");
    }
  }
});

Mind you, you’d want to ensure all your other routes are protected, too…

You might want to look into something like this, if you’re interested in more than a simple redirect:

https://github.com/simplabs/ember-simple-auth (Note I heaven’t personally used this, and I’ve heard there are a lot of different options around this including several blog posts around the web on how to do it “the best way”).


#3

That would be transitioning to other routes and it sounded like the original post was asking about dynamically changing the content of the route rather than redirecting.

You mentioned renderTemplate and that’s the answer to your question. By the time that hook is called your model is resolved and you have access to the controller as well. If you’re injecting the user object you have access to that as well. RenderTemplate can swap out the view/template for unauthorizes or login page into the outlet it would normally be yielding to. This could make for a good base class for your route, and you can even override the route:basic type to implement this logic on generated routes across your app.

I am on my tablet but let me know if you need examples of anything I mentioned.


#4

Oh yeah, sorry and thanks @jasonmit . Gosh. I really should spend more time reading and understanding questions people ask.


#5

I wasn’t sure whether implementing the logic in renderTemplate is a good idea, so thanks for the encouragement @jasonmit :smile: