Setting up firebase Admin SDK in node - node.js

I am developing a password-recovery block for my application. I found out that I could call sendPasswordResetEmail function which works fine, but I want to use my own email template so I need to use Admin SDK and call admin.auth().generatePasswordResetLink(email) to generate a link where I could extract the OobCode to use resetPassword function. But for some reason I got the following error calling admin.auth().generatePasswordResetLink(email):
errorInfo: {
code: 'auth/insufficient-permission',
message: 'Credential implementation provided to initializeApp() via the "credential" property has insufficient permission to access the requested resource.
},
codePrefix: 'auth'
}
The permissions settting should be fine in firebase, altough I am totaly new in firebase.
Here is my code what includes the firebase-client initialization, admin sdk initialization, the post request:
import config from "config"
const serviceAccount = config.get('serviceAccount')
import admin from "firebase-admin";
const dbUrl = ""
try {
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: dbUrl
});
} catch (e) {
console.log(e)
}
export {admin}
//------------------------------------------------
import { admin } from './firebase/firAdmin.js';
import {getAuth} from "firebase/auth";
import {initializeApp} from 'firebase/app';
const {
FIR_APP_ID,
FIR_API_KEY,
FIR_PROJECT_ID,
FIR_DATBASE_URL,
FIR_AUTH_DOMAIN,
FIR_STORAGE_BUCKET,
FIR_MESSAGING_SENDER_ID
} = process.env
const firConfig = {
appId: FIR_APP_ID,
apiKey: FIR_API_KEY,
authDomain: FIR_AUTH_DOMAIN,
databaseURL: FIR_DATBASE_URL,
projectId: FIR_PROJECT_ID,
storageBucket: FIR_STORAGE_BUCKET,
messagingSenderId: FIR_MESSAGING_SENDER_ID
}
const firApp = initializeApp(firConfig)
//------------------------------------------------
app.post('/password-recovery', async(req, res) => {
const {email} = req.body;
admin.auth().generatePasswordResetLink(email).then((link) => {
console.log(link)
})
.catch((err) => {
console.log(err)
});

Related

Firebase auth emulator was blocked

I got this error when I using local firebase emulator.
blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Private-Network' header was present in the preflight response for this private network request targeting the local address space.
Initializing firebase.
export const firebaseConfig = {
apiKey: process.env.NEXT_PUBLIC_FIREBASE_APP_APIKEY,
authDomain: process.env.NEXT_PUBLIC_FIREBASE_APP_AUTHDOMAIN,
databaseURL: process.env.NEXT_PUBLIC_FIREBASE_APP_DATABASEURL,
projectId: process.env.NEXT_PUBLIC_FIREBASE_APP_PROJECT_ID,
storageBucket: process.env.NEXT_PUBLIC_FIREBASE_APP_STORAGE_BUCKET,
messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_APP_MESSAGING_SENDER_ID,
appId: process.env.NEXT_PUBLIC_FIREBASE_APP_APP_ID,
measurementId: process.env.NEXT_PUBLIC_FIREBASE_APP_MEASUREMENT_ID
};
const firebase = initializeApp(firebaseConfig);
const store = initializeFirestore(firebase, {ignoreUndefinedProperties: true})
const db = getDatabase(firebase);
const auth = getAuth(firebase);
const storage = getStorage(firebase);
// #ts-ignore
if (process.env.NEXT_PUBLIC_MODE === 'emulator' && !auth.config.emulator) {
connectDatabaseEmulator(db, "localhost", 9000);
connectFirestoreEmulator(store, "localhost", 8080);
connectAuthEmulator(auth, 'http://localhost:9099');
connectStorageEmulator(storage, 'localhost', 9199);
}
export { store, db, auth, storage };
export default firebase;
I got error when I execute this code.
const userCredential = await setPersistence(auth, browserLocalPersistence).then(async () => {
return await signInWithEmailAndPassword(auth, e.email, e.password).then((userCredential) => {
return userCredential;
}).catch((error) => {
console.log(error);
return null;
});
});
versions
node: v16.4.0
react: ^17.0.2
next: ^12.0.7
firebase: ^9.6.2
firebase-tools#10.6.0
Chrome: 100.0.4896.75(Official Build) (x86_64)

How to access admin firestore using firebase admin SDK?

I am working on an application, where it uses Next.js and Firebase.
I need to implement server-side authentication. Firebase allows connecting the server using Firebase Admin SDK.
const admin = require("firebase-admin");
const serviceAccount = require("../../../../3-firebase/service-account-key/service-account-file.json");
try {
admin.initializeApp({
credential: admin.credential.cert({
client_email: process.env.FIREBASE_CLIENT_EMAIL,
private_key: process.env.FIREBASE_PRIVATE_KEY,
project_id: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
}),
});
console.log("Initialized.");
} catch (error) {
if (!/already exists/u.test(error.message)) {
console.error("Firebase admin initialization error", error.stack);
}
}
const db = admin.firestore();
export { db };
I installed the firebase-admin package using NPM and I setup firebase admin SDK using the above code by creating a separate file called "firebase-admin.js"
import { initializeApp } from "firebase/app";
const firebaseConfig = {
apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
};
const defaultApp = initializeApp(firebaseConfig);
export default defaultApp;
The above code is the default firebase application setup in a separate file called "firebase.js"
The problem I encountered is I am not able to access the admin firestore. However, I can able to access the default firestore.
What I observed is admin SDK is able to initialize using the credentials (private key). But I don't know why I can't access admin firestore. I mean when i use admin firestore the console gives error of 500 (internal server error)
Here is the error message, when I try to use admin.firestore()
{"error":{"code":"invalid-argument","name":"FirebaseError"}}
versions I am using
"firebase": "^9.6.6",
"firebase-admin": "^10.0.2",
Timely help is much needed
You're importing the initializeApp method from the Firebase Javascript SDK. You should be importing from the Firebase Admin SDK.
import { initializeApp } from "firebase/app";
vs.
import { initializeApp } from "firebase-admin/app";
Using firebase-admin v10.0.2 I was able to successfully access the db adding this in my config.js file, similar to your firebase.js file.
const ServiceAccount = require('../superSecretServiceKeyFile.json');
const app = initializeApp(ServiceAccount);
const { getFirestore } = require('firebase-admin/firestore');
const db = getFirestore(app);

DB.collection is not a function in firebase?

I am trying to connect to firebase realtime database (not firestore) but I get the error that db.collection is not a function. Other answers in StackOverflow are mentioned with respect to Firestore. Thanks for your help.
const admin = require('firebase-admin');
// Firebase configuration - this should not be public.
// Please use your own config if you intend to use this code.
var firebaseConfig = {
apiKey: "xxxxxxxxxxxxxxxxxx",
authDomain: "xxxxxxxxxxxxxxxxxx",
databaseURL: "xxxxxxxxxxxxxxxxxx",
projectId: "xxxxxxxxxxxxxxxxxx",
storageBucket: "xxxxxxxxxxxxxxxxxx",
messagingSenderId: "xxxxxxxxxxxxxxxxxx",
}
// Initialize Firebase
admin.initializeApp(firebaseConfig)
const db = admin.database();
console.log("Database setup");
(async () => {
try {
let query = db.collection('users');
console.log("Doing database query now");
await query.get().then(querySnapshot => {
console.log(querySnapshot);
});
} catch (error) {
console.log(error);
}
})();
const db = admin.database() is an instance of Firebase realtime database and not Firestore. To get an instance of Firestore, use admin.firestore().
const admin = require('firebase-admin');
admin.initializeApp(/* service account */)
const db = admin.firestore();
console.log("Firestore setup");
Admin SDK uses a service account and not the same public credentials. You can refer to the documentation for detailed information. You can get a service account from project settings.
Do note that if you are using Cloud functions then you can leave initializeApp() empty.

How to get user using email and password firebase with nodejs [duplicate]

This question already has answers here:
Firebase Admin SDK to Log user in from Server
(3 answers)
Closed 3 years ago.
how can I get a user data using firebase authentication with email and password of an user?
the only way I was able to capture the user was to use the
firebase.auth() function.getUserByEmail(email)
but I don't find how to perform that call passing the email and password of the user, any help with this question?
my source code:
var express = require('express');
var app = express();
const firebase = require('firebase-admin');
const inquirer = require('inquirer')
const serviceAccount = require('...')
var currentUser;
var userProfile;
var config = {
credential: firebase.credential.cert(serviceAccount),
apiKey: "...",
authDomain: "...",
databaseURL: "...",
projectId: "...",
storageBucket: "...",
messagingSenderId: "..."
};
firebase.initializeApp(config);
let server = app.listen('8081', function (err) {
if (err) {
console.log(err);
}
console.log("App listening on port " + "8081");
var authentication = [
{
type: 'input',
name: 'email',
message: "Type your email:",
},
{
type: 'password',
name: 'password',
message: "Type your password:",
},
]
inquirer.prompt(authentication).then(answers => {
console.log(`Hello! The application is starting!`)
startCrawler(answers['email'], answers['password'])
})
async () => {
await firebase.auth().getUserByEmail(email) //Here where I want to grab the user with email and password
.then((user) => {
currentUser = user.toJSON();
}).catch(err => {
console.log('Email or password invalid!');
});
if (!currentUser) { return };
}
});
It looks like you're trying to sign the user in on a Node.js app that uses the Firebase Admin SDK. The Firebase Admin SDK doesn't have the concept of a signed in user. If you need that, consider using the regular Firebase SDK for web applications.
Also see my answer here: Firebase Admin SDK to Log user in from Server

can’t find variable self

I want to get a firebase token from expo and have to send that token to node js, using that I have to send push notifications.
Whenever I run the below code it shows unhandled promise rejection: reference error: can't find variable: self
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import * as firebase from 'firebase';
import '#firebase/messaging';
export default class App extends React.Component {
async componentDidMount(){
const config = {
apiKey: "xxxx",
authDomain: "xxxx",
databaseURL: "xxxx",
projectId: "xxx",
storageBucket: "xxxx",
messagingSenderId: "xxx",
debug: true
};
firebase.initializeApp(config);
firebase.messaging().getToken()
.then(fcmToken => {
if (fcmToken) {
// user has a device token
console.log("check for tokens",fcmToken)
} else {
console.log("err")
// user doesn't have a device token yet
}
});
}
render() {
return (
<Text>Open up App.js to start working on your app!</Text>
);
}
}

Resources