Can't find my Function URL on deploying webhook on Firebase - firebase

Screenshot attached when I entered "Firebase deploy" command
I was trying to execute this set on instructions while deploying webhook using Google Cloud Functions for Firebase and the static resources needed by the project using Firebase Hosting:
Run firebase init, and select to configure Hosting and Functions. Select the project. In the configuration wizard, accept all the default choices.
Generate a private key using Firebase Settings/Service Accounts, and edit functions/database.js with the path to the JSON cert file. Now populate the database: node database.js
Run firebase deploy and take note of the endpoint where the fulfillment webhook has been published. It should look like Function URL (yourGame): https://us-central1-YOUR_PROJECT.cloudfunctions.net/yourGame. The command will also deploy the static assets at https://us-central1-YOUR_PROJECT.cloudfunctions.net/.
On running firebase deploy I can't find the "Function URL". It would just display "Hosting URL" and "Project Console".
A screenshot is attached upon running "firebase deploy" on CLI.
And also what does it mean by "Now populate the database: node database.js"?

Follow this Project Console URL.
You then should be in your project's dashboard, on the left side of the screen you gonna see a bunch of options, among them one called "Functions", click on it.
Your URL should be displayed there.

If you created a new Firebase project, then your index.js in your ./functions directory will look like this by default:
const functions = require('firebase-functions');
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
//exports.helloWorld = functions.https.onRequest((request, response) => {
// response.send("Hello World!");
//});
Make sure you uncomment the hellowWorld function. Then save your project. Then run firebase deploy. Then, the url will show up in your dashboard.

Related

What causes typescript compile error when deploying

I roughly following this tutorial to make a cloud function with typescript. It works fine in development, but when I try to deploy it (firebase deploy --only functions), I get A LOT of typescript errors. I have no idea why. It works in dev, why can't I push the same set up to Firebase?
Follow the below steps for a successful cloud functions deployment:
After you have created a Firebase project using this step, install
the Firebase CLI using : npm install -g firebase-tools.
Run firebase login to log in via the browser and authenticate the
firebase tool.
Run firebase init firestore
Run firebase init functions
When you run firebase init functions, there will be prompts, 1st
prompt : “What language would you like to use to write Cloud
Functions?” -> Choose Typescript. 2nd prompt : Do you want to use
ESlint to catch probable bugs and enforce style (y/n)? -> Choose n.
By selecting no you will be saving yourself from the typescript
compile errors.
Once initialization is complete, uncomment the sample in index.ts and
run npm run serve to see a "Hello World" function in action. Once you
can see the output in Firebase emulator, you will know the functions
executed properly.
Now, before you deploy the functions, assign the Cloud Functions
Invoker, Cloud Functions Admin and Cloud Functions Developer role to
project-id#appspot.gserviceaccount.com
Now run firebase deploy –only functions. The deployment will be
successful but the browser might show 403 errors ( Client does not
have permission..) For that, select your cloud function (check box)
click "Add members" under the Permissions tab in the right side,
enter "allUsers" under "New members", select Role as Cloud Functions -> Cloud Functions Invoker and then save the configuration.
If you do not want to give public access to your cloud functions, you
can set up authentication, by skipping the previous step. In Cloud
Shell, run gcloud auth print-identity-token. This outputs a token
which you will be authenticating your cloud function with. Now
provide authentication credentials in your request as a
Google-generated ID token stored in an Authorization header with this
command :
curl https://REGION-PROJECT_ID.cloudfunctions.net/FUNCTION_NAME \ -H "Authorization: bearer $(gcloud auth print-identity-token)"

How can I "admin.initializeApp();" no arguments in local

I am always grateful for your help.
I want to write code admin.initializeApp(); both locally and in production.
When I deploy functions to production with no auguments, it works.
But locally, it requires me to write it like below:
const serviceAccount = require("/home/yhirochick/development/ServiceAccountKey.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://xxxx.firebaseio.com/"
});
In the official documentation it says that configuration is applied automatically when you initialize the Firebase Admin SDK with no arguments
But when I execute the command firebase serve --only functions locally and some calls some requests by postman produce the error below:
[2019-07-22T06:45:26.227Z] #firebase/database: FIREBASE WARNING: Provided
authentication credentials for the app named "[DEFAULT]" are invalid. This
usually indicates your app was not initialized correctly. Make sure the
"credential" property provided to initializeApp() is authorized to access the
specified "databaseURL" and is from the correct project.
I want to know How can I "admin.initializeApp();" no arguments locally.
I have grappled with this also and I don't think the local testing scenario currently is explained very well in the official documentation. But here is a solution:
For your local environment you need to download the firebase projects firebase service account json file (found in firebase console under project settings -> service account) and set an environment variable GOOGLE_APPLICATION_CREDENTIALS to point to the file:
# Linux/MACOS version
export GOOGLE_APPLICATION_CREDENTIALS="[PATH_TO_YOUR_SERVICE_ACCOUNT_FILE]"
Read more here, also on how to do this on Windows
Now you will be able to use admin.initializeApp() (with no arguments) locally.
A possible downside of this approach is that you have to set the environment variable each time you fire up a terminal before you start the firebase emulator, because the variable gets deleted when you end the session.
Automate it...
You could automate the export ... command by bundling it together with the command that fires up the emulator. You could do this by adding an entry to the scripts section of your package.json, e.g.:
"local": "export GOOGLE_APPLICATION_CREDENTIALS='[PATH_TO_YOUR_SERVICE_ACCOUNT_FILE]' && firebase emulators:start --only functions"
Then, in this example, you would only need to type npm run local.
Alternative: provide explicit credentials in local environment only
Look at this example: https://stackoverflow.com/a/47517466/1269280.
It basically use a runtime node environment variable to separate between local and production and then use the explicit way of providing credentials in the local environment only.
This is my preferred way of doing things, as I think it is more portable. It allows me to put the service account file inside my codebase and not deal with its absolute file path.
If you do something like this then remember to to exclude the service account file from your repo! (it contains sensitive info).
Background: difference between production and local service account discovery
The reason that admin.initializeApp() (with no arguments) works out-of-the-box in production is that when you deploy to production, i.e. Firebase Functions, the code ends up in a 'Google managed environment'. In Google managed environments like Cloud Functions, Cloud Run, App Engine.. etc, the admin SDK has access to your applications default service account (the one you downloaded above) and will use that when no credentials are specified.
This is part of Google Clouds Application Default Credentials (ADC) strategy which also applies to firebase functions.
Now, your local environment is not a 'google managed environment' so it doesn't have access to the default service account credentials. To google cloud, your local box is just an external server trying to access your private Firebase ressources. So you need to provide your service account credentials in one of the ways described above.
Before I knew this, I thought that because I was already logged in to firebase via my terminal i.e. firebase login and were able to deploy code to firebase, the firebase emulator would also have the necessary credentials for the firebase admin sdk, but this is not the case.

firebase realtime database configuring with firebase functions

i want to configure firebase realtime databse, with my firebase cloud function.
1)what is "serviceAccountKey.json"?
2) How to get this file?
3) did one "serviceAccountKey.json" is enough for all the users using firebase functions?
suppose if i use below sample
"exports.dbCreate = functions.database.ref('/path').onCreate((event) => {
const createdData = event.data.val(); // data that was created
});"
how to call dbCreate and what path i have to give in "/path"?
how to get serviceAccountKey.json?
i am using the versions " "actions-on-google" :"^2.0.1",
"firebase-admin": "~5.12.0",
"firebase-functions": "^1.0.1",
"dialogflow": "^0.1.0",
"dialogflow-fulfillment": "^0.4.1","
Firebase Functions are server-side (cloud based) scripts that interact with your Firebase project. So, they need a key since they have full access to your project.
Your example functions.database.ref('/path').onCreate is not something you call, it is triggered.
Get started with
a service account to communicate with the Firebase service, and a
configuration file with your service account's credentials.
If you don't already have a Firebase project, add one in the Firebase console. The Add
project dialog also gives you the option to add Firebase to an
existing Google Cloud Platform project.
Navigate to the Service Accounts
tab in your project's settings page.
Click the Generate New Private Key button at the bottom of the Firebase Admin SDK section of the Service Accounts tab.

how to find my Google application credentials key.json

I try to run Firebase Functions locally by following the instruction here.
It mentioned these steps:
$ export GOOGLE_APPLICATION_CREDENTIALS="path/to/key.json"
$ firebase experimental:functions:shell
OR
$ firebase serve --only functions
How can I find my path/to/key.json?
Presumably you followed the instructions on the page you linked to:
To set up admin credentials for emulated functions (other than Cloud
Firestore and Realtime Database):
Open the Service Accounts pane of the Google Cloud Console.
Make sure that App Engine default service account is selected, and use the options menu at right to select Create key.
When prompted, select JSON for the key type, and click Create.
Set your Google default credentials to point to the downloaded key
Only you know the path of the JSON file you just downloaded from the console. Put the full path to that file there.

