Full example code
<!DOCTYPE html>
<html>
<head>
<title>Dapp</title>
</head>
<body>
<h1>Welcome to Dapp</h1>
<p>This is a simple dapp.</p>
<p id="token">Token: </p>
<p id="user">User: </p>
<button
onclick="login()"
>
login
</button>
<button
onclick="redirectLogin()"
>
Redirect login
</button>
</body>
<script>
function redirectLogin() {
location.href = `https://api.well.eco/oauth/auth?state=${Date.now()}${Math.floor(Math.random() * 100000)}&hostname=test.com&redirect_url=${encodeURIComponent('https://oauth-test.pages.dev')}`;
}
function login() {
// Open a new popup window for the OAuth flow
const popup = window.open(`https://api.well.eco/oauth/auth?state=${Date.now()}${Math.floor(Math.random() * 100000)}`, 'WELL OAuth', 'width=500,height=600');
// Listen for messages from the popup window
window.addEventListener('message', async function(event) {
console.log(event)
// Check for the user data in the message
if (event.data && event.data.type === 'well-oauth-token' && event.data.token) {
// Update the original page with the user's info
document.getElementById('token').textContent = `Token: ${event.data.token}`;
const res = await fetch('https://api.well.eco/oauth/me', {
headers: {
'oauth-token': event.data.token
}
});
const data = await res.json()
document.getElementById('user').textContent = `User: ${JSON.stringify(data, null , ' ')}`;
// Close the popup window
if (popup) {
popup.close();
}
}
});
}
(async () => {
const initialToken = new URLSearchParams(location.search).get('token');
console.log({initialToken})
if (initialToken) {
document.getElementById('token').textContent = `Token: ${initialToken}`;
const res = await fetch('https://api.well.eco/oauth/me', {
headers: {
'oauth-token': initialToken
}
});
const data = await res.json()
document.getElementById('user').textContent = `User: ${JSON.stringify(data, null , ' ')}`;
// Close the popup window
if (popup) {
popup.close();
}
}
})();
</script>
</html>
Test website: https://oauth-test.pages.dev
Last updated