Skip to content

Instantly share code, notes, and snippets.

@evvvritt
Last active February 3, 2021 23:03
Show Gist options
  • Save evvvritt/b60b4b1762d477ebe404d87150ca25b2 to your computer and use it in GitHub Desktop.
Save evvvritt/b60b4b1762d477ebe404d87150ca25b2 to your computer and use it in GitHub Desktop.
Netlify Function Password Protect Site
// Netlify Function
require('dotenv').config() // loads environment variables
const password = process.env.SITE_PWD // the password as environment variable
exports.handler = async function (event, context) {
try {
if (event.body === password) {
return {
statusCode: 200,
body: JSON.stringify({ status: 200, msg: 'success' })
}
} else {
return {
statusCode: 401,
body: JSON.stringify({ status: 401, msg: 'incorrect password' })
}
}
} catch (e) {
console.error(e)
return {
statusCode: 500,
body: JSON.stringify({ status: 500, message: 'Internal Server Error', error: e })
}
}
}
const pwd = async cb => {
// load from sessionStorage or prompt new password
const p = sessionStorage.getItem('p') || window.prompt('password')
// calls the netlify function
const checkPwd = (p) => fetch('/.netlify/functions/pwd', { method: 'POST', body: p })
if ((await checkPwd(p)).status === 200) {
sessionStorage.setItem('p', p) // save for refresh
cb()
} else {
// ask again
sessionStorage.removeItem('p')
pwd(cb)
}
}
// pwd(() => initApp())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment