how to initializeApp in firebase with admin privilege - javascript

i have this error when i trying to initialize app with firebase :
"The default Firebase app does not exist. Make sure you call initializeApp() before using any of the Firebase services."
this is my script :
const functions = require("firebase-functions");
const admin = require("firebase-admin");
const servicesAccount = require("./admin.json");
const express = require("express");
const app = express();
const firebase = require("firebase");
const firebaseConfig = {...};
const database = admin.firestore();
firebase.initializeApp(firebaseConfig);
admin.initializeApp({
credential: admin.credential.cert(servicesAccount),
databaseURL: "...",
});
and then all my routes...

You should call initializeApp() before any other methods on the Admin object. Change the order of statements like this:
admin.initializeApp({
credential: admin.credential.cert(servicesAccount),
databaseURL: "...",
});
const database = admin.firestore();
Note that admin.firestore() comes after initializeApp().

Normally, if you want to interact, from a Cloud Function, with the Firebase back-end services (Firestore, the Realtime Database, Cloud Storage, etc.) you just need to initialize the Admin SDK with no parameters
In this case, the SDK uses Google Application Default Credentials and
reads options from the FIREBASE_CONFIG environment variable. ... The
FIREBASE_CONFIG environment variable is included automatically in
Cloud Functions for Firebase functions that were deployed via the
Firebase CLI.
Have also a look at the following section of the Cloud Functions doc: new initialization syntax for firebase-admin.
On the other hand, you do the following
const firebaseConfig = {...};
firebase.initializeApp(firebaseConfig);
when you want to use the Firebase JavaScript SDK in your web app or as a client for end-user access, for example, in a Node.js desktop or IoT application.
So, in conclusion, you should do something like:
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
const express = require("express");
const app = express();
const database = admin.firestore();
//....

Related

Can someone copy my Firebase config data? [duplicate]

This question already has answers here:
Is it safe to expose Firebase apiKey to the public?
(10 answers)
Closed 11 months ago.
I use firebase for authentication on JS. Everything is making in client side. Anyone can look my js files, copy the config datas, can make own project. How can I hide that datas? Because my plan is "pay as you go", If anyone copy that data, i have a big trouble. What should I do?
Maybe Firebase REST API can solve my problem. Is there any example about authentication with REST API.
I tried move codes Node.js but I couldnt handle it.
You can see my index.js, It is on functions folder. I deploy it to firebase hosting.
Authentication doesnt work.
const functions = require("firebase-functions");
const admin = require("firebase-admin");
const express = require("express");
const config = require('./config.js');
const app = express();
admin.initializeApp(config);
const app2 = initializeApp(config);
const auth = getAuth();
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
app.post("/", async (req, res) => {
const user = req.body;
await admin.firestore().collection("users").add(user);
const mail=user.Email;
const pass=user.Password;
createUserWithEmailAndPassword(auth, mail, pass)
.then((userCredential) => {
// Signed in
const user = userCredential.user;
// ...
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
// ..
});
});
exports.widgets = functions.https.onRequest(app);
You can ensure that your firebaseConfig is stored in an environment variable.
You can also secure the app with Firestore security rules and App Check

Firebase REST get data

After watching Firebase Cloud Function Tutorial - REST API Part 1 | Diligent Dev, I have spent several hours trying to understand how to get the entire record that was posted into firestore. Here is index.js code:
const functions = require("firebase-functions");
const express = require("express");
const cors = require("cors");
const admin = require("firebase-admin");
admin.initializeApp();
const app = express();
app.use(cors({origin: true}));
app.post("/", async (req, res) => {
const user = req.body;
await admin.firestore().collection("users").add(user);
res.status(201).send(JSON.stringify(user));
});
The JSON data I posted was:
{"id":123, "name":"Tony Stark", "email":"ironMan#MarvelComics.com"}
In this get, the id is returned but I can't seem to access the other properties that are part of the record (example name: Tony Stark)?
app.get("/:id", async (req, res) => {
const snapshot = await
admin.firestore().collection("users").doc(req.params.id).get();
const userId = snapshot.id;
const userData = snapshot.data():
constole.log(userData);
res.status(200).send(JSON.stringify({id: userId, ...userData}));
});
There must be a simple solution but console.log(userData) is not the answer! :-(
Almost forgot to say, my request from the browser is passing the user id as a query parameter, in this example localhost:5001/projectReference/user/1 and I also tried with the Cloud Firestore document id (.../user/XRAwtfj9FSubeCArvUtQ). In each case I see in the browser the JSON string {"id":"the_value_requested"} but no userData.
What does console.dir(userData) output? That should help you see what's in the returned object.
Are you confident that name and email are avtually present on the record in Firebase? It's possible your retrieval is working as expected but the data expected isn't there.

Im failing to authenticate Big query from my node.js firebase functions index.js file

I am using the big query API in my firebase functions index.js file, but I keep getting an internal server error when initializing the Big query instance, my first attempt was to include my service account key file in the functions directory and my code is below
const functions = require("firebase-functions");
const express = require('express');
const cors = require('cors')({ origin: true });
const app = express();
app.use(cors);
app.use(express.json());
exports.api = functions.https.onRequest(app);
app.post('/create_table', (req, res) => {
'use strict';
const { BigQuery } = require('#google-cloud/bigquery');
const options = {
keyFilename: 'gamelot-c057c-837d4660ae39.json',
projectId: 'gamelot-c057c',
};
const bigquery = new BigQuery(options);
this is the line causing the error
const { BigQuery } = require('#google-cloud/bigquery');
const options = {
keyFilename: 'gamelot-c057c-837d4660ae39.json',
projectId: 'gamelot-c057c',
};
const bigquery = new BigQuery(options);
how can I solve this?
If you are using Cloud Functions for Firebase (i.e. Cloud Functions deployed via the Firebase CLI), you should not pass any options when creating the BigQuery client. Just do as follows:
const { BigQuery } = require('#google-cloud/bigquery');
const bigquery = new BigQuery();
As a matter of fact, Cloud Functions for Firebase use the App Engine default service account, i.e. {project-id}#appspot.gserviceaccount.com, which has an Editor role, which, by default, contains permissions to interact with BigQuery.
You can check here if the Editor "basic" role has the desired permissions.

firebase.auth().currentUser and onAuthStateChanged always null inspite of being signed in

The firebase.auth().currentUser is always null, as is the onAuthStateChanged listener in my node.js code. However, the user is signed in at my front end swift application. And it is from there that I call to the above node.js script in firebase. A snippet of my code is below. Please take a look and let me know how I can resolve this issue.
Version info
firebase 3.17.5
npm 5.4.2
firebase SDK 5.0.4
Platform Information
linux mac-book air 17.2.0
CODE:
'use strict';
const firebase = require('firebase');
const fireApp = require('firebase-app');
const functions = require('firebase-functions');
const fireAuth = require('firebase-auth');
const admin = require('firebase-admin');
const gcs = require('#google-cloud/storage');
const exec = require('child_process').exec;
const path = require('path');
const fs = require('fs');
const google = require('googleapis');
const sizeOf = require('image-size');
var config = {
apiKey: "Ahigdhvd_icvisQijbdsivdbbvb_blisdvchsblksdbs",
authDomain: "my_project.firebaseapp.com",
databaseURL: "https://my_project.firebaseio.com",
projectId: "my_project",
storageBucket: "my_project.appspot.com",
messagingSenderId: "2536384943632"
};
firebase.initializeApp(config);
admin.initializeApp(config);
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
console.log("user is signed in")
} else {
console.log("no user is signed in")
}
});
You can't use the Firebase Authentication SDK like this. The SDK only works on the client side. You can detect when the user logs in an out on the device (web, Android, iOS), but code running elsewhere can't set up listeners like this.
If you need to communicate with a backend about the login state of the user, you'll have to write some code to communicate between the frontend and backend.

How to properly access the app variable set by express in a node.js app?

I'm building a node.js server and my folder structure looks like this:
server.js
app/routes.js
app/routes/users.js
My problem is that i'm not sure how can i use the app variable inside the users.js file. Do i have to require and setup express again in this file or is there a better/easier way to do it? Here is my sample code(just the bare minimum to understand my problem):
server.js
// Include our packages in our main server file
var express = require('express');
var stormpath = require('express-stormpath');
var app = express();
// Init Stormpath for user management and authentication
app.use(stormpath.init(app));
// Load routes
require('./app/routes')(app);
// Start the server
app.listen(process.env.PORT);
// Stormpath will let you know when it's ready to start authenticating users.
app.on('stormpath.ready', function () {
console.log('Your server is running on port ' + port + '.');
});
app/routes.js
// Import dependencies
const express = require('express');
const stormpath = require('express-stormpath');
// Export the routes for our app to use
module.exports = function(app) {
// Create API group routes
const apiRoutes = express.Router();
// User management: get users, invite users, view user profile
var UsersRoute = require('./routes/users');
apiRoutes.get('/memberinfo', stormpath.loginRequired, UsersRoute.memberInfo);
// Set url for API group routes
app.use('/', apiRoutes);
};
app/routes/users.js
// Protected route test
module.exports.memberInfo = function(req, res){
//how do i access the "app" here?
res.status(200).send({ user: req.user });
}
In your .memberInfo method, you can use req.app to access the app object that is associated with that request.
In cases where you aren't passed a req object that you can use in this way, then you need to initialize the module by calling a method on it and passing it the app object and the module can then store the app object locally so it can use it when desired.

Categories

Resources