Expo firebase auth provider is undefined - firebase

I'm using firebase facebook for my app. I just want user's public profile so that I can create user in my database. I do not want firebase full authentication just the profile detail but I am getting the following error.
Here is some code
const firebaseConfig = {
apiKey: FIREBASE_KEY,
authDomain: FIREBASE_AUTH_DOMAIN,
databaseURL: FIREBASE_DATABASE_URL,
projectId: FIREBASE_PROJECT_ID,
storageBucket: FIREBASE_STORAGE_BUCKET
}
export const Firebase = firebase.initializeApp(firebaseConfig);
async loginWithFacebook(navigate){
const { type, token} = await Expo.Facebook.logInWithReadPermissionsAsync(FACEBOOK_APP_ID, {
permissions: ['public_profile'],
});
if (type == 'success') {
const provider = new Firebase.auth.FacebookAuthProvider();
const credential = provider.credential(token);
Firebase.auth().signInWithCredential(credential)
.then((user) => {})
.catch((error) => {
});
}
}
I'm very new in react native please let me know what I'm doing wrong here.

Change your code to the following:
const credential = Firebase.auth.FacebookAuthProvider.credential(token);
Firebase.auth().signInWithCredential(credential)
credential is a static method on firebase.auth.FacebookAuthProvider.

Related

Firebase authentication not working in NuxtJs application

In am using Firebase Authentication in my Nuxt App. I am following the Firebase Documentation for setting up Authentication using GoogleAuthProvider. In my case, onAuthStateChanged() listener returns null even after successfull redirect.
When the user enter my web application, Nuxt will execute the plugin in the client side. There the firebase configuration is initialized. Then the initUser() function defined in useFirebaseAuth.ts composable is called. If user successfully logged In, log the user details.
Note : After I encountered this error, I replaced signInWithRedirect to signInWithPopup, it works very well.
// plugins/firebase.client.ts
import { initializeApp } from "firebase/app";
import { initUser } from "~~/composables/useFirebaseAuth";
export default defineNuxtPlugin(() => {
const config = useRuntimeConfig();
const firebaseConfig = {
apiKey: "...",
authDomain: "...",
databaseURL: "...",
projectId: "...",
appId: "...",
messagingSenderId: "...",
};
// Initialize Firebase
const firebaseApp = initializeApp(firebaseConfig);
initUser(firebaseApp);
})
// composables/useFirebaseAuth.ts
import { FirebaseApp } from "firebase/app";
import { getAuth,signInWithPopup, GoogleAuthProvider, onAuthStateChanged, signInWithRedirect, signOut, User } from "firebase/auth";
import { equalTo, getDatabase, onValue, orderByChild, query, ref as dbRef } from "firebase/database";
export const signInUser = async () => {
const provider = new GoogleAuthProvider();
const auth = getAuth();
await signInWithRedirect(auth, provider)
}
export const initUser = async (firebaseApp: FirebaseApp) => {
const auth = getAuth(firebaseApp)
const db = getDatabase()
onAuthStateChanged(auth, user => {
if (user) {
console.log(user)
} else {
console.log("user not logged in"
return navigateTo('/login')
}
});
}
export const signOutUser = async () => {
const auth = getAuth();
await signOut(auth)
}
In the above code, I always get the user value as null. I am working on the project for 2 months. The authentication works fine almost one month ago. But it is not working now. Please help me to resolve the issue.
# node --version
v19.5.0
# npm version
{
npm: '9.3.1',
node: '19.5.0',
v8: '10.8.168.25-node.11',
uv: '1.44.2',
zlib: '1.2.13',
brotli: '1.0.9',
ares: '1.18.1',
modules: '111',
nghttp2: '1.51.0',
napi: '8',
llhttp: '8.1.0',
uvwasi: '0.0.14',
acorn: '8.8.1',
simdutf: '3.1.0',
undici: '5.14.0',
openssl: '3.0.7+quic',
cldr: '42.0',
icu: '72.1',
tz: '2022g',
unicode: '15.0',
ngtcp2: '0.8.1',
nghttp3: '0.7.0'
}
I have gone through many answers posted for same question in the stackoverflow website. But those answers didn't solved my issues.

How can I get a valid Firebase user JWT token

Given that I have a Firebase project, but no development environment that supports the Firebase SDK, how can I get a valid Firebase JWT for one of the users in the Firebase project? I am able to create cloud functions in the project, and I tried making a function for this (in TypeScript), but to no avail:
import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
admin.initializeApp();
export const login = functions.https.onRequest((req, res) => {
const email: string = req.query.email || req.body.email;
const password: string = req.query.password || req.body.password;
admin.auth().signInWithEmailAndPassword(email, password);
admin.auth().currentUser.getIdToken(true).then((idToken: any) => {
functions.logger.info("token: " + idToken, {structuredData: true});
res.status(200).send(idToken);
}).catch((error: any) => {
functions.logger
.info("could not get token: " + error, {structuredData: true});
res.status(500).send(error);
});
});
This code wont deploy due to these errors:
Property 'signInWithEmailAndPassword' does not exist on type 'Auth'.
Property 'currentUser' does not exist on type 'Auth'.
Here's the JS script I got from a colleague for this:
// Import the functions you need from the SDKs you need
const { initializeApp } = require("firebase/app");
const { getAuth, signInWithEmailAndPassword } = require("firebase/auth");
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "API-key-here",
authDomain: "my-app.firebaseapp.com",
databaseURL: "https://my-app-default-rtdb.firebaseio.com",
projectId: "my-app",
storageBucket: "my-app.appspot.com",
messagingSenderId: "sender-id-here",
appId: "app-id-here",
measurementId: "measurement-id-here"
};
const app = initializeApp(firebaseConfig);
const auth = getAuth();
signInWithEmailAndPassword(auth, "user#example.com", "user-password-here")=
.then((userCredential) => {
console.log(userCredential.user.accessToken);
})
.catch((error) => {
console.log(error.message);
});

