Skip to content

Instantly share code, notes, and snippets.

@shortthirdman
Created June 3, 2017 08:19
Show Gist options
  • Save shortthirdman/4813d8819832a9c621ee5f253d88262d to your computer and use it in GitHub Desktop.
Save shortthirdman/4813d8819832a9c621ee5f253d88262d to your computer and use it in GitHub Desktop.
EmberJS Authentication using HTTP/XHR Requests and Response
var API = {
token: null,
login: function(username, password) {
var self = this;
var payload = {
username: username,
password: password
};
var deferred = jQuery.post('/session', payload).then(
function(data) {
self.token = data.token;
return data.user;
},
function(error) {
return { status: error.statusText, message: error.responseText };
}
);
return Ember.RSVP.resolve(deferred);
},
logout: function() {
var self = this;
var settings = { type: 'DELETE', headers: { 'Authorization': 'Token token=' + this.token } };
var deferred = jQuery.ajax('/session', settings).then(function() {
self.token = null;
});
return Ember.RSVP.resolve(deferred);
},
get: function(resource) {
var url = '/' + resource;
var settings;
if (this.token) {
settings = { headers: { 'Authorization': 'Token token=' + this.token } };
} else {
settings = {};
}
var deferred = jQuery.ajax(url, settings).then(null, function(error) {
return { status: error.statusText, message: error.responseText };
});
return Ember.RSVP.resolve(deferred);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment