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.
Related
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
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.
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.
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();
//....
I want to use firebase as a database service to my server to which a android app would send requests to. I want the server to retrieve data rather than the android app because I want to do some processing before sending data back to client (app).
My node code (index.js) :
const express = require('express')
const app = express()
var port = process.env.PORT || 10000
firebase = require('./firebase') // I added this cuz I can't use <script> tag here
// Initialize Firebase
var config = {
apiKey: "AIzaSynotgonnatell2Q-kwk85XrCyNnc",
authDomain: "hnotgonnatell.firebaseapp.com",
databaseURL: "https://hnotgonnatell.firebaseio.com",
projectId: "notgonnatell",
storageBucket: "",
messagingSenderId: "699935506077"
};
firebase.initializeApp(config);
var database = firebase.database()
ref = database.ref("some_table")
data = {
name : "my name",
number : "2938019283"
}
app.get('/', function(req, res){
ref.push(data)
res.send("hello")
})
app.listen(port)
I cannot use <script src="https://www.gstatic.com/firebasejs/4.12.1/firebase.js"></script> cause I'm not connecting to firebase from client. So I instead copied the code from https://www.gstatic.com/firebasejs/4.12.1/firebase.js and imported it into my index.js using require() . When I run the index.js I get:
firebase.initializeApp(config);
^
TypeError: firebase.initializeApp is not a function
at Object.<anonymous> (E:\workspace_javascript\firebase_try\index.js:24:10)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:422:7)
at startup (bootstrap_node.js:143:9)
at bootstrap_node.js:537:3
It works well when I run it by returning a html with firebase code inside <script>
Install firebase from NPM
npm install --save firebase-admin
Initiallize firebase
var admin = require('firebase-admin');
var serviceAccount = require('path/to/serviceAccountKey.json');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: 'https://<DATABASE_NAME>.firebaseio.com'
});
src: https://firebase.google.com/docs/admin/setup
If you want to access Firebase products on a server, you should be using the Firebase Admin SDK, not the client SDK.