Skip to content

Instantly share code, notes, and snippets.

@jason-dark
Created October 4, 2018 18:33
Show Gist options
  • Save jason-dark/ed850aff3c6030179a9fe1afb64926be to your computer and use it in GitHub Desktop.
Save jason-dark/ed850aff3c6030179a9fe1afb64926be to your computer and use it in GitHub Desktop.
<script>
const privatePages = [
'/private',
'/members'
];
const publicPages = [
'/sign-up',
'/log-in'
];
firebase.auth().onAuthStateChanged(function (user) {
// Get the current path from the URL bar
let rawPath = window.location.pathname;
// Count how many forward slashes it has
let numSlashes = (rawPath.match(/\//ig) || []).length;
// Set an undefined variable which will become the root path
let currentPath;
// Count the number of slashes
if (numSlashes > 1) {
// There were more than 2 slashes (e.g /members/eum-voluptas)
// so set current path to be everything before the last "/" (e.g /members)
currentPath = rawPath.substr(0, rawPath.lastIndexOf("/"));
} else {
// There was only 1 forward slash, nothing to change
currentPath = rawPath;
}
if (user) {
// User is signed in.
if (publicPages.includes(currentPath)) {
window.location.replace('/');
} else {
console.log('User is logged in!');
console.log('Email: ' + user.email);
console.log('UID: ' + user.uid);
signupLink.style.display = 'none';
loginLink.style.display = 'none';
loadingScreen.style.display = 'none';
}
} else {
// User is signed out.
if (privatePages.includes(currentPath)) {
window.location.replace('/');
} else {
console.log('No user is logged in');
privateLink.style.display = 'none';
logoutLink.style.display = 'none';
loadingScreen.style.display = 'none';
}
}
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment