Skip to content

Instantly share code, notes, and snippets.

@BitPuffin
Last active December 25, 2015 06:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save BitPuffin/6936429 to your computer and use it in GitHub Desktop.
Save BitPuffin/6936429 to your computer and use it in GitHub Desktop.
var signinLink = document.getElementById('signin')
var signoutLink = document.getElementById('signout')
if (signinLink) {
signinLink.onclick = function() { alert("Time to sign in!"); navigator.id.request(); }
}
if (signoutLink) {
signoutLink.onclick = function() { navigator.id.logout(); }
}
#! stdtmpl
# proc htmlLayout(request: TRequest, content, title: string): string =
# result = ""
<!DOCTYPE html>
<html>
<head>
<title>${title}</title>
<script src="https://login.persona.org/include.js"></script>
<script src="/js/personabuttons.js"></script>
<script src="/js/personawatcher.js"></script>
</head>
<body>
<h1>Personal Site</h1>
${content}
<a href="#" id="signin"><img src="https://developer.mozilla.org/files/3969/plain_sign_in_blue.png"/></a>
<a href="#" id="signout">sign out</a>
</body>
</html>
function getCookie(name) {
var parts = document.cookie.split(name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
var currentUser = getCookie("useremail") || null
function simpleXhrSentinel(xhr) {
return function() {
if (xhr.readyState == 4) {
if (xhr.status == 200){
// reload page to reflect new login state
window.location.reload();
}
else {
navigator.id.logout();
alert("XMLHttpRequest error: " + xhr.status);
}
}
}
}
function verifyAssertion(assertion) {
// Your backend must return HTTP status code 200 to indicate successful
// verification of user's email address and it must arrange for the binding
// of currentUser to said address when the page is reloaded
var xhr = new XMLHttpRequest();
xhr.open("POST", "/sign-in", true);
// see http://www.openjs.com/articles/ajax_xmlhttp_using_post.php
var param = "assertion="+assertion;
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-length", param.length);
xhr.setRequestHeader("Connection", "close");
xhr.send(param); // for verification by your backend
xhr.onreadystatechange = simpleXhrSentinel(xhr);
}
function signoutUser() {
// Your backend must return HTTP status code 200 to indicate successful
// sign out (usually the resetting of one or more session variables) and
// it must arrange for the binding of currentUser to 'null' when the page
// is reloaded
var xhr = new XMLHttpRequest();
xhr.open("GET", "/sign-out", true);
xhr.send(null);
xhr.onreadystatechange = simpleXhrSentinel(xhr);
}
navigator.id.watch({
loggedInUser: currentUser,
onlogin: verifyAssertion,
onlogout: signoutUser
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment