Skip to content

Instantly share code, notes, and snippets.

@brantje
Created February 6, 2017 11:50
Show Gist options
  • Save brantje/d7ef651807204c830a1c2bfcd7164359 to your computer and use it in GitHub Desktop.
Save brantje/d7ef651807204c830a1c2bfcd7164359 to your computer and use it in GitHub Desktop.
var api_request = function (endpoint, method, data, callback) {
API.cookies.getAll({url: _API.host}).then(function (cookies) {
if(!cookies){
make_request();
return;
}
if(cookies.length === 0){
make_request();
return;
}
remove_cookies(cookies, make_request)
});
function restore_cookies(cookies){
if(!cookies){
return;
}
for(var i = 0; i < cookies.length; i++){
API.cookies.set(cookies[i], function(){});
}
}
function remove_cookies(cookies, cb){
for(var i = 0; i < cookies.length; i++){
API.cookies.remove({url: _API.host, name: cookies[i].name}).then((function (i, cookies, cb) {
return function () {
if(i === cookies.length-1){
cb()
}
}
})(i, cookies, cb));
}
}
function make_request(cookies_to_restore) {
method = (!method) ? 'GET' : method;
var encodedLogin = btoa(_API.username + ":" + _API.password);
var url = _API.host + '/index.php/apps/passman' + endpoint;
console.log('Requesting ' + url);
var opts = {
type: method,
url: url,
crossDomain: false,
withCredentials: false,
cache: false,
headers: {
'Authorization': 'Basic ' + encodedLogin
},
dataType: "json",
success: function (result, status, xhr) {
callback(result);
restore_cookies(cookies_to_restore);
},
error: function (httpObj, err) {
callback({error: err, result: httpObj});
restore_cookies(cookies_to_restore);
}
};
if (data) {
opts.data = data;
}
$.ajax(opts);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment