Skip to content

Instantly share code, notes, and snippets.

@mikewest
Last active April 13, 2016 17:12
Show Gist options
  • Save mikewest/2d303c8d7ee8934a99323edeb8c7d21d to your computer and use it in GitHub Desktop.
Save mikewest/2d303c8d7ee8934a99323edeb8c7d21d to your computer and use it in GitHub Desktop.
Guardian + Credential Management API
//
// On https://profile.theguardian.com/signin
//
// Note: This will require relaxing the Content Security Policy on the sign-in page to
// allow `fetch()` to access the signin endpoint at `/actions/signin`.
//
// First, adjust the `autocomplete` attributes on the email and password form fields:
document.querySelector('#signin_field_email').setAttribute('autocomplete', 'username');
document.querySelector('#signin_field_password').setAttribute('autocomplete', 'current-password');
// Then hook up an event listener to the form to catch typed/autofilled sign-ins:
document.querySelector('#signin-form').addEventListener('submit', e => {
if (navigator.credentials) {
var c = new PasswordCredential(e.target);
fetch(e.target.action, { credentials: c, method: 'POST' })
.then(r => {
if (r.type == 'opaqueredirect') { // If we're redirected, success!
navigator.credentials.store(c).then(_ => {
window.location = "http://www.theguardian.com/international";
});
} else {
// Do something clever to handle the sign-in error.
}
});
}
});
// And then try to grab credentials:
navigator.credentials.get({
password: true,
federated: {
"providers": [ "https://facebook.com", "https://accounts.google.com" ]
}
/*
Adding `, unmediated: true` here would grab credentials automatically if
they've allowed that access, and would just return `undefined` without
asking the user if they haven't.
*/
})
.then(c => {
if (c instanceof PasswordCredential) {
c.additionalData = new FormData(document.querySelector('#signin-form'));
c.idName = "email";
fetch("/actions/signin", { credentials: c, method: 'POST' })
.then(r => {
if (r.type == 'opaqueredirect') { // If we're redirected, success!
navigator.credentials.store(c).then(_ => {
window.location = "http://www.theguardian.com/international";
});
} else {
// Do something clever to handle the sign-in error.
}
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment