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.
Related
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)
});
Here is my code
var admin = require("firebase-admin");
var serviceAccount = require("./google-services.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
});
module.exports.admin = admin
My API file code
const admin = require('../firebaseConfig')
async function sendFireBaseNotification(registrationToken , message ){
const options = notification_options
return admin.messaging().sendToDevice(registrationToken, message, options)
.then( response => {
console.log("Notification sent successfully"+response)
})
.catch( error => {
console.log(error);
});
}
my firebase version "firebase-admin": "^5.13.1"
I am getting error 'TypeError: admin.messaging is not a function'
I am looking for the solutions , please help.
Version 5.13.1 of the Firebase Admin SDK that you're using is from July 2018 (!). I recommend upgrading to a more recent version.
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);
I've checked the other stacks about this but still not sure why i'm getting insufficient permissions error. Probably I'm being insecure.
I'm trying to sync users from 2 different firebase accounts. The first account calls a firebase function on the second account. If a user does not exist, it creates and does some databasing. If user exists, then it creates a custom token and passes it back to the first account to use in an iframe query parameter.
I've created IAM service account, created keys and saved to file, and edited the service token permissions like the other stacks explain but i'm getting the error nonetheless. Here's my function start:
const firebaseConfig = {
credential: admin.credential.applicationDefault(),
apiKey: "xxxxxxxxxxxxxxxxxxxxxxx",
authDomain: "itsli7-87384.firebaseapp.com",
databaseURL: "https://itsli7-87384.firebaseio.com",
projectId: "itsli7-87384",
storageBucket: "itsli7-87384.appspot.com",
messagingSenderId: "503897448704",
appId: "1:503897448704:web:45773bfb231a24bbe213e5"
}
fb.initializeApp(firebaseConfig);
admin.initializeApp(firebaseConfig);
And the function is running this.
return admin.auth().getUser(data.user.uid)
.then(async function () {
return admin.auth().createCustomToken(data.user.uid)
.then(function (customToken) {
res.send(customToken);
})
.catch(function (error) {
console.log('Error creating custom token:', error);
});
The error
code: auth/insufficient-permission
Error creating custom token: FirebaseAuthError: The caller does not
have permission; Please refer to
https://firebase.google.com/docs/auth/admin/create-custom-tokens for
more details on how to use and troubleshoot this feature.
Instead of using the prescribed method of adding cred.json to admin.credential.applicationDefault(), and passing in the same firebase init config object to admin init, it is working with:
var serviceAccount = JSON.parse(fs.readFileSync("cred.json"));
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://itsli7-87384.firebaseio.com"
});
fb.initializeApp(firebaseConfig);
I am building a CLI app where I want to use firebase as the backend. I am using the firebase node.js sdk for this and I am running into a problem where after successful login, the firestore add / set functions stop responding and do not trigger either the "then" method or the "error" method.
const firebase = require('firebase');
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "<REDACTED>",
authDomain: "<REDACTED>",
databaseURL: "<REDACTED>",
projectId: "<REDACTED>",
storageBucket: "<REDACTED>",
messagingSenderId: "<REDACTED>",
appId: "<REDACTED>"
};
// Initialize Firebase
var app = firebase.initializeApp(firebaseConfig);
function main() {
firebase.auth().signInWithEmailAndPassword('username', 'somepassword').then((cred) => {
console.log('Successful sign in');
firebase.firestore().collection('UserData').doc(cred.user['uid']).collection('ShellCommands').add({'Hello': 'World'}).then(function() {
console.log("Document successfully written!");
terminate();
}).catch(function(error) {
console.log(error);
});
}).catch(function(error) {
console.log(error);
});
}
main();
Now when I run this, I do see the successful sign in console log but after that the app stops and doesn't respond. It seems like its waiting for user input since the keyboard is active.
My firestore rules are open (for testing).
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write;
}
}
}
Am wondering if I messed up chaining the promise or is there something fundamentally wrong with doing it this way. Note, this will not be a server but a CLI app.
[EDITED]: The CLI app gets passed a string which it writes to firestore and exits. So everytime, the CLI is run, it would login and write the string. However, the CLI would be per user, so the user is only allowed to write to their collection. something like UserData/{UserID}/Data.