Skip to content

Instantly share code, notes, and snippets.

@epexa
Last active October 2, 2019 19:19
Show Gist options
  • Save epexa/9a939cf332041e18f375d35df1145c75 to your computer and use it in GitHub Desktop.
Save epexa/9a939cf332041e18f375d35df1145c75 to your computer and use it in GitHub Desktop.
Authentication through MetaMask example
<!--
This example based on official documentation:
https://metamask.github.io/metamask-docs/API_Reference/Ethereum_Provider
Gist: https://gist.github.com/epexa/9a939cf332041e18f375d35df1145c75
Author example: @epexa
-->
<button id="auth">authentication through metamask</button>
<button id="sign" style="display: none">sign</button>
<h2 id="status"></h2>
<script>
const $authButton = document.querySelector('#auth');
const $statusText = document.querySelector('#status');
const $signButton = document.querySelector('#sign');
let provider;
$authButton.addEventListener('click', () => {
if (typeof window.ethereum !== 'undefined' || (typeof window.web3 !== 'undefined')) {
provider = window['ethereum'] || window.web3.currentProvider;
if (provider.isMetaMask) {
if (provider.networkVersion == '1') {
provider.autoRefreshOnNetworkChange = false;
provider.enable()
.then(accounts => {
$statusText.innerText = `authorized with account: ${accounts[0]}`;
$authButton.style.display = 'none';
$signButton.style.display = 'block';
})
.catch(error => {
console.error(error);
});
}
else $statusText.innerText = 'need change to main network!';
}
else $statusText.innerText = 'it\'s not a metamask!';
}
else $statusText.innerText = 'need enable metamask!';
});
$signButton.addEventListener('click', () => {
web3.personal.sign(web3.sha3('example'), provider.selectedAddress, (error, result) => {
if ( ! error) {
$statusText.innerText = `signed! result: ${result}`;
/* axios
.post(`${base}/api/user`, {
publicAddress: provider.selectedAddress,
signature: result
})
.then(response => {
localStorage.setItem('publicAddress', response.data.publicAddress);
localStorage.setItem('userId', response.data.userId);
localStorage.setItem('jwtToken', response.data.accessToken);
axios.defaults.headers.common = {
'Authorization': `Bearer ${localStorage.getItem('jwtToken')}`
};
})
.catch(error => {
console.error({error});
}); */
} else {
if (error.code == -32603) $statusText.innerText = 'decline sign!';
else console.error(error);
}
});
});
</script>
@epexa
Copy link
Author

epexa commented Oct 2, 2019

Authentication through MetaMask other example:

https://gist.github.com/epexa/4ce11de71d1b40f8cb1d35567e993b53

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment