Skip to content

Instantly share code, notes, and snippets.

@dealproc
Created July 17, 2014 15:56
Show Gist options
  • Save dealproc/86caa4b9ae8535489efc to your computer and use it in GitHub Desktop.
Save dealproc/86caa4b9ae8535489efc to your computer and use it in GitHub Desktop.
The way we sent the headers to the api backend from DurandalJS
define(['amplify'], function () {
return {
BeginAuthorization: function () {
var authorizationUrl = SystemState.AuthorizationUrl,
client_id = SystemState.ClientID,
scope = SystemState.AuthScope,
response_type = "token",
redirect_uri = SystemState.AuthRedirectURI,
state = Date.now() + "" + Math.random();
var url = authorizationUrl + "?" + "&" +
"client_id=" + encodeURI(client_id) + "&" +
"scope=" + encodeURI(scope) + "&" +
"response_type=" + encodeURI(response_type) + "&" +
"redirect_uri=" + encodeURI(redirect_uri) + "&" +
"state=" + encodeURI(state);
amplify.store("state", state);
amplify.store("return_to", window.location);
window.location.href = url;
},
IsAuthenticated: function () {
var token = amplify.store("token");
var token_expires = amplify.store("token_expires");
if (token && new Date() < new Date(token_expires)) {
return "ok";
}
var params = [],
queryString = location.hash.substring(1),
regex = /([^&=]+)=([^&]*)/g,
m;
while (m = regex.exec(queryString)) {
params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
};
if (params.error) {
return "error";
};
var state = amplify.store("state") || Date.now() + "" + Math.random();
if (params.state !== state) {
return "invalid state";
};
amplify.store("token", params.access_token);
var tExpires = new Date();
tExpires.setSeconds(tExpires.getSeconds() + (params.expires_in * 1));
amplify.store("token_expires", tExpires);
window.location.hash = "";
return "ok";
},
SignOut: function() {
this.clear();
window.top.location.href = "/Auth/SignOut";
},
token: function () {
return {
scheme: "bearer",
token: amplify.store("token") || ""
};
},
clear: function () {
amplify.store("state", null);
amplify.store("token", null);
amplify.store("token_expires", null);
amplify.store("return_to", null);
}
};
});
/// <reference path="../../Scripts/jquery-2.0.3.intellisense.js" />
/// <reference path="../../Scripts/jquery-2.0.3.js" />
define(["durandal/app", "jquery", "knockout", "lib/AuthorizationManager"], function (app, $, ko, authManager) {
return function () {
var errorHandler = function (xhr, textStatus, errorThrown) {
switch (xhr.status) {
case 401:
authManager.clear();
authManager.BeginAuthorization();
break;
case 400:
app.showMessage("There was a problem submitting your request. " + xhr.statusText);
break;
default:
// RB: Do not remove. Want to roll over at some point to this form of error message. We cannot handle
// Aggregate Exceptions (think a list of multiple issues.)
var jsonError = $.parseJSON(xhr.responseText);
app.showMessage("There was a problem submitting your request. " + jsonError.Message || "We could not process your request", "Request Failed");
//if (jsonError["Message"] !== undefined && jsonError["Message"] !== null) {
// var messages = []
// try {
// var msgConverted = $.parseJSON(jsonError.Message);
// if ($.isArray(msgConverted)) {
// var messages = $.map(msgConverted, function (msg) {
// return msg.Message;
// });
// } else {
// messages.push(jsonError.Message);
// }
// } catch (err) {
// messages.push(jsonError.Message);
// };
// return errorMessage.show(messages);
//} else {
// return errorMessage.show([errorThrown + " " + textStatus]);
//}
break;
}
};
var get = function (params) {
var resource = this.resource;
var deferred = $.Deferred(function (def) {
if (!params) {
def.reject();
}
if (!authManager.IsAuthenticated) {
authManager.BeginAuthorization();
}
var auth = authManager.token();
$.ajax({
url: "/api/" + resource, // may need to be "/api/" + resource "/" + params.Id
type: "GET",
dataType: "json",
contentType: "application/json; charset=UTF-8",
data: params,
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", auth.scheme + " " + auth.token);
}
})
.success(function (data, textStatus, xhr) {
def.resolve(data);
})
.error(function (xhr, textStatus, errorThrown) {
errorHandler(xhr, textStatus, errorThrown);
def.reject(xhr, textStatus, errorThrown);
});
});
return deferred;
};
var getByKey = function (key) {
var resource = this.resource;
var deferred = $.Deferred(function (def) {
if (!authManager.IsAuthenticated) {
authManager.BeginAuthorization();
}
if (!key) {
def.reject();
}
var auth = authManager.token();
$.ajax({
url: "/api/" + resource + "/" + key,
type: "GET",
dataType: "json",
contentType: "application/json; charset=UTF-8",
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", auth.scheme + " " + auth.token);
}
})
.success(function (data, textStatus, xhr) {
def.resolve(data);
})
.error(function (xhr, textStatus, errorThrown) {
errorHandler(xhr, textStatus, errorThrown);
def.reject(xhr, textStatus, errorThrown);
});
});
return deferred;
};
var getAll = function (params, options) {
var resource = this.resource;
var deferred = $.Deferred(function (def) {
if (!authManager.IsAuthenticated) {
authManager.BeginAuthorization();
}
var auth = authManager.token();
$.ajax({
url: "/api/" + resource,
type: "GET",
dataType: "json",
contentType: "application/json; charset=UTF-8",
data: params,
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", auth.scheme + " " + auth.token);
}
})
.success(function (data, textStatus, xhr) {
def.resolve(data);
})
.error(function (xhr, textStatus, errorThrown) {
errorHandler(xhr, textStatus, errorThrown);
def.reject(xhr, textStatus, errorThrown);
});
});
return deferred;
};
var create = function (item) {
var data = ko.toJSON(item);
var resource = this.resource;
var deferred = $.Deferred(function (def) {
if (!authManager.IsAuthenticated) {
authManager.BeginAuthorization();
}
var auth = authManager.token();
$.ajax({
url: "/api/" + resource,
type: "PUT",
dataType: "json",
contentType: "application/json; charset=UTF-8",
data: data,
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", auth.scheme + " " + auth.token);
}
})
.success(function (data, textStatus, xhr) {
def.resolve(data);
})
.error(function (xhr, textStatus, errorThrown) {
errorHandler(xhr, textStatus, errorThrown);
def.reject(xhr, textStatus, errorThrown);
});
});
return deferred;
};
var update = function (item) {
var data = ko.toJSON(item);
var resource = this.resource;
var deferred = $.Deferred(function (def) {
if (!authManager.IsAuthenticated) {
authManager.BeginAuthorization();
}
var auth = authManager.token();
$.ajax({
url: "/api/" + resource,
type: "POST",
dataType: "json",
contentType: "application/json; charset=UTF-8",
data: data,
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", auth.scheme + " " + auth.token);
}
})
.success(function (data, textStatus, xhr) {
def.resolve(data);
})
.error(function (xhr, textStatus, errorThrown) {
errorHandler(xhr, textStatus, errorThrown);
def.reject(xhr, textStatus, errorThrown);
});
});
return deferred;
};
var save = function (item) {
var resource = this.resource;
var self = this;
var deferred;
var updated = false;
var unwrapped = ko.toJS(item);
if (!authManager.IsAuthenticated) {
authManager.BeginAuthorization();
}
try {
delete unwrapped["__observable__"];
} catch (err) {
// do nothing.
}
if (unwrapped && unwrapped.Id && unwrapped.Id != 0) {
updated = true;
deferred = self.update(unwrapped);
} else {
deferred = self.create(unwrapped);
}
deferred.updated = function (callback) {
if (updated) {
deferred.then(callback);
}
return deferred;
};
deferred.created = function (callback) {
if (!updated) {
deferred.then(callback);
}
return deferred;
};
return deferred;
};
var remove = function (item, byId) {
var data = ko.toJSON(item);
var resource = this.resource;
var deferred;
if (!authManager.IsAuthenticated) {
authManager.BeginAuthorization();
}
if (byId || byId === undefined) {
deferred = $.Deferred(function (def) {
var auth = authManager.token();
$.ajax({
url: "/api/" + resource + "/Delete?" + $.param(item),
type: "DELETE",
dataType: "json",
contentType: "application/json; charset=UTF8",
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", auth.scheme + " " + auth.token);
}
})
.success(function (data, textStatus, xhr) {
def.resolve(data);
})
.error(function (xhr, textStatus, errorThrown) {
errorHandler(xhr, textStatus, errorThrown);
def.reject(xhr, textStatus, errorThrown);
});
});
} else {
deferred = $.Deferred(function (def) {
var auth = authManager.token();
$.ajax({
url: "/api/" + resource + "/Delete",
type: "DELETE",
dataType: "json",
contentType: "application/json; charset=UTF8",
data: data,
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", auth.scheme + " " + auth.token);
}
})
.success(function (data, textStatus, xhr) {
def.resolve(data);
})
.error(function (xhr, textStatus, errorThrown) {
errorHandler(xhr, textStatus, errorThrown);
def.reject(xhr, textStatus, errorThrown);
});
});
}
return deferred;
};
var action = function (methodToCall, params) {
var resource = this.resource;
var data = ko.toJSON(params);
if (!authManager.IsAuthenticated) {
authManager.BeginAuthorization();
}
var auth = authManager.token();
var settings = {
url: "/api/" + resource + "/" + methodToCall,
type: "POST",
dataType: "json",
contentType: "application/json; charset=UTF-8",
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", auth.scheme + " " + auth.token);
}
};
if (params !== undefined) {
settings["data"] = data;
};
var deferred = $.Deferred(function (def) {
$.ajax(settings)
.success(function (data, textStatus, xhr) {
def.resolve(data);
})
.error(function (xhr, textStatus, errorThrown) {
errorHandler(xhr, textStatus, errorThrown);
def.reject(xhr, textStatus, errorThrown);
});
});
return deferred;
};
var defineRequests = function (resource) {
return {
resource: resource,
get: get,
getByKey: getByKey,
getAll: getAll,
save: save,
update: update,
post: update,
create: create,
put: create,
remove: remove,
action: action
};
};
var makeCall = function (methodType, resourceUri, data) {
var deferred = $.Deferred(function (def) {
if (!authManager.IsAuthenticated) {
authManager.BeginAuthorization();
}
var auth = authManager.token();
$.ajax({
url: "/api/" + resourceUri,
type: methodType,
dataType: "json",
contentType: "application/json; charset=UTF-8",
data: data,
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", auth.scheme + " " + auth.token);
}
})
.success(function (data, textStatus, xhr) {
def.resolve(data);
})
.error(function (xhr, textStatus, errorThrown) {
errorHandler(xhr, textStatus, errorThrown);
def.reject(xhr, textStatus, errorThrown);
});
});
return deferred;
};
return {
define: defineRequests
};
}();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment