Authorize to access routes

Hello,

I’m trying to solve a basic problem but I cannot seem to figure out how to do this with Ember. How can I prevent access to routes until App.User.loggedIn is set to true?

These are the routes that I have:

App.Router.map(function() {
    this.route('login', { path: '/' });
    this.route('home');
    this.route('settings');
    this.route('help');
    // ... and some nested routes too
});

The user model:

App.User = Ember.Object.create({
    loggedIn: false
});

I can implement the redirect function of every route like so:

App.HomeRoute = Ember.Route.extend({
    redirect: function() {
        if (!App.User.loggedIn) {
            this.transitionTo('login');
        }
    }
});

But it feels dirty doing it this way. Is there a better way of solving this problem?

1 Like

Check out the ember-auth project at https://github.com/heartsentwined/ember-auth

It includes a customised route class that allows you to redirect unauthorised requests to the login page.

Hi, I’m not familiar with coffeescript. But looking at this file https://github.com/heartsentwined/ember-auth/blob/master/src/routes/auth.coffee I feel like I’m doing a similar thing.

You could just create a parent AuthenticatedRoute which would implement this behavior, and then all of your routes would just be defined as

App.HomeRoute = App.AuthenticatedRoute({ ... });
2 Likes

Yep, that’s what I ended up doing. I will post a complete example here later on!

4 Likes

Look forward to seeing your progress and example @rytis!

I’ve done some basic auth in my Ember app here. The basic premise is to redirect to login on a 401 from the API. Also, if there’s a global authentication_token variable defined or stored in a cookie, sign all requests with it. Not sure if it’s the best approach (I’m not crazy about the jQuery ajax 401 manipulation), but it has been working pretty well.

1 Like

I like the benburton way but I would also do it using authorization atributes on each request and a correct aproach when “request denied” comes from the server.

On server side you could use an ACL system or something else for each request, declaring resources and types of access (read, write, etc.).