Created
May 11, 2019 01:56
-
-
Save lucascaton/eda8061fd430041ce1a10b91bba0657f to your computer and use it in GitHub Desktop.
Código explicado na LIVE #006: https://www.lucascaton.com.br/lives/
This file contains hidden or 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
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