2👍
✅
Override Backbone.sync like this. Each request with Backbone goes through Backbone.sync
Backbone._sync = Backbone.sync
Backbone.sync = function(method, model, options) {
options = $.extend({
// In case the request is cross domain, keep these next 4 lines
crossDomain: true
, xhrFields: {
withCredentials: true
}
// Add the token to the request header
, beforeSend: function(xhr){
xhr.setRequestHeader('Authorization', 'Token ' + token);
}
}, options);
return Backbone._sync(method, model, options);
}
You could store the token in localStorage when you post the credentials. I noticed i had to add a short timeout before redirecting in order for the script to have time store the token in localstorage.
user.save({}, {success: function(model, response) {
localStorage.setItem('access_token', response.token)
setTimeout(function(){
window.workspace.navigate('#transaction/list', { trigger: true}); }
, 100);
return true;
}});
and fetch it from there with
, beforeSend: function(xhr){
xhr.setRequestHeader('Authorization', 'Token ' + localStorage.access_token);
}
in order to allow the user to remained logged in when opening a new browser window or tab.
Source:stackexchange.com