Cannot find modue default firebase app - firebase

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)
...
}
}

Related

Firebase Cloud messaging (Notification)

I'm new here. Been having issues with working with the firebase cloud messaging. Tried sending notification throught the the notification composer but it not promting any notification at my side. N:B I have no knowledge of backend technologies, so only implemented it in the front-end.
This is my code
// For the App.js folder
import { initializeApp } from "firebase/app";
import { getToken, getMessaging, onMessage } from "firebase/messaging";
const firebaseConfig = {
apiKey: "AIzaSyCy1TQbCwalPdU3sBf2sDKraxHpplamGQ8",
authDomain: "fir-project-test-44a6b.firebaseapp.com",
projectId: "fir-project-test-44a6b",
storageBucket: "fir-project-test-44a6b.appspot.com",
messagingSenderId: "648408030635",
appId: "1:648408030635:web:2a94b932f10e11abb6c6ee",
measurementId: "G-2YHQFP9KWX"
};
// Initialize Firebase
const firebaseApp = initializeApp(firebaseConfig);
const messaging = getMessaging(firebaseApp);
Notification.requestPermission().then((permission) => {
if(permission === 'granted'){
console.log('permission granted')
}
})
.catch((err) => {
console.log('permission denied:', err)
})
getToken(messaging, {vapidKey: 'BMRthb-93vz-iQl0XQA8AsKbzMyLq-f2JCB00B2rMb35Z_1iVdWX8CquQ820-z6vyMmdDB0W46FIIS3R5IhTbXY'}).then((token) => {
console.log('my token is', token);
});
onMessage(messaging, (payload) => {
console.log(payload.notification);
new Notification(payload.notification.title, {
body:payload.notification.body
})
})
For the Service worker folder
import { getMessaging, onBackgroundMessage } from "firebase/messaging";
import { initializeApp } from "firebase/app";
importScripts("https://www.gstatic.com/firebasejs/9.16.0/firebase-app.js");
importScripts("https://www.gstatic.com/firebasejs/9.16.0/firebase-messaging.js");
const firebaseConfig = {
apiKey: "AIzaSyCy1TQbCwalPdU3sBf2sDKraxHpplamGQ8",
authDomain: "fir-project-test-44a6b.firebaseapp.com",
projectId: "fir-project-test-44a6b",
storageBucket: "fir-project-test-44a6b.appspot.com",
messagingSenderId: "648408030635",
appId: "1:648408030635:web:2a94b932f10e11abb6c6ee",
measurementId: "G-2YHQFP9KWX"
};
// Initialize Firebase
const firebaseApp = initializeApp(firebaseConfig);
const messaging = getMessaging(firebaseApp);
onBackgroundMessage(messaging, (payload) => {
console.log('received background messages:', payload)
const notificationTitle= payload.notification.notificationTitle
const notificationBody = {
body: payload.notification.body,
}
self.registration.showNotification(notificationTitle, notificationBody);
})
i would apprecitate if someone can come through for me. thanks[image 1(app.jsimage2 (app.js)](https://i.stack.imgur.com/tMoq2.png)
Tried evrything, but to no avail. I want to be able to send notifications to user via the notificTION COMPOSER

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);
});

NextJS: Accessing Google Firestore data

So I'm not sure how to do this exactly. Here is what I have:
In my Index.js I have
Index.getInitialProps = async function () {
const firebase = require('firebase')
const firebaseConfig = {
apiKey: "examplezbxW_9nKoUjas",
authDomain: "example-prod.firebaseapp.com",
databaseURL: "https://example-prod.firebaseio.com",
projectId: "example-prod",
storageBucket: "example-prod.appspot.com",
messagingSenderId: "1234567890",
appId: "1:1234567890:web:1234567890"
};
if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig)
}
const db = firebase.firestore()
const data = db.collection('data').get()
return {
data
}
}
This gives me an error of FirebaseError: projectId must be a string in FirebaseApp.options
(Maybe I need to run the firebase node package and login...)
It says the error is occurring at this line const db = firebase.firestore()
Any help is appreciated. Maybe this isn't the spot I should be trying to load firestore data... not sure.
I also considered creating a node server and doing it that way, but ideally, I'd like to avoid that.
Okay, so there was a couple changes I made to fix this.
I moved my firebase initialization to another file and that file looked like this:
import firebase from 'firebase/app'
import 'firebase/firestore'
export function loadDB() {
try {
var config = {
apiKey: "YOUR INFO HERE",
authDomain: "YOUR INFO HERE.firebaseapp.com",
databaseURL: "https://YOUR INFO HERE.firebaseio.com",
projectId: "YOUR INFO HERE",
storageBucket: "YOUR INFO HERE.appspot.com",
messagingSenderId: "YOUR INFO HERE",
appId: "YOUR INFO HERE"
};
firebase.initializeApp(config);
} catch (err) {
// we skip the "already exists" message which is
// not an actual error when we're hot-reloading
if (!/already exists/.test(err.message)) {
console.error('Firebase initialization error', err.stack);
}
}
return firebase;
}
Then, in my NextJS componenet, in the getInitialProps method, I have:
import { loadDB } from '../lib/db'
Index.getInitialProps = async function () {
const db = await loadDB()
let data = []
const querySnapshot = await db.firestore().collection('data').get()
querySnapshot.forEach(doc => {
data.push(doc.data())
})
return {
data
}
}

Expo firebase auth provider is undefined

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.

firestore vue.js: auth() is not a function

I have a firebase config file like this:
import { firebase } from "#firebase/app";
import "#firebase/firestore";
const firebaseApp = firebase.initializeApp({
apiKey: "myKey",
authDomain: "myDomain",
databaseURL: "myURL",
projectId: "myProject",
storageBucket: "myBucket",
messagingSenderId: "999999999"
});
export const db = firebaseApp.firestore();
export const firebaseApp = firebaseApp;
I am trying to authenticate a user but keep getting firebaseApp.auth() is not a function.
let me = db.collection('staff').where('email', '==', this.current_user.email)
.get()
.then((querySnapshot) => {
querySnapshot.forEach((doc) => {
this.fbUser = doc.id;
let email = doc.data().email;
let pw = doc.data().key;
firebaseApp.auth().onAuthStateChanged(user => {
if (user) {
//console.log('Already authenticated.');
} else {
firebaseApp.auth().signInWithEmailAndPassword(email, pw)
.then(liu => {
//console.log('Logged in', liu.uid);
let uid = liu.uid;
this.$localStorage.set('fbId',this.fbUser, 0);
this.$localStorage.set('fbAuthId', uid, 0);
me.update({
is_active: true
});
});
} // end if
});
});
Don't I have to configure the app? There's no auth functionality in #firebase.
Any help is appreciated.
You should add the auth Firebase service in your initialization, as follows:
import { firebase } from "#firebase/app";
import "#firebase/firestore";
import "#firebase/auth"; // <- NEW
const firebaseApp = firebase.initializeApp({
apiKey: "myKey",
authDomain: "myDomain",
databaseURL: "myURL",
projectId: "myProject",
storageBucket: "myBucket",
messagingSenderId: "999999999"
});
export const db = firebaseApp.firestore();
export const auth = firebaseApp.auth(); // <- NEW
export const firebaseApp = firebaseApp;
Then, in your component, you do:
auth.onAuthStateChanged(user => {})
and
auth.signInWithEmailAndPassword(email, pw)

Resources