Skip to content

Instantly share code, notes, and snippets.

@lucascaton
Created May 11, 2019 01:56
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 lucascaton/eda8061fd430041ce1a10b91bba0657f to your computer and use it in GitHub Desktop.
Save lucascaton/eda8061fd430041ce1a10b91bba0657f to your computer and use it in GitHub Desktop.
Código explicado na LIVE #006: https://www.lucascaton.com.br/lives/
document.addEventListener('DOMContentLoaded', () => {
const uri = URI(window.location.href);
const cookieName = uri.path() + '-auth';
const authParam = uri.query(true)['auth'];
const wbp = document.querySelector('head meta[name=wbp]').content;
if (isUserAuthenticated()) {
document.querySelector('body').setAttribute('style', ''); // Show page
} else {
if (checkWBP()) {
document.cookie = cookieName + '=' + asciiToHexa(wbp);
} else {
window.location = window.location.href.replace(/(\/|\.html)?$/, '-inscricao/');
}
}
if (authParam !== undefined) {
// Removes 'auth' query string as user is already authenticated
window.location = URI(window.location.href).removeSearch('auth').toString();
}
function isUserAuthenticated() {
return getCookie(cookieName) === asciiToHexa(wbp);
}
// Copied from https://www.w3schools.com/js/js_cookies.asp
function getCookie(cname) {
var name = cname + '=';
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') { c = c.substring(1); }
if (c.indexOf(name) == 0) { return c.substring(name.length, c.length); }
}
return '';
}
function checkWBP() {
return authParam === asciiToHexa(wbp);
}
function asciiToHexa(str) {
var arr1 = [];
for (var n = 0, l = str.length; n < l; n ++) {
var hex = Number(str.charCodeAt(n)).toString(16);
arr1.push(hex);
}
return arr1.join('');
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment