Last active
June 25, 2018 15:51
-
-
Save xzion/71163a1fcc1bc04203bc240f03169a4b to your computer and use it in GitHub Desktop.
Twitch OAuth in a popup
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// In your app/extension frontend | |
$("#startOauth").click(function () { | |
let btn = $(this); | |
if (!btn.hasClass('is-loading')) { | |
btn.addClass('is-loading'); | |
let authUrl = `https://id.twitch.tv/oauth2/authorize?client_id=${EXTENSION_CLIENT_ID}`; | |
authUrl += "&redirect_uri=" + encodeURIComponent(OAUTH_REDIRECT_URL); | |
authUrl += `&response_type=code`; | |
authUrl += "&scope=" + encodeURIComponent("user:read:email"); | |
authUrl += "&state=" + encodeURIComponent(latestAuth.token); | |
// This opens a popup window | |
var authWindow = window.open(authUrl, "_blank", "width=500,height=600"); | |
window.addEventListener('message', (msg) => { | |
btn.removeClass('is-loading'); | |
authWindow.close(); // This auto-closes the popup | |
if (msg.data == "AUTHCOMPLETE") { | |
// SUCCESSFUL AUTH! Go do more things! | |
} else { | |
// AUTH ERROR! Show an error, prompt for retry etc | |
} | |
}); | |
} | |
}); | |
// When your backend gets hit by the OAuth redirect, it should process the code, then render a blank HTML | |
// page with a script like this included. 'authErr' should be dynamically rendered as a bool, true for success, | |
// false for fail etc. | |
$(function() { | |
if (authErr) { | |
window.opener.postMessage("AUTHERROR", "*"); | |
} else { | |
window.opener.postMessage("AUTHCOMPLETE", "*"); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment