How to use setPersistence in Firebase Modular SDK V9? - javascript

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

Related

React / Stripe / createPortalLink() with firebase v9

I'm using Stripe extension for Firebase with firebase functions.
Since I refactored a bit my code for firebase v9 modular SDK, I'm getting the following console error with my Stripe createPortalLink() function:
Uncaught (in promise) TypeError: _firebase__WEBPACK_IMPORTED_MODULE_2__.default.functions is not a function
at createPortalLink (Subscription.js:99:1)
Here is my function:
async function createPortalLink() {
const functionRef = app
.functions("europe-west1")
.httpsCallable("ext-firestore-stripe-payments-createPortalLink");
const { data } = await functionRef({
returnUrl: `${window.location.origin}/dashboard-pro/abonnement/`,
locale: "auto",
});
window.location.assign(data.url);
}
Can anyone please advise?
Thanks
You need to use the getFunctions() and httpsCallable() functions in the new Modular SDK as shown below:
import { getFunctions, httpsCallable } from "firebase/functions";
// after initializing Firebase
const functions = getFunctions();
const functionRef = httpsCallable(functions, 'ext-firestore-stripe-payments-createPortalLink');
functionRef({
returnUrl: `${window.location.origin}/dashboard-pro/abonnement/`,
locale: "auto",
})
.then((result) => {
const data = result.data;
});
Checkout the documentation for more details.

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 SignInWIthEmailAndPasswod doesn't work

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

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.

Why cant i login with credentials i got from facebook sdk through firebase?

Hi i am having an error with facebook login using expo, facebook sdk and Firebase
[Error: Unsuccessful debug_token response from Facebook: {"error":{"message":"Invalid OAuth access token.","type":"OAuthException","code":190,"fbtrace_id":"AM5hHHrnXuN4ehHi4q_mmR_"}}]
In my console log i can see the credentials are being received yet i still get this error and on my facebook notification i got the notification that i logged into this app, error is in firebase signInWithCredential,
also on facebook debugger : https://developers.facebook.com/tools/debug/accesstoken/ the token from credential logs is valid,
my code
import React from 'react'
import firebase from "firebase/app";
import "firebase/auth";
import {Button} from "react-native-paper";
import * as Facebook from "expo-facebook";
function FacebookLogin({appColor}) {
firebase.auth().onAuthStateChanged(user => {
if (user != null && !user.isAnonymous) {
console.log('We are authenticated now!');
}
// Do other things
});
async function LoginWithFacebook() {
await Facebook.initializeAsync({appId: '741443520140189', appName: 'Just an app'});
const {type, token} = await Facebook.logInWithReadPermissionsAsync({
permissions: ['public_profile'],
});
if (type === "success") {
console.log("TOKEN", token)
const credential = firebase.auth.FacebookAuthProvider.credential(token);
console.log("credentials", credential)
firebase
.auth()
.signInWithCredential(credential)
.catch(error => {
console.log(error)
});
}
}
return <Button onPress={() => LoginWithFacebook()} color={"#fff"} style={{marginTop: "20%"}}>Login</Button>
}
export default FacebookLogin

Categories