firebaseConfig.default.auth promise rejection error

I am trying to signup user with facebook but i am seeing very rigid error and it seems there is no solved help out there so i am asking again
thats my code
async function signInWithFacebook() {
// const appId = Expo.Constants.manifest.extra.facebook.appId;
Facebook.initializeAsync(appid)
const permissions = ['public_profile']; // Permissions required, consult Facebook docs
const {
type,
token,
} = await Facebook.logInWithReadPermissionsAsync(
{permissions}
);
if(type == "success"){
const credential = initFirebase.auth.FacebookAuthProvider.credential(token);
initFirebase.auth().signInWithCredential(credential)
.catch(err => {
console.log(err)
})
}
}
i am using appid in strings but i have not added it here hope you understand that.
and the error is this
this is my firebase config file code
import firebase from "firebase/app"
import "firebase/firestore"
import "firebase/auth"
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "xxxxxxxx",
authDomain: "xxxxxx",
databaseURL: "xxxxxx",
projectId: "xxxx",
storageBucket: "xxxxx",
messagingSenderId: "xxxxx",
appId: "xxxxx"
};
// Initialize Firebase
const initFirebase = firebase.initializeApp(firebaseConfig);
export default initFirebase
variable values are hidden because of privacy .i worked with firestore and that worked but i am seeing issue with auth with facebook .
i am using react native , firebase , expo and not firebase sdk
You don't have to register a Facebook App for Login with Facebook using Firebase. You can use the below code with Firebase Facebook Authentication enabled in the console.
export const loginWithFacebook = (accessToken) => {
const credential = initFirebase.auth.FacebookAuthProvider.credential(accessToken);
return new Promise((resolve, _reject) => {
signInWithCredential(credential).then(response => {
resolve(response);
});
});
};

Cannot find modue default firebase app

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const firebase = require('firebase/app');
const credentials = require('./credentials.json');
const db = admin.firestore();
const user = require('./http-functions/user-creation')
var config = {
apiKey: "KEY",
authDomain: "ecommerce.firebaseapp.com",
databaseURL: "https://ecommerce.firebaseio.com",
projectId: "ecommerce",
storageBucket: "ecommerce.appspot.com",
messagingSenderId: "ID"
};
firebase.initializeApp(config)
admin.initializeApp({
credential: admin.credential.cert(credentials),
databaseURL: "https://ecommerce.firebaseio.com",
projectId: "ecommerce"
});
exports.addUser = functions.https.onRequest((req, res) => user.addUser(req, res, db, firebase))
I'm importing firebase so that I can use the firebase.auth() to create a new user on cloud functions firestore. But I'm having this error where it says that when I run my firebase deploy:
Error: The default Firebase app does not exist. Make sure you call initializeApp() before using any of the Firebase services.
at FirebaseAppError.FirebaseError [as constructor]
Below is the code for adding a new user
module.exports = {
addUser: function(req, res, db, firebase, admin) {
firebase.auth().createUserWithEmailandPassword(email, password)
.then(userRecord => {
const uid = userRecord.uid;
const email = userRecord.email;
return firebase.firestore()
.collection('users')
.doc(uid)
.set({email: email},
{merge: true});
})
.catch(err => {
console.log(err)
})
}
}
Try assigning the intitializeApp into a const and use it instead of firebase.auth()
Something like:
var config = {
apiKey: "KEY",
authDomain: "ecommerce.firebaseapp.com",
...
};
const firebaseApp = firebase.initializeApp(config)
module.exports = {
addUser: function(req, res, db, firebase, admin) {
firebaseApp.auth().createUserWithEmailandPassword(email, password)
...
}
}

Connect Firebase with React Native

I'm trying to connect React Native with Firebase. I'm using the following method to connect Firebase.
import * as firebase from 'firebase';
// Initialize Firebase
const firebaseConfig = {
apiKey: "<YOUR-API-KEY>",
authDomain: "<YOUR-AUTH-DOMAIN>",
databaseURL: "<YOUR-DATABASE-URL>",
storageBucket: "<YOUR-STORAGE-BUCKET>"
};
firebase.initializeApp(firebaseConfig);
app.authWithPassword({
"email": "abc#abc.com",
"password": "abc1234"
}, (error, user_data) => {
if (error) {
alert('Login Failed. Please try again');
} else {
AsyncStorage.setItem('user_data', JSON.stringify(user_data));
}
});
But it returns the following error:
app.authWithPassword is not a function.
I'm using Firebase 3.4 and React Native 0.32.
From the Firebase documentation:
firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
});

Resources