Can Firebase RemoteConfig be accessed from cloud functions - firebase

I'm using Firebase as a simple game-server and have some settings that are relevant for both client and backend and would like to keep them in RemoteConfig for consistency, but not sure if I can access it from my cloud functions in a simple way (I don't consider going through the REST interface a "simple" way)
As far as I can tell there is no mention of it in the docs, so I guess it's not possible, but does anyone know for sure?

firebaser here
There is a public REST API that allows you to read and set Firebase Remote Config conditions. This API requires that you have full administrative access to the Firebase project, so must only be used on a trusted environment (such as your development machine, a server you control or Cloud Functions).
There is no public API to get Firebase Remote Config settings from a client environment at the moment. Sorry I don't have better news.

This is probably only included in newer versions of firebase (8th or 9th and above if I'm not mistaken).
// We first need to import remoteConfig function.
import { remoteConfig } from firebase-admin
// Then in your cloud function we use it to fetch our remote config values.
const remoteConfigTemplate = await remoteConfig().getTemplate().catch(e => {
// Your error handling if fetching fails...
}
// Next it is just matter of extracting the values, which is kinda convoluted,
// let's say you want to extract `game_version` field from remote config:
const gameVersion = remoteConfigTemplate.parameters.game_version.defaultValue.value
So parameters are always followed by the name of the field that you defined in Firebase console's remote config, in this example game_version.
It's a mouthful (or typeful) but that's how you get it.
Also note that if value is stored as JSON string, you will need to parse it before usage, commonly: JSON.parse(gameVersion).
Similar process is outlined in Firebase docs.

Related

Is there a way to read environment variables inside override.ts with AWS Amplify Auth

I used to AWS Amplify Auth for a social login, recently.
and, for social provider setting, I'm trying to use amplify auth override.
docs is here: https://docs.amplify.aws/cli/auth/override/
for security reason, I don't want write the secrets inside override.ts like client id, client secrets, etc.
Is it possible to read environment variables in override.ts?
or any idea?
Amplify CLI retained the information in amplify/backend/amplify-meta.json such as project environment information and others resources information.
I used amplify-meta.json as a module.
There is a StackName with the value of amplify-[PROJECT_NAME]-[ENVIRONMENT_NAME]-[PROECT_NUMBER]. So we can get the environment name by deconstructing the string.
override.ts
export function override(resources: AmplifyAuthCognitoStackTemplate) {
const amplifyMetaJson = require('../../../amplify-meta.json');
const envName = amplifyMetaJson.providers.awscloudformation.StackName.split("-").slice(-2, -1).pop();
console.log("Environment for cloudformation => ", envName);
}
Note: This is the temporary solution of an evil way. It is better to fix the issue.
https://github.com/aws-amplify/amplify-cli/issues/9063

Is there a way to add new field to all of the documents in a firestore collection?

I have a collection that needs to be updated. There's a need to add new field and fill it out based on the existing field.
Let's say I have a collection called documents:
documents/{documentId}: {
existingField: ['foo', 'bar'],
myNewField ['foo', 'bar']
}
documents/{anotherDocumentId}: {
existingField: ['baz'],
myNewField ['baz']
}
// ... and so on
I already tried to fire up local cloud function from emulator that loops for each document and writes to production data based on the logic I need. The problem is that function can only live up to max of 30 seconds. What I need would be some kind of console tool that I can run as admin (using service-account) to quickly manage my needs.
How do you handle such cases?
Firebase does not provide a console or tool to do migrations.
You can write a program to run on your development machine that uses the one of the backend SDKs (like the Firebase Admin SDK) to query, iterate, and update the documents and let it run as long as you want.
There is nothing specific built into the API for this type of data migration. You'll have to update each document in turn, which typically involves also reading all documents (or at least their IDs).
While it is possible to do this on Cloud Functions, I find it easier to do it with a local Node.js script, as that doesn't have the runtime limits Cloud Functions imposes.

Firebase Admin SDK Not Reading, Writing, or Throwing Errors (Node.js)

This question was previously closed, telling me to "update the question so it focuses on one problem only;" I don't know what the problem is, and if I did, I wouldn't be posting this question. Regardless, I'll make some clarifications here:
I was previously using just the normal Firebase module (the one imported using "npm i firebase"); everything worked perfectly before. The issue has to do with the authentication (as far as I am aware) with the Firebase Admin SDK. I don't understand how I'm supposed to send this to the Heroku build without revealing the service account key JSON file on my GitHub.
As for the GOOGLE_APPLICATION_CREDENTIALS path, is there a way where I don't have to set it every session? The Heroku app restarts once a day, and I would need to somehow automate this entry process (or skip it entirely). That's the way I currently understand it. Here's a quote from a previous answer:
When I set the GOOGLE_APPLICATION_CREDENTIALS path, doesn't this only set it on my local machine?
Environment variables only work on the individual machine and process where they have been set. If you want it set on another machine and process, you will have to arrange for that separately. According to the documentation:
Set the environment variable GOOGLE_APPLICATION_CREDENTIALS to the file path of the JSON file that contains your service account key. This variable only applies to your current shell session, so if you open a new session, set the variable again.
My main question here is as follows: "I implemented the Firebase Admin SDK incorrectly. How do I do it the right way?"
Even just posting a link to guides that would help would be appreciated (although I understand this is typically discouraged as links sometimes break).
Original:
Note: this is my first time using the Firebase Admin SDK, so I'm really not sure what I'm doing (although I have used Firebase quite a bit).
Recently, I decided I would go back to one of my older Discord bots and actually authenticate its requests to Firebase properly (I hadn't done this previously as I've never authenticated from a server before and didn't think it was possible). I discovered the Firebase Admin SDK, which sounded perfect for my needs (the bot is being hosted on Heroku, for the record).
I found this guide: https://firebase.google.com/docs/admin/setup, but there's a few things I can't wrap my head around (note that these are purely rhetorical, you don't need to answer them in your answer; I'm just providing them so you can understand my thought process):
When I set the GOOGLE_APPLICATION_CREDENTIALS path, doesn't this only set it on my local machine? I could also try running the export command on the server (using "heroku run" in the CLI), but then the path would be pointing to a file that doesn't exist on the server (since the service account key JSON file is on my local machine). Do I need to set an environment variable in Heroku or something?
How does "admin.credential.applicationDefault()" know how to get the credentials?
I can't find any other guides that make sense.
The way I currently have it setup must be wrong, since reads and writes fail silently.
Firebase setup code:
// Setup Firebase:
const admin = require('firebase-admin');
// Initialize Firebase:
admin.initializeApp({
credential: admin.credential.applicationDefault(),
databaseURL: "https://<APP>.firebaseio.com" // I removed the actual <APP> name to ask this question
});
let database = admin.database();
Things like database.ref("test").set("Hello World!"); don't change the data in the database, and no errors are thrown (I've also tried attaching a .then and a .catch to the end of this; still nothing). This was working before I switched over to the Firebase Admin SDK (I was just using the "firebase" module previously, rather than the "firebase-admin" module that I'm now using). The same goes for reading data.
Any help would be appreciated.
Here was my problem:
I was sending res.status(200) outside of the async firebase call, killing the request before firebase had a chance to finish. Somehow localhost allows this to work properly but when its hosted things go sideways.
so I had this
fireabse.database().ref('parent/foo').set('bar');
res.status(200)
I needed this:
firebase.database().ref('parent/foo').set('bar').then(() => {
res.status(200);
});

Firebase - Firestore - create a function to verify if a user exists in Auth

I want to verify if a user exists in the Authentication list of users in firebase. I know I can use:
admin.auth().getUserByEmail(email)
admin.auth().getUser(uid)
I am building a react native app, so I can't install firebase-admin since it would require I ship credentials in the app, which is too dangerous, since someone can do reverse engineering and find them.
I have found I can write functions, so I have created a separate project to create and deploy functions, this will work as a backend.
Now I want to create a function there that uses firebase-admin and to be able to use the 2 methods listed above.
I found I can create:
exports.addMessage = functions.https.onCall((data, context) => {
// ...
});
and call it like:
var addMessage = firebase.functions().httpsCallable('addMessage');
addMessage({text: messageText}).then(function(result) {
// Read result of the Cloud Function.
});
Not sure if using https.onCall is the best for this case or is there a better way.
Thanks in advance.
As far as the documentation indicates - accessible here - and the fact that the https.onCall() uses a safe method to be called (HTTPS) I believe that this is the best option for your case, since installing firebase-admin doesn't fit your case.
The official documentation Protocol specification for https.onCall also says:
If you are able to use the Android, iOS, or web SDKs, you're recommended to do that instead of directly implementing this protocol. The SDKs provide features to save coding time and effort, as detailed in Call Functions from Your App
So, this is indicated, in case you don't want/can use the SDK, which I believe it's what you are saying. Considering that, I believe that the https.onCall() it's the option for your situation.
Let me know if the information helped you!

How to generate DownloadUrl from Google-Cloud storage (I came from firebase)

Just trying to figure out something that seemed trivial in firebase, in google-cloud.
It seems as though if you're making a node.js app for HTML (i'm talking to it through Unity actually, but it's a desktop application) you can't use firebase-storage for some odd reason, you have to use google-cloud, even the firebase-admin tools use the cloud storage to do storage from here.
Nevertheless, i got it working, i am uploading the files to the firebase storage; however, the problem is in firebase, you could specify a specific file, and then do storage().ref().child(filelocation).GetDownloadURL(): this would generate a unique url for some set time that can be used publicly, without having to give out access to read to all anonymous users.
I did some research and i need to implement something called GS UTIL in order to generate my own special urls, but it's so damn complicated (im a newbie to this whole server stuff), i don't even know where to start to get this working in my node server.
Any pointers? I'm really stuck here.
-------if anyones interested, this is what im trying to do high level-----
I'm sending 3d model data to node app from Unity
the node app is publishing this model on sketchfab
then it puts the model data onto my own storage, along with some additional data specially made for my app
after it gets signed to storage, it gets saved to my Firebase DB in my global model database
to be accessed later, by users, to try to get the downloadURL of this storage file and send them all back to Unity users(s)
I would just download the files into my node app, but i wanna reduce any server load, it's supposed to be just a middleman between Unity and Firebase
(i would've done it straight from Unity, but apparently firebase isn't for desktop windows apps).
Figured it out:
var firebase_admin = require("firebase-admin");
var storage = firebase_admin.storage();
var bucket = storage.bucket();
bucket.file(childSnapshot.val().modelLink).getSignedUrl({
action: 'read',
expires: expDate
},function(err,url){
if(err){
reject(err);
}
else{
finalData.ModelDownloadLink = url;
console.log("Download model DL url: " + url);
resolve();
}
});

Resources