Firebase cloud function "Your client does not have permission to get URL /200 from this server"

I just made a firebase cloud function :
exports.deleteAfterSevenDays = functions.https.onRequest((req, res) => {...
I deployed the function and got a function URL. When I request this url from my browser I get the following message :
"Error: Forbidden Your client does not have permission to get URL /200
from this server."
I have just updated to firebase Blaze plan because I thought there were limitations with Spark plan, but it still doesn't work.
In my firebase cloud function logs it is written "Function execution took 572 ms, finished with status code: 302".
My cron job "has been disabled automatically because of too many failed executions".
Do you see what's wrong?
Cloud function should have a role with member called "All users" to invoke this function from anywhere/anyone irrespective of an authorization.
Without Authorization:
Go to the cloud function tab
Select your cloud function (check box)
Click "Add members" under Permissions tab in the right side
Enter "allUsers" under "New memebers"
Select Role as "Cloud Functions -> Cloud Functions Invoker"
Save
Test your cloud function by just pasting it in the browser
With Authorization:
It's always a good practice to set authorization on your cloud functions
Note: Cloud functions throwing error with "403 Forbidden - Your client does not have permission to get URL" should be called by authorized users.
Simple test:
Click on Cloud shell(icon) terminal in the top
type - gcloud auth print-identity-token
copy the generated token
forming Authorization key to be passed while calling cloud function
4.1 Authorization: bearer generated_token
Use above Authorization key while calling your cloud function
Note:
Never make a cloud function available to allUsers
From Cloud Function docs:
Caution: New HTTP and HTTP callable functions deployed with any
Firebase CLI lower than version 7.7.0 are private by default and throw
HTTP 403 errors when invoked. Either explicitly make these functions
public, or update your Firebase CLI before you deploy any new
functions.
In my case the CLI version was out of date. If you currently get the 403 error, try this:
Delete your Cloud Functions
Update Firebase CLI npm install -g firebase-tools
Re-deploy your functions
To be clear:
Go to your function (make sure your project is selected):
https://console.cloud.google.com/functions/details/us-central1/ssr
Click Permissions Tab
Click Add Permissions
New Principals: allUsers
Role: Cloud Functions Invoker
Done.
J
Changing the IAM role(Cloud Functions Invoker) for targeted cloud function to allUsers should solve this issue. https://console.cloud.google.com/functions
If you face this in 2020 it might also be due to a different access behaviour:
Note: As of January 15, 2020, HTTP functions require authentication by
default. You can specify whether a function allows unauthenticated
invocation at or after deployment.
https://cloud.google.com/functions/docs/securing/managing-access-iam#allowing_unauthenticated_function_invocation
Here are the steps
Go the Google Cloud Console(Not Firebase Console) -> Search For Cloud Functions to see the list of functions
Click the checkbox next to the function to which you want to grant
access.
Click Permissions at the top of the screen. The Permissions panel
opens.
Click Add principal.
In the New principals field, type allUsers.
Select the role Cloud Functions > Cloud Functions Invoker from the
Select a role drop-down menu.
Click Save.
Enable access from Postman project:
Open https://console.cloud.google.com/functions
Open cloud shell (right top terminal icon)
Write: gcloud auth print-identity-token
Copy your token and open your Posman
Right click on your collection -> Edit
Authorization -> Choose type OAuth 2.0
Paste your token in the Access Token
Note: You can do the same for a single request or folder.
This might be far fetched but if you have interrupted a cloud function deployment, then redeployed the function (which lead to an error), and after that you redeployed the function successfully this could have caused the issue.
I am trying to reproduce, but simple deleting the function in the firebase console and redeploying worked for me.
it happens to me after i upgraded all NPM packages and then deployed...
i delete all the functions from the cloude and re-deplyed them. it solve me this error immediately. without change permisions or any other cahnge
I know this doesn't make sense, or not a real solution but I solved it by making my account an Owner of the Firebase project. It was working nice while I was Editor but stopped working suddenly and setting my account as Owner solved it for now.
I guess it has to do with certain account having proper access to the Service Account which is the actual interface with Firebase Functions and Google Cloud API.
In my case, I made error in Postman
when I typed Body of Request, I didn't switched format from Text to JSON.
Check that part.

Resources