Skip to content

Instantly share code, notes, and snippets.

@n-ari
Last active December 30, 2020 12:18
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 n-ari/75932d9fbac313625ab9a2e9683c8da2 to your computer and use it in GitHub Desktop.
Save n-ari/75932d9fbac313625ab9a2e9683c8da2 to your computer and use it in GitHub Desktop.
Gated Content with Netlify Identity
/login.html /login.html 200!
/* 200! Role=admin
/* /login.html?redirect=/:splat 302!
<!DOCTYPE HTML>
<html lang="ja">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>login</title>
<script type="text/javascript" src="https://identity.netlify.com/v1/netlify-identity-widget.js"></script>
</head>
<body>
<div data-netlify-identity-menu></div>
<script>
const query = [...new URLSearchParams(location.search).entries()]
.reduce((obj, e) => ({...obj, [e[0]]: e[1]}), {});
const redirectURL = query.redirect || "/";
function note(text) {
document.body.insertAdjacentHTML('beforeend', `<p>${text}</p>`);
}
netlifyIdentity.on('init', user => {
if (user) {
if (!user.token
|| !user.token.expires_at
|| !user.app_metadata
|| !user.app_metadata.roles) {
// invalid token
note("Invalid token. Please try to login again.")
} else if (user.token.expires_at <= Date.now()) {
// expired
note("Token expired. Please wait...");
netlifyIdentity.refresh().then(_ => {
if (user.token.expires_at <= Date.now()) {
note("Cannot refresh token. Please try to login again.");
} else {
note(`
Token refreshed.
<a href="${redirectURL}">redirecting...</a>
`);
setTimeout(() => { location.href = redirectURL; }, 500);
}
});
} else if (!user.app_metadata.roles.includes("admin")) {
// no role
note("`admin` role does not found in your token. Please contact admin to get the role, or try to login again.");
} else {
// already logined
note(`
Already logined.
<a href="${redirectURL}">Please click here to back to the content.</a>
`);
}
} else {
// manual login
note("Please login to access the content.");
netlifyIdentity.on('login', user => {
netlifyIdentity.close();
note(`
Login succeeded.
<a href="${redirectURL}">redirecting...</a>
`);
setTimeout(() => { location.href = redirectURL; }, 500);
});
}
});
</script>
</body>
</html>
  • たまにトークンが正しくリフレッシュされてるのにリダイレクトをされることがある
    • 良く分かってない
    • _redirects ファイルの書式が間違っているか netlifyIdentity の使い方が間違っているか変なキャッシュが残っているか
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment