google function: accessing firestore database of another project - javascript

I would like a Google Cloud project A (project-a-id) to access the firestore data of another Google Cloud project B (project-b-id). For the same I added project A default service account viz. project-a-id#appspot.gserviceaccount.com in the IAM of project B and set the role to Cloud Filestore Editor.
In the cloud function of project A, I am trying to access both project A's (its own) firestore as well as project B's firestore but it keeps showing project A default database for both Apps. The code is:
var primaryAppConfig = {
databaseURL: 'https://project-a-id.firebaseio.com'
};
var primaryApp = admin.initializeApp(primaryAppConfig, 'primary');
var primarydb = admin.firestore(primaryApp);
var secondaryAppConfig = {
databaseURL: 'https://project-b-id.firebaseio.com'
};
var secondaryApp = admin.initializeApp(secondaryAppConfig, 'secondary');
var secondarydb = admin.firestore(secondaryApp);
I was under the impression if the default service account of project-a is given rights in project-b it should automatically get rights. At least I found it applicable when I am accessing google cloud storage buckets in this manner.
Is something else to be done? Thanks

I have a cloud-native firestore as opposed to a real-time database in project-a. However, was facing the same issue when I tried to access it from project-b.
Was able to solve it by generating a service account with access to project-a firestore, downloading the credentials and accessing the same from project-b with the following:
credential_path = "pathTo/xxxxx.json"
db = firestore.Client.from_service_account_json(credential_path)

You need to create apps within current firebase project.
Firebase Console -> Project Setting -> General -> Add App
These apps will have access to same firestore but will be deployed seperately under different subdomains(under firebaseapp.com).

Related

How do I interact with the Firestore database through the firebase admin?

I can't find the answer to this in the documentation. I have created a firebase cloud function which listens to the database and gets triggered when a doc in the database changes.
What I want the function to do is to gather information from the database, other than the information listened to in the first place, and then work with that information. How would I gather information from the Firestore database using firebase admin?
Down below is the code I have written so far:
exports.costCalculation = functions.firestore
.document("questions/{docId}/post_publish_information/outcome_information")
.onUpdate((change, context) => {
const predictions = admin
.firestore()
.document("questions/{docId}/post_publish_information/predictions");
console.log(predictions);
});
The Admin SDK is already loaded and initialized, you just can't access it through the admin variable. If you don't feel like initializing an Admin SDK instance yourself, you can work from the document you get it from change.
For example, to get a reference to the predictions document you can also:
change.before.ref.parent.doc("predictions")

Firebase app give error "Uncaught TypeError: firebase.store is not a function" although I imported firebase storage

I am new in firebase.I created app that connect to database and create new id in it.
const db = firebase.store();
my db variable is not reachable.
There is no product names store() in Firebase.
If you're looking for Firestore (for storing documents with fields and values), use firebase.firestore().
If you're looking for Cloud Storage for Firebase (so for storing unstructured files), use firebase.storage().

firebase realtime funtions using multiple databases

We have two different firebase projects each with its own firebase functions and realtime database used.
we have come to a situation where we want to leverage one of the dataset (a node in the realtime db) from project 1 into the project 2.
As this node is read-only true so i can a access it in the format
https://myproject.firebaseio.com/prj1db/nodeX.json
but that will give entire data for this node. What i need is to query specific data like i do using below format for the db attached to the same project in the firebase function:
const rsp = await db.ref("/users/").orderByChild("color").equalTo("pink).once("value")
is there a way?
So above answer did not work even being super close to what i need. The above response ends up giving error indicating there is a security issue.
What worked for me was that i used the service key approach with below code
const scanbuddyDBApp = admin.initializeApp({
credential: admin.credential.cert("./src/scanbuddy_service_key.json"),
databaseURL: "https://mydb.firebaseio.com",
}, 'scanbuddy');

How to prevent firebase db access from chrome console or other methods

So I have a single page frontend only app. Right now I have something like this
// db.js
import firebase from "firebase/app"
import "firebase/firestore";
var firebaseConfig = {
...
};
export const db = firebase
.initializeApp(firebaseConfig)
.firestore();
in main.js I was experimenting with putting the db instance in the global window scope just to see if I could go to the chrome web console and access it to submit a doc and indeed I can
// main.js
import { db } from './db'
window.db = db;
and then from chrome console
db.collection("test").add({'somekey': 'Can I add this doc?'})
How do I prevent someone from doing this without having a real backend to check auth? I like the reactivity of vue + firebase. If I don't expose the db variable to global scope is that enough? I was reading this post:
https://forum.vuejs.org/t/how-to-access-vue-from-chrome-console/3606/2
because any variable you create inside your main.js fiel will still not be globally available due to how webpack
One of the great things about Firestore is that you can access it directly from within your web page. That means that within that web page, you must have all configuration data to find the relevant Google servers, and find your Firebase project on those servers. In your example, that data is part of firebaseConfig.
Since you app needs this configuration, any malicious user can also get this data from your app. There is no way to hide this: if you app needs, a sufficiently motivated malicious user will be able to find it. And once someone has the configuration, they can use it to access your database.
The way to control access to the database, is by using Firebase's server-side security rules. Since these are enforced on the server, there is no way to bypass them, neither by your code, nor by the code that a malicious user writes.
You can use these security rules to ensure that all data is valid, for example making sure that all the required fields are there, and that there's no data that your app doesn't use.
But the common approach is to also ensure that all data access is authorized. This requires that your users are authenticated with Firebase Authentication. You can either require your users to sign in with their credentials, or you can anonymously sign them in. In the latter case they don't need to enter any credentials, but you can still ensure for example that each user can only write data to their own area of the data, and that they can only read their own data.

Firebase, two projects same DB?

Let me explain the situation (excuse my english, I will do my best):
I have two Firebase Web projects in my Firebase console: coretechtest-ce207 and agon-plugin
coretechtest-ce207 is the main app and agon-plugin is a secondary app wich needs to connect to the auth and database of coretechtest-ce207. As far as I know I can't host two apps on the same project so thats why I made to separated projects. The main one works fine, I can do everything I want (signup, database, etc.) but I need the main and the second one both on the same auth and DB. agon-plugin (secondary one) is made based on the FriendlyChat app and connects directly to the server in wich the app is hosted.
For example:
// Initializes FriendlyChat.
function FriendlyChat() {
this.initFirebase();
}
// Sets up shortcuts to Firebase features and initiate firebase auth.
FriendlyChat.prototype.initFirebase = async function() {
// Shortcuts to Firebase SDK features.
this.auth = firebase.auth();
this.database = firebase.database();
this.storage = firebase.storage();
// Initiates Firebase auth and listen to auth state changes.
await this.auth.onAuthStateChanged(this.onAuthStateChanged.bind(this));
};
As you can see there is no need to put
apiKey: "AIzaSyAfGm_ILVdfsd--Fw7aascc8tAB73q__Bbko",
authDomain: "coretechtest-ce207.firebaseapp.com",
databaseURL: "https://coretechtest-ce207.firebaseio.com",
projectId: "coretechtest-ce207",
storageBucket: "coretechtest-ce207.appspot.com",
messagingSenderId: "994718782"
I tryied replacing it using those parameters so it would be
FriendlyChat.prototype.initFirebase = async function() {
// Shortcuts to Firebase SDK features.
this.auth = 'coretechtest-ce207.firebaseapp.com';
this.database = 'https://coretechtest-ce207.firebaseio.com';
this.storage = 'coretechtest-ce207.appspot.com';
// Initiates Firebase auth and listen to auth state changes.
await this.auth.onAuthStateChanged(this.onAuthStateChanged.bind(this));
};
But no luck there, can you tell me what I am doing wrong? I thought that replacing that would connect to my main project but it did not... =/
I hope you can understand what Im trying to say!
Thanks!
Not 100% sure about Web, but it should be similar to Android :
Going to your console panel
On top left click on the wheel next to "Project OverView"
In the pop-up click on Project Setting
In the settings page scroll down a little bit and you should see a blue "add app" (or something like that) button.
Then do everything you did on your first app to your second app
Most importantly, dont post your api key on the web !
If you're using Web and want to host 2 webapps that use the same database - you have a couple options.
Free: the only thing that associates a web app to your db is the api keys in the Firebase config used to initialize firebase in the web app. If 2 apps use those same settings then they can share the same db. If you are wanting to host both web apps with firebase for free - only 1 app can be hosted for free per project. However, you can easily create a 2nd new project and host your 2nd web app in that new project. But don't use the new web api settings from that new project inside your app. Instead use the same ones from your original project. 2 apps in 2 projects can use the same DB if they use the same API keys config. (only select firebase hosting when doing 'firebase init' from the cli for the 2nd app)
A paid option: is if you go to the Hosting page in your firebase console, and you scroll down to the bottom -you will see a card offering hosting more than 1 app in 1 project. It requires you to update to the pay-as-you-go blaze plan. Which may or may not cost you money.

Categories

Resources