I have the following setup to connect to firebase but for some reason in the browser console it shows that auth.createUserWithEmailAndPassword() is not a function. Is there something wrong with my code?
import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.0.2/firebase-app.js';
import { getAuth, createUserWithEmailAndPassword } from 'https://www.gstatic.com/firebasejs/9.0.2/firebase-auth.js';
import { getFirestore } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-firestore.js"
// TODO: Replace the following with your app's Firebase project configuration
const firebaseConfig = {
" my config here "
};
const app = initializeApp(firebaseConfig);
const auth = getAuth();
const db = getFirestore();
var button = document.getElementById("button").addEventListener("click", function () {
var email = document.getElementById("email").value;
var phone = document.getElementById("phone").value;
var password = document.getElementById("password").value;
auth.createUserWithEmailAndPassword(email, password).then(cred => {
console.log(cred);
})
});
edit: I removed auth. from auth.createUserWithEmailAndPassword(email, password).then(cred => { console.log(cred); and now it is giving me the current error: ```Uncaught (in promise) TypeError: Cannot create property
'_canInitEmulator' on string 'heheboi#gmail.com'
at _performFetchWithErrorHandling (firebase-auth.js:1983)
at _performApiRequest (firebase-auth.js:1958)
at _performSignInRequest (firebase-auth.js:2030)
at signUp (firebase-auth.js:5330)
at createUserWithEmailAndPassword (firebase-auth.js:5978)
at HTMLButtonElement.<anonymous> (register.html:48) ``
Just update your code to the latest Firebase SDK 9:
import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.0.2/firebase-app.js';
import { getAuth, createUserWithEmailAndPassword } from 'https://www.gstatic.com/firebasejs/9.0.2/firebase-auth.js';
import { getFirestore } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-firestore.js"
// TODO: Replace the following with your app's Firebase project configuration
const firebaseConfig = {
" my config here "
};
const app = initializeApp(firebaseConfig);
const auth = getAuth();
const db = getFirestore();
var button = document.getElementById("button").addEventListener("click", function () {
var email = document.getElementById("email").value;
var phone = document.getElementById("phone").value;
var password = document.getElementById("password").value;
createUserWithEmailAndPassword(auth, email, password).then(cred => {
console.log(cred);
}).catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
// ..
});
});
You are already importing createUserWithEmailAndPassword. You can't use auth.createUserWithEmailAndPassword anymore. You can find here the latest docs.
Related
I am currently trying to make an account page for users using data from Firebase auth, database, and storage. The only problem with the code is that the text and images that need data from the database(username and profile picture) are appearing as undefined so it seems like the database isn't returning data
the code:
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.13.0/firebase-app.js"
import { getAuth, createUserWithEmailAndPassword, signInWithEmailAndPassword, signOut, onAuthStateChanged } from 'https://www.gstatic.com/firebasejs/9.13.0/firebase-auth.js';
import { getDatabase, set, ref } from 'https://www.gstatic.com/firebasejs/9.13.0/firebase-database.js';
import { getStorage, ref as storageRef, getDownloadURL } from 'https://www.gstatic.com/firebasejs/9.13.0/firebase-storage.js'
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: ""
};
//Initiate firebase services
const app = initializeApp(firebaseConfig);
const auth = getAuth(app)
const database = getDatabase(app)
const storage = getStorage(app)
//Get image folder from storage
const imageFolder = storageRef(storage, "gs://betterbadgeworld.appspot.com/profile-pictures")
//Get user UID and accountData
let user = onAuthStateChanged(auth, (user)=>{
if (user) {
var user = auth.currentUser
return user
}
else {
return
}
})
let accountData = onAuthStateChanged(auth, (user)=>{
if (user) {
var userUID = user.uid
var accountData = ref(database, 'users/' + user.uid)
console.log(accountData)
return accountData
}
else {
return
}
})
//Add username and profile picture to website with accountData
function initializeData(accountData) {
//Get profile picture file name
let userProfilePicture = accountData.profilePicture + ".png"
//Set username in text box
const usernameText = document.createTextNode(accountData.username)
const usernameBox = document.getElementById('username')
usernameBox.appendChild(usernameText)
//Get profile picture div, make gs:// link, and get downloadURL for it
const profilePicBox = document.getElementById("profile-picture")
var profileGSLink = imageFolder + "/" + userProfilePicture
var profileLink = getDownloadURL(storageRef(storage, profileGSLink))
//Make image element and use profileLink as source
let img = document.createElement("img");
img.src = profileLink;
profilePicBox.appendChild(img);
}
initializeData(accountData)
the code that isn't returning the data:
let accountData = onAuthStateChanged(auth, (user)=>{
if (user) {
var accountData = ref(database, 'users/' + user.uid)
console.log(accountData)
return accountData
}
else {
return
}
})
I was running my next.js app and trying to fetch user I am getting "cannot read properties of undefined" error
And following error in the console
Below is the code I was using
import Ewitter from './Ewitter.json';
import ethers from 'ethers';
import { useState, useEffect } from 'react';
const ContractABI = Ewitter.abi;
const ContractAddress = '0x5FbDB2315678afecb367f032d93F642f64180aa3';
const Ethereum = typeof window !== 'undefined' && (window as any).ethereum;
const getEwitterContract = () => {
const provider = new ethers.providers.Web3Provider(Ethereum);
const signer = provider.getSigner();
const EwitterContract = new ethers.Contract(
ContractAddress,
ContractABI,
signer
);
return EwitterContract;
};
const useEwitter = () => {
// const Ewitter = getEwitterContract();
const [currentAccount, setCurrentAccount] = useState<string>('');
const [currentUser, setCurrentUser] = useState<string>('');
const connect = async () => {
try {
if (!Ethereum) {
alert('Please install MetaMask');
return;
}
const accounts = await Ethereum.request({
method: 'eth_requestAccounts',
});
if (accounts.length === 0) {
alert('Please unlock MetaMask');
return;
}
const account = accounts[0];
console.log('connected to account: ', account);
setCurrentAccount(account);
} catch (errors) {
console.log(errors);
}
};
useEffect(() => {
if(!Ethereum){
console.log("No ethereum wallet found, please install metamask")
return ;
}
connect();
}, []);
useEffect(() =>{
if(currentAccount){
getUser();
}
}, [currentAccount])
const getUser = async ()=>{
const contract = getEwitterContract();
const user = await contract.getUser(currentAccount);
const {avatar, bio, name, username, wallet} = user;
console.log(user);
return user;
}
return { connect, account: currentAccount };
};
export default useEwitter;
#Update1
I've changed import ethers from 'ethers' to import {ethers} from 'ethers' and now I'm facing this error
If unable to understand properly or if you want to see the whole codebase then this is the link to the github repo
https://github.com/ChiragDogra/ewitter/blob/userIssue/dapp/hooks/useEwitter.ts
believe or not I just had that issue.
the problem is how you are importing ethers. Should be
import { ethers } from "ethers";
I made a form , here I am trying to get all datails of form to the profile page
Here's form code:
`
<script type="module">
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.10/firebase-app.js";
import { getDatabase, set, ref, get, child } from "https://www.gstatic.com/firebasejs/9.6.10/firebase-database.js";
const firebaseConfig = {
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = getDatabase();
const SelectRole = document.getElementById('selectRole');
const facebook = document.getElementById('furl');
const twitter = document.getElementById('turl');
const insta = document.getElementById('instaurl');
const linkdin = document.getElementById('lurl');
const submit = document.getElementById('sub_btn');
const username = document.getElementById('uname');
function InsertData() {
set(ref(db, "TheUsers/" + username.value), {
Username: username.value,
// Password : password.value,
Role: SelectRole.value,
FacebookURL: facebook.value,
TwitterURL: twitter.value,
InstagramURL: insta.value,
LinkedinURL: linkdin.value,
})
.then(() => {
alert("Data stored successfully");
window.location = "profile.html";
})
.catch((error) => {
alert("unsuccessful,error" + error);
});
}
//------------------------------------------------------ASSIGN EVENT TO BTN------------------------------------//
submit.addEventListener('click', InsertData);
</script>
\`
After filling the form page... page redirect to the profile page and should have shows all datails ......but heres at profile page all fields shows undefine.
Here's profile page code:
`
<script type="module">
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.10/firebase-app.js";
import { getDatabase, set, ref, get, child } from "https://www.gstatic.com/firebasejs/9.6.10/firebase-database.js";
const firebaseConfig = {
....
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = getDatabase();
const SelectRole = document.getElementById('selectRole');
const facebook = document.getElementById('furl');
const twitter = document.getElementById('turl');
const insta = document.getElementById('instaurl');
const linkdin = document.getElementById('lurl');
const submit = document.getElementById('sub_btn');
const username = document.getElementById('uname');
function selectdata() {
const dbref = ref(db);
get(child(dbref, "TheUsers/" + username.value)).then((snapshot) => {
if (snapshot.exists()) {
username.value = snapshot.val().Username;
SelectRole.value = snapshot.val().Role;
facebook.value = snapshot.val().FacebookURL;
twitter.value = snapshot.val().TwitterURL;
insta.value = snapshot.val().InstagramURL;
linkdin.value = snapshot.val().LinkedinURL;
}
else {
alert("No data Found")
}
})
.catch((error) => {
alert("error" + error);
})
}
// submit.addEventListener('click',selectdata);
window.onload = selectdata;
</script>
`
Thanks for any help.
I'm trying to add MFA inside my web app and the multiFactor property is missing.
Check the code:
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.2/firebase-app.js";
import { getAuth, RecaptchaVerifier, PhoneAuthProvider, signInWithEmailAndPassword }
from "https://www.gstatic.com/firebasejs/9.6.2/firebase-auth.js";
const firebaseConfig = {
...
};
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
auth.onAuthStateChanged((user) => {
const userEl = document.getElementById('user');
if (user) {
userEl.innerHTML = `${user.email} logged in. ${JSON.stringify(
user.multiFactor.enrolledFactors
)}`;
} else {
userEl.innerHTML = 'signed out';
}
});
window.recaptchaVerifier = new RecaptchaVerifier('recaptcha-container', {
'size': 'invisible',
'callback': (response) => {
console.log('captcha solved!');
}
}, auth);
const enrollBtn = document.getElementById('enroll-button');
enrollBtn.onclick = () => {
signInWithEmailAndPassword(auth, 'blabla#gmail.com', 'foobar').then(() => {
const user = auth.currentUser;
if (!user) {
return alert('User not logged!');
}
const phoneNumber = document.getElementById('enroll-phone').value;
console.log(user);
user.multiFactor.getSession().then((session) => {
const phoneOpts = {
phoneNumber,
session,
};
const phoneAuthProvider = new PhoneAuthProvider();
phoneAuthProvider.verifyPhoneNumber(
phoneOpts,
window.recaptchaVerifier
).then((verificationId) => {
window.verificationId = verificationId;
alert('sms text sent!');
});
});
});
};
In the code above the user.multiFactor is undefined. The signIn is returning the user normally, but without this property.
error on console:
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'getSession')
The Firebase project have MFA enabled:
enter image description here
**************** UPDATE *******************
Apparently change the code to this worked:
const mfaUser = multiFactor(user);
mfaUser.getSession().then((session) => {
But now I'm getting this error when I call verifyPhoneNumber:
VM21778 index.html:315 TypeError: Cannot read properties of undefined (reading 'tenantId')
at _addTidIfNecessary (firebase-auth.js:1934:14)
at startEnrollPhoneMfa (firebase-auth.js:6778:125)
at _verifyPhoneNumber (firebase-auth.js:8500:40)
However I'm not using Multi-Tenancy option, this is disabled in my project.
Changed to:
const mfaUser = multiFactor(user);
mfaUser.getSession().then((session) => {
and:
const phoneAuthProvider = new PhoneAuthProvider(auth);
I don't know if Firebase Auth docs is deprecated or I'm doing something different. XD
I'm using firebase twitter authentication for my project. The auth variable returning the credentials does not contain the account's twitter username but everything else.
I need to work with the username, is there a way to work around this?
Users shown in the console look like thisFirebase Console
How do I get the respective identifier of a uid?
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.1.2/firebase-app.js";
import { getAuth, signInWithPopup, TwitterAuthProvider } from "https://www.gstatic.com/firebasejs/9.1.2/firebase-auth.js";
const app = initializeApp(firebaseConfig);
const provider = new TwitterAuthProvider();
const auth = getAuth();
document.querySelector('button').addEventListener('click', authenticate);
function authenticate() {
signInWithPopup(auth, provider)
.then((result) => {
const credential = TwitterAuthProvider.credentialFromResult(result);
const token = credential.accessToken;
const secret = credential.secret;
const user = result.user;
console.log(result)
}).catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
const email = error.email;
const credential = TwitterAuthProvider.credentialFromError(error);
console.log(error);
});
}
Is there a way to get the username from this 'auth' variable, check below code for ref
import { getAuth } from "https://www.gstatic.com/firebasejs/9.1.2/firebase-auth.js"
const auth = getAuth();
auth.onAuthStateChanged(user => {
if(user){
// window.location.href = "/home/index.html"
}else{
}
})
I think you mean Twitter handle (also called screen name) by "username"
const provider = new TwitterAuthProvider();
const userInfo = await signInWithPopup(auth, provider);
console.log(userInfo._tokenResponse.screenName) // twitter handle
Hello there you can try this:
firebase.auth().signInWithPopup(new firebase.auth.TwitterAuthProvider())
.then((userCredential) => {
// here you get the username
console.log(userCredential.additionalUserInfo.username);
})
.catch((error) => {
console.log("error occurred");
});
or else you can get the info using this if you are having id :
let url = `https://api.twitter.com/1.1/users/show.json?user_id=${the_uid_from_provider_data}`;
fetch(url)
.then(response => {
let data = response.json();
console.log(data);
})
.catch(error => {
// handle the error
});
For me it works like that
const res = await signInWithPopup(auth, provider);
const user = res.user;
const username = user.reloadUserInfo.screenName;
console.log(`username #${username}`);