Firebase SignInWIthEmailAndPasswod doesn't work - javascript

I'm having issues implementing Login logic using Firebase email and password method. I've done everything according to documentation for 8 and 9 SDK versions but they don't work. To be more specific .then doesn't work.
I've implemented register and sign out without any issue, but login doesn't do anything. Here is login:
import firebase from 'firebase/app'
import 'firebase/auth';
import { useHistory } from 'react-router-dom';
...
const loginUser = (email, password) => {
firebase.auth().signInWithEmailAndPassword(email, password).then((userCredential) => {
console.log('user', userCredential)
history.push('/admin')
})
.catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
console.error(errorCode, errorMessage)
});
}
}
...
Whatever I try to log in .then() nothing happens, there is also no error. In network tab verifyPassword request is cancelled.
I really don't understand what is wrong there since it should be easy implementation.
Thanks

firebase.auth()
is not available in Firebase V9. Make sure to read Docs of Firebase V9.
Because Firebase V9 doesn't built-in Object-Oriented Way. It was built with Functional
Way.
You can change as
import { initializeApp } from 'firebase/app';
import { getAuth, signInWithEmailAndPassword } from 'firebase/auth';
const firebaseConfig = {
////
}
initializeApp(firebaseConfig)
const auth = getAuth()
const loginUser = (email, password) => {
signInWithEmailAndPassword(auth, email, password).then((userCredential) => {
console.log('user', userCredential)
history.push('/admin')
})
.catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
console.error(errorCode, errorMessage)
});
}
}
Kindly read the Documentation to your doubts.
I would recommend you to watch Net Ninja's Firebase V9
Click here

Related

I can create firebase user using this code, but how can I add display Name, phone Number and other information in default firebase user table? Thanks

This is my funcation code.
const signUpFun = () => {
if (isValidForm()) {
createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
// Signed in
const user = userCredential.user;
setbitdata({});
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
setEmailAndPasswordCheck(true)
setTimeout(() => {
setEmailAndPasswordCheck(false)
}, 3500)
});
}
}
import { getAuth, updateProfile } from "firebase/auth";
const auth = getAuth();
updateProfile(auth.currentUser, {
displayName: "My Name", photoURL: "https://example.com/jane-q-user/profile.jpg"
}).then(() => {
// Profile updated!
}).catch((error) => {
// An error occurred
});
If you are using firebase version 8, then you should use like these:
import firebase from "firebase";
const user = firebase.auth().currentUser;
user.updateProfile({
displayName: "My Name",
photoURL: "https://example.com/jane-q-user/profile.jpg"
}).then(() => {
// Update successful
}).catch((error) => {
// An error occurred
});
Firebase have very great documentation, you should probably read that, as like #Alexandros Giotas mentioned the link for official Documentation for your question
You're probably looking for the updateProfile method.
Using modular imports:
import { getAuth, updateProfile } from "firebase/auth";
const auth = getAuth();
updateProfile(auth.currentUser, {
displayName: "Your display name here",
// more updating..
}).then(() => {
// Success
}).catch((e) => {
// Handle errors.
});
Remember that updateProfile returns a Promise which you should handle, with either then() & catch() as shown above or await if you're updating within an async function.
I encourage you to read the Firebase docs on updating a user's profile.
There are more code snippets there, that answer your question probably better than I did.

Recaptcha is working, Email is Verified, 2FA turned on in console... yet auth/internal-error when running .verifyPhoneNumber()

I have checked other StackOverflow posts and haven't seen anything that addresses the issue. I am trying to set up multi-factor auth for my app. As far as I've understood the basic steps are:
Enable 2FA in firebase console & Google Cloud Console ✔️
Set up a reCaptcha ✔️
Get the session ✔️
And send a verification message with phoneAuthProvider.verifyPhoneNumber ❌
I'm not sure why as all I am getting is FirebaseError: Firebase: Error (auth/internal-error)
Imports
import 'firebase/auth';
import * as firebase2 from 'firebase/auth';
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import firebaseApp from '../../../../src/config';
import { getAuth } from 'firebase/auth';
Here is the recaptcha:
useEffect(() => {
try {
const auth22 = getAuth();
// Recaptcha only ran once, stored in state
const recaptchaVerifier = new firebase2.RecaptchaVerifier(
'multifactor-form',
{
size: 'invisible',
callback: (response) => {
console.log('successfully created the captcha');
console.log(response);
},
},
auth22
);
console.log(recaptchaVerifier);
setCaptchaVerifier(recaptchaVerifier);
} catch (e) {
console.log(e);
}
}, []);
And here's the function I run when I click send SMS:
const sendSMS = async function (phoneNumber: any) {
console.log(phoneNumber);
console.log(typeof phoneNumber);
try {
let verificationId: any;
const auth = firebaseApp.auth();
const user = auth.currentUser;
const newNumber: string = `+1${phoneNumber}`;
const session = await user.multiFactor.getSession();
const phoneOpts = {
newNumber,
session,
};
const phoneAuthProvider = new firebase.auth.PhoneAuthProvider();
verificationId = await phoneAuthProvider.verifyPhoneNumber(phoneOpts, recaptchaVerfifier);
//Nothing runs after the line above this one
alert('sms text sent!');
} catch (e) {
console.log(e);
}
};
Can anyone see anything wrong with what I'm doing?
If needed Here are the tutorials, and guides, I've been following along with:
https://fireship.io/lessons/two-factor-auth-firebase/#identity-platform
https://cloud.google.com/identity-platform/docs/web/mfa?_ga=2.210928085.-1381314988.1638978774
I had the same error. Some info in docs is incorrect https://cloud.google.com/identity-platform/docs/web/mfa#web-version-8_21
Incorrect !!!
// Specify the phone number and pass the MFA session.
var phoneInfoOptions = {
phoneNumber: phoneNumber,
session: resolver.session
};
Correct version is in the complete example code at the bottom of docs:
var phoneInfoOptions = {
multiFactorHint: resolver.hints[selectedIndex],
session: resolver.session
};

Firebase Firestore db.collection is not a function

I am developing a shift scheduler and I use firebase authentication and firestore. My idea is that when a user signs up it creates a document in collection "workers" and sets the doc id to the user's email. When the user adds a shift I want to add the shift info into a sub-collection "shifts" inside that user's document where all the shifts will be stored. I have read and seen many guides but I can't get the syntax/logic right, and due to firebase changes of syntax I am including most of the settings I use.
firebase.js:
import { getAuth } from "firebase/auth";
import "firebase/firestore";
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore"
require('firebase/auth');
const firebaseConfig = {
...
};
const app = initializeApp(firebaseConfig);
export const db = getFirestore(app);
export const auth = getAuth(app);
export default app
SignUp.js:
import { db } from "../firebase";
import { collection, addDoc, setDoc, doc } from "firebase/firestore";
import { useAuth } from '../contexts/AuthContext';
const { signup } = useAuth();
const handleSubmit = async (event) => {
event.preventDefault();
setError("");
try{
const data = new FormData(event.currentTarget);
await signup ( data.get('email'), data.get('password'));
const docRef = await setDoc(doc(db, "workers", data.get('email')), {
firstName: data.get('firstName'),
lastName: data.get('lastName'),
email: data.get('email'),
numberOfShifts: 0
});
}
catch(e){
console.error("Error adding document: ", e);
setError("Failed to create an account");
};
The sign up works nicely and the document id is the email. The error is when I try to add shift to that document (the collection shifts is not created at this stage)
Datasheed.js: (where the user inputs their shifts)
import { auth } from "../firebase"
import { db } from "../firebase";
const commitChanges = async ({ added, changed, deleted }) => {
if (added) {
try {
db.collection("workers")
.doc(auth.currentUser.email)
.collection("shifts")
.add(added);
} catch (e) {
console.error("Error adding document: ", e);
}
}
For now I am only trying to add, and the caught exception I am getting is:
Error adding document: TypeError: firebase__WEBPACK_IMPORTED_MODULE_5_.db.collection is not a function.
From what I have read the problem is that I use firebase modular and it doesn't have db.collection anymore and it uses collection refs. Do I need the collection ref for the sub-collection as well? What changes do I need to do in order to implement this?
You are using Modular SDK and also modular syntax in signup.js. You should use the same syntax everywhere else. Try refactoring like this:
const commitChanges = async ({ added, changed, deleted }) => {
if (added) {
try {
await addDoc(collection(db, "workers", auth.currentUser.email, "shifts"), added)
} catch (e) {
console.error("Error adding document: ", e);
}
}
}
You can learn more about the new syntax in the documentation.

How to use setPersistence in Firebase Modular SDK V9?

i try firebase 9 version persistence for login:
setPersistence(auth, firebaseApp.auth.Persistence.LOCAL).then( async() => {
// login
}).catch((e) => {
this.error = e.message
})
show error:
Uncaught TypeError: Cannot read property 'Persistence' of undefined
any clue?
You need to import persistence states this way:
import {
getAuth,
setPersistence,
browserLocalPersistence,
browserSessionPersistence,
inMemoryPersistence
} from "firebase/auth";
const auth = getAuth()
await setPersistence(auth, browserLocalPersistence);
Namespaced Version V8
Modular Version V9
firebase.auth.Auth.Persistence.LOCAL
browserLocalPersistence
firebase.auth.Auth.Persistence.SESSION
browserSessionPersistence
firebase.auth.Auth.Persistence.NONE
inMemoryPersistence

my data is not adding in to my firebase real time database

my data is not adding in to my firebase real time database. I have facing the problem during sending data in firebase real time database. It gives an error config_firebase__WEBPACK_IMPORTED_MODULE_0_.default.database is not a function.
I also import 'firebase/database' in my firebase.js file.
import firebase from "../../config/firebase"
import { getAuth, signInWithPopup, FacebookAuthProvider } from "firebase/auth";
const facebook_login=()=>{
return (dispatch)=>{
const provider = new FacebookAuthProvider();
const auth = getAuth();
signInWithPopup(auth, provider)
.then((result) => {
console.log("Facebook Login")
var user = result.user;
var credential = FacebookAuthProvider.credentialFromResult(result);
var accessToken = credential.accessToken;
let create_user={
name:user.displayName,
email:user.email,
profile:user.photoURL,
uid:user.uid
}
firebase.database().ref('/').child(`users/${user.uid}`).set(create_user)
.then(()=>{
alert("Login Successfull")
})
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
const email = error.email;
const credential = FacebookAuthProvider.credentialFromError(error);
console.log(errorMessage)
});
}
}
export{
facebook_login
}
Since you are using the new Modular SDK, you should not use the firebase.database() namespaced syntax.
import { getDatabase, ref, set } from "firebase/database";
const db = getDatabase();
set(ref(db, `users/${user.uid}`), create_user);
You can learn more about the modular syntax in the documentation.

Categories