Created
April 17, 2020 02:36
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
import React from 'react'; | |
import get from 'lodash/get'; | |
import isEmpty from 'lodash/isEmpty'; | |
import queryString from 'query-string'; | |
import shajs from 'sha.js'; | |
import { LandingComingSoon } from '../LandingComingSoon'; | |
const ACCESS_TOKEN = process.env.GATSBY_ACCESS_TOKEN; | |
const TOKEN_KEY = 'token'; | |
const IS_SSR = typeof window === 'undefined'; | |
function hashToken(token) { | |
// Using the same function we used to generate GATSBY_ACCESS_TOKEN | |
// so we can match if the user has a valid password | |
return shajs('sha256').update(token).digest('hex'); | |
} | |
function getCachedToken() { | |
if (IS_SSR) { | |
return; | |
} | |
return get(localStorage, [TOKEN_KEY]); | |
} | |
function cacheToken(token) { | |
if (IS_SSR) { | |
// Skip on SSR | |
return; | |
} | |
localStorage[TOKEN_KEY] = token; | |
} | |
function getTokenFromLocation(location) { | |
const locationSearch = queryString.parse(location.search); | |
const token = get(locationSearch, [TOKEN_KEY]); | |
if (!token) { | |
return; | |
} | |
// We are hashing this token to see if it matches the | |
// GATSBY_ACCESS_TOKEN | |
return hashToken(token); | |
} | |
function getToken(location) { | |
const cachedToken = getCachedToken(); | |
if (cachedToken) { | |
return cachedToken; | |
} | |
const token = getTokenFromLocation(location); | |
if (!isEmpty(token) && token === ACCESS_TOKEN) { | |
cacheToken(token); | |
return token; | |
} | |
return; | |
} | |
export const withPageProtection = (Component) => (props) => { | |
const location = !IS_SSR && window.location; | |
const token = getToken(location); | |
// TODO: Once we release into production and in order to prevent | |
// people to access staging, we can set here | |
// token || process.env === 'production' | |
const isUserAllowed = token; | |
if (!isUserAllowed) { | |
return <LandingComingSoon />; | |
} | |
return <Component {...props} />; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment