jeudi 4 février 2016

how to handle error 401 in simple ember auth?

The problem is the session will expire after a predetermined amount of time. Many times when this happens the ember.js app is still loaded. So all requests to the backend return a 401 {not autorized} response.

so i need to redirect user to the login page and clear the last token from the session so that isauthenticated property becomes false.

I am using custom authenticator.

import Base from 'ember-simple-auth/authenticators/base';
import ENV from '../config/environment';
import Ember from 'ember';

export default Base.extend({

    restore: function(data) {
        return new Ember.RSVP.Promise(function (resolve, reject) {
            if (!Ember.isEmpty(data.token)) {
                resolve(data);
            }
            else {
                reject();
            }
        });
    },
    authenticate: function(options) {
        return new Ember.RSVP.Promise(function(resolve, reject) {
            Ember.$.ajax({
                type: "POST",
                contentType: 'application/json',
                url: ENV.CONSTANTS.API_URL + '/authentication',
                data: JSON.stringify({
                    username: options.username,
                    password: options.password
                })
            }).then(function(response) {
                if(!response.token){
                    Ember.run(function(){
                        reject(response.message);
                    });
                } else {
                    Ember.run(function() {
                        resolve(response);
                    });
                }
            }, function(xhr, status, error) {
                Ember.run(function() {
                    reject(xhr.responseJSON || xhr.responseText);
                });
            });
        });
    },
    invalidate: function(data) {
        return new Ember.RSVP.Promise(function(resolve, reject) {
            Ember.$.ajax({
                type: "GET",
                url: ENV.CONSTANTS.API_URL + '/authentication/logout'
            }).then(function(response) {
                Ember.run(function() {
                    resolve(response);
                });
            }, function(xhr, status, error) {
                Ember.run(function() {
                    reject(xhr.responseJSON || xhr.responseText);
                });
            });
        });
    }
});

I am using ember simple auth 1.0.0. Anybody have a working solution to this problem?




Aucun commentaire:

Enregistrer un commentaire