Retrieve wallet address after connecting Metamask with Web3.js - javascript

I got this code off github which allows you to connect to MetaMask using web3.js and also to make payment. I then modified it to
Display a Connect Button when user is not logged in by checking if the content of an element is empty and if it is not empty, the connect button is hidden.
Retrieve the connected wallet address which is in the element that hides the button.
The problem i am facing currently is that
The connected wallet address does not display nor is the connect button hidden until i reload the page manually.
I have tried calling location.reload(); after await ethereum.enable(); which works but in turns hide the #status dialogs from displaying when a user declines making payment as a result of the page reloading instead of displaying the dialogs.
Below is my code
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://unpkg.com/#metamask/legacy-web3#latest/dist/metamask.web3.min.js"></script>
</head>
<body>
<div>
<div id="selected-account"></div>
<button class="pay-button">Pay</button>
<div id="status"></div>
<div id="accTabs"></div>
</div>
<script type="text/javascript">
async function initWeb3() {
if (window.ethereum) {
window.web3 = new Web3(ethereum);
try {
await ethereum.enable();
window.location.reload();
} catch (err) {
$("#status").html("User denied account access", err);
}
} else if (window.web3) {
return (window.web3 = new Web3(web3.currentProvider));
} else {
return $("#status").html("No Metamask (or other Web3 Provider) installed");
}
}
selectedAccount = ethereum.selectedAddress;
document.querySelector("#selected-account").textContent = selectedAccount;
$(".pay-button").click(async () => {
await initWeb3();
// paymentAddress is where funds will be send to
const paymentAddress = "0x192c96bfee59158441f26101b2db1af3b07feb40";
const amountEth = "1";
web3.eth.sendTransaction(
{
to: paymentAddress,
value: web3.toWei(amountEth, 'ether')
},
(err, transactionId) => {
if (err) {
console.log("Payment failed", err);
$("#status").html("Payment failed");
} else {
console.log("Payment successful", transactionId);
$("#status").html("Payment successful");
}
}
);
});
</script>
<script>
if ($('#selected-account').text() == '') {
document.getElementById("accTabs").innerHTML = '<button onclick="initWeb3()">Connect Ethereum</button>';
} else {
}
</script>
</body>
</html>
Let me quickly state that there may be some not well written codes here as a result of my not being very good with Javascript. Still learning.
Thanks for your assistance.

The easiest way to answer would be for you to watch this:
YouTube video explaining exactly that

Related

Why does my electron/react project redirect to the next window location then go back to the previous page?

I am using React with Electron and have a login page that is supposed to send the user to the next page when the fields are filled out. I am using the ipcRender to send information to ipcMain. When ipcMain responds back with true, the page should go to the next page. It does this for a second then goes back to the login page and I am really not sure why.
Here is the code I am using for the login page
function handleRedirect(event){
ipcRenderer.send(channels.GET_LOGIN, event.target[0].value,event.target[1].value);
ipcRenderer.on(channels.GET_LOGIN, (event,arg) => {
console.log(arg)
if (arg === true){
console.log("heading on")
window.location.hash = "/nextPage";
}
else{
window.location.hash="/login"
}
});
}
Here is the code for the electron main.js
ipcMain.on(channels.GET_LOGIN, async(event,arg,val) => {
const db = new sqlite.Database('donationDb.db', (err) => {
if (err) {
console.error(err.message);
}
console.log('Connected to the database.');
});
db.run('CREATE TABLE IF NOT EXISTS login(username text, password text)', (err) => {
if (err) {
console.log(err);
throw err;
}
});
console.log(val);
event.sender.send(channels.GET_LOGIN, true);
db.close();
});

MSAL.js infinite loop, not calling Microsoft Sign-In Page

I am trying really hard to make MSAL work with Vanilla JavaScript, but it just doesn't work.
Whenever I am trying to click the Sign In button on the Login Page, the Login page just refreshes and nothing happens, the Microsoft Sign In Page is not being shown.
Also no errors are logged to console.
After clicking the Sign In button for like 200 or more times and page refreshing that many times, the Microsoft Sign In page shows up and then it works fine.
Script reference
<script type="text/javascript" src="https://alcdn.msauth.net/lib/1.4.4/js/msal.js" integrity="sha384-fTmwCjhRA6zShZq8Ow5ZkbWwmgp8En46qW6yWpNEkp37MkV50I/V2wjzlEkQ8eWD" crossorigin="anonymous"></script>
JS MSAL code
//Config
const msalConfig = {
auth: {
clientId: "{Client ID}",
authority: "{Authority}",
redirectUri: "{Base App URL}/Dashboard", //This URL is registered in Microsoft AAD
navigateToLoginRequestUrl: false
},
cache: {
cacheLocation: "localStorage",
storeAuthStateInCookie: true,
}
};
//Login Request Object
const loginRequest = {
scopes: ["User.Read"],
prompt: 'login',
};
//Initialize MSAL
var myMSALObj = new Msal.UserAgentApplication(msalConfig);
myMSALObj.handleRedirectCallback(authRedirectCallBack);
//Handle Callback
function authRedirectCallBack(error, response) {
if (error) {
console.log(error);
} else {
if (response.tokenType === "id_token") {
console.log("id_token acquired at: " + new Date().toString());
if (myMSALObj.getAccount()) {
showWelcomeMessage(myMSALObj.getAccount());
}
} else if (response.tokenType === "access_token") {
console.log("access_token acquired at: " + new Date().toString());
accessToken = response.accessToken;
try {
callMSGraph(graphConfig.graphMailEndpoint, accessToken, updateUI);
} catch (err) {
console.log(err)
}
} else {
console.log("token type is:" + response.tokenType);
}
}
}
$(document).on("click", "#btn-testing-msal", function () {
myMSALObj.loginRedirect(loginRequest);
});
Any help will be appreciated, Thanks in advance
Debug your frontend code like this, just trying to make sure where caused your problem, and it may have some help:

How to use AsyncStorage in React-Native

I'm creating an Android App in React-Native.
This is my question:
I have basically 5 pages to manage the user:
1) Authentication ( in which I give the possibility to go to the Login or the SignUp)
2) Login Page
3) SignUp Page. In this page i set the value and then they are passed to the userPage.
4) User page. In this page I have the fetch to do a signup.
5) HomepageUser
In the User page I have the 2 function :
AsyncStorage.setItem
AsyncStorage.getItem
Like this
static async saveLoggedInUser(value) {
try {
await AsyncStorage.setItem("#loggedInUser", JSON.stringify(value));
} catch (error) {
console.log(error.message);
}
}
static async getUserLoggedIn() {
try {
return await AsyncStorage.getItem("#loggedInUser");
} catch (error) {
console.log(error.message);
return null;
}
}
Now My First page is the Authentication, how can I check if an user is already authenticated and then direct it to the HomepageUser??
Thanks you a lot!
On successful login you need to set user token in the Sign in page,
try {
await AsyncStorage.setItem('token', usertoken);
} catch (error) {
// Error saving data
}
Inside the componentDidMount method of your first page you need to check whether user token is set or not,
componentDidMount = async() =>{
try {
const value = await AsyncStorage.getItem('token');
if (value !== null) {
// We have data!!
console.log(value);
}
} catch (error) {
// Error retrieving data
}
}
if token exist navigate to Home page or redirect to Sign in page.
There is an excellent documentation on Authentication flows with React navigation. You can check that if you are using React navigation for routing.
https://reactnavigation.org/docs/en/auth-flow.html

authWithOAuthPopup Error on Web Platform

I am trying to use Firebase's Facebook authentication on a webpage, but I get this error:
Login failed Error: Invalid authentication credentials provided.
at Error (native)
at http://45.55.203.213/js/firebase.js:160:367
at e (http://45.55.203.213/js/firebase.js:140:400)
Here's my Javascript code:
var ref = new Firebase("https://fantasy-smash-bros.firebaseio.com/");
function FBLogin() {
ref.authWithOAuthPopup("facebook", function(error, authData) {
if (error) {
console.log("Login failed", error);
} else {
loginWithAuthData(authData);
}
});
}
function loginWithAuthData(authData) {
username = authData.facebook.displayName;
avatarURL = authData.facebook.cachedUserProfile.picture.data.url;
userID = authData.facebook.id;
}
function attemptLogin() {
var user = ref.getAuth();
if (user) {
loginWithAuthData(user);
} else {
$("#fb-login").click(function () {
FBLogin();
});
}
}
$(document).ready(function () {
attemptLogin();
});
Note: I have imported firebase.js. Here's a copy of the Javascript I used.
I believe I have setup everything correctly: adding Firebase's callback URL to my Facebook app's whitelist, enabling Facebook authentication on the Firebase app. But I am still stumped on what to do. Any help would be greatly appreciated.

Firebase not found in angularjs

I am making an angularJS application, and I plan to use Firebase for simple authentication.
My index.html file includes
<script src="https://cdn.firebase.com/js/simple-login/1.6.2/firebase-simple-login.js"></script>
<script src="scripts/login.js"></script>
My login.js looks like this at the moment:
$(document).ready(function(){
var myRef = new Firebase("https://my_app.firebaseio.com");
var auth = new FirebaseSimpleLogin(myRef, function(error, user) {
if (error) {
// an error occurred while attempting login
console.log(error);
} else if (user) {
// user authenticated with Firebase
console.log("User ID: " + user.uid + ", Provider: " + user.provider);
} else {
// user is logged out
}
});
var authRef = new Firebase("https://my_app.firebaseio.com/.info/authenticated");
authRef.on("value", function(snap) {
if (snap.val() === true) {
alert("authenticated");
} else {
alert("not authenticated");
}
});
auth.login('password', {
email: 'user#host.com',
password: 'password',
});
console.log(auth);
});
All I really want to do with this is test whether I can log in, and what the auth object will look like after a login.
Later, I will integrate the login into a ng-model to pass the data that way rather than just passing it hard coded.
The problem right now is that this code doesn't even run, I get an error back from the javascript console:
Uncaught ReferenceError: Firebase is not defined
Why is this happening?
It seems you haven't included the firebase.js script.
Only the firebase-simple-login.js isn't enough, it require firebase.js.
<script src="https://cdn.firebase.com/js/client/1.0.17/firebase.js"></script>
<script src="https://cdn.firebase.com/js/simple-login/1.6.2/firebase-simple-login.js"></script>
<script src="scripts/login.js"></script>

Categories

Resources