Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ember.js app should redirect to login, when ember-data receive http status 401

I want my Emberjs application to handle HTTP Status Unauthorized (401).

The application uses ember-data to integrate a JSON API (Rails).

The client layer (Emberjs) should redirect to a Emberjs view/template prompting for login, when receiving HTTP Status Unauthorized (401).

How can I do this for the entire application?

like image 910
Jacob Avatar asked Apr 18 '13 08:04

Jacob


2 Answers

I was researching on the same topic and looks like the information here is a little bit outdated. Using Ember 1.7.0, you should handle the error in the route. If you want to apply this to the whole app, you should add it to your ApplicationRoute class, like so

// app/routes/application.js
import Ember from 'ember';

var ApplicationRoute = Ember.Route.extend({
    actions: {
        error: function (error, transition) {
            // Handle the error here
            if (error && error.status === 401) {
                return this.transitionTo('login');
            }
        }
    }
});

export default ApplicationRoute;

This is the same way as the documentation describes it: read here

Update: In newer versions of Ember and Ember Data, the error object structure will be a little different. The status will be a string, contained within an error object, within an errors array:

actions: {
  error: function(error, transition) {
    if (error.errors[0].status === '401') {
      this.transitionTo('sign-in');
    }
  }
}
like image 178
Mirko Akov Avatar answered Sep 28 '22 09:09

Mirko Akov


I've struggled with the same problem. I've succesfully implemented the following hack.

window.App = Em.Application.extend
  ready: ->
    $(document).ajaxError( (event, request, settings) =>
      if request.status == 401 && !["/profile", "/users/sign_in.json"].contains(settings.url)
        controller = App.__container__.lookup('controller:application')
        controller.transitionToRoute('sign_in' )
)

The idea is to catch a jQuery ajaxError event. In the event you can check witch the type of error (.e.g. request.status == 401), url that caused the error (e.g. settings.url) and based on that information you can decide what to do.

Hope this helps

like image 45
Bert Hajee Avatar answered Sep 28 '22 07:09

Bert Hajee