Skip to content

Instantly share code, notes, and snippets.

@callahad
Last active December 23, 2015 15:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save callahad/6654015 to your computer and use it in GitHub Desktop.
Save callahad/6654015 to your computer and use it in GitHub Desktop.
Let's Code Test Driven JavaScript's Persona integration.
// Copyright (c) 2012-2013 Titanium I.T. LLC. All rights reserved.
/*global window, document, navigator, XMLHttpRequest, alert, setupPersona, $*/
(function() {
"use strict";
var ready = false;
window.setupPersona = function(email) {
$(".tdjs-signin").click(onSignin);
$(".tdjs-signout").click(onSignout);
navigator.id.watch({
loggedInUser: email,
onlogin: postLoginRequest,
onlogout: postLogoutRequest,
onready: function () { ready = true; }
});
};
function onSignin(event) {
event.preventDefault();
navigator.id.request({
siteName: "Let’s Code JavaScript"
});
}
function onSignout(event) {
event.preventDefault();
navigator.id.logout();
}
function postLoginRequest(assertion) {
var post = $.post("/v3/auth/login", "assertion=" + assertion);
post.done(function(data) {
if (data === "ok") {
window.location.reload();
}
else {
alert("Login failed. Please try again.");
// Must logout on failure or Persona will keep trying to validate assertion. But that will trigger
// onlogout (postLogoutRequest()) synchronously, which will cause a window reload, so the logout must be
// the last thing we do in this function.
navigator.id.logout();
}
});
post.fail(function(data, textStatus) {
alert("Could not contact server to log in. Please try again.");
});
}
function postLogoutRequest() {
if (!ready) { return; }
var post = $.post("/v3/auth/logout", "ios6_cache_buster=" + (new Date()).valueOf());
post.done(function(data) {
window.location.reload();
});
post.fail(function(data, textStatus) {
alert("Could not contact server to log out. Please try again.");
});
}
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment