PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label google-cloud-functions. Show all posts
Showing posts with label google-cloud-functions. Show all posts

Tuesday, November 22, 2022

[FIXED] How to dispatch a Paypal IPN to a Google Cloud function?

 November 22, 2022     firebase-realtime-database, google-cloud-functions, paypal, paypal-ipn     No comments   

Issue

I've read here that it's possible to send an IPN directly to a Google cloud function. I have my Google Cloud functions running on Firebase on an index.js file.

I've set up my Paypal buttons to send the IPN to a page on my webapp.

Here is an example of one of the functions I'm running off Google Cloud Functions/Firebase:

// UPDATE ROOMS INS/OUTS
exports.updateRoomIns = functions.database.ref('/doors/{MACaddress}').onWrite((change, context) => {
    const beforeData = change.before.val(); 
    const afterData = change.after.val(); 
    const roomPushKey = afterData.inRoom; 
    const insbefore = beforeData.ins; 
    const insafter = afterData.ins; 
    if ((insbefore === null || insbefore === undefined) && (insafter === null || insafter === undefined) || insbefore === insafter) {
        return 0;
    } else {
        const updates = {};
        Object.keys(insafter).forEach(key => {
            updates['/rooms/' + roomPushKey + '/ins/' + key] = true;
        });
        return admin.database().ref().update(updates); // do the update} 
    }   
    return 0;
});

Now question:

1) I want to add another function to process IPN from Paypal as soon as I have a transaction. How would I go about this?

I'll mark the answer as correct if solves this first question.

2) how would that Google cloud function even look like?

I'll create another question if you can solve this one.

Note I am using Firebase (no other databases nor PHP).


Solution

IPN is simply a server that tries to reach a given endpoint.

First, you have to make sure that your firebase plan supports 3rd party requests (it's unavailable in the free plan).

After that, you need to make an http endpoint, like so:

exports.ipn = functions.http.onRequest((req, res) => {
    // req and res are instances of req and res of Express.js
    // You can validate the request and update your database accordingly.
});

It will be available in https://www.YOUR-FIREBASE-DOMAIN.com/ipn



Answered By - Eliya Cohen
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, November 5, 2022

[FIXED] How to change a environmental variable (functions.config()) of a firebase function, without redeploying the function from the cli

 November 05, 2022     environment-variables, firebase, google-cloud-functions, google-cloud-platform, javascript     No comments   

Issue

I'm trying to use a functions.config() variable of the firebase functions environment, to be able to switch logs on/off depending on, whether this variable is set to true/false. I have already created it, but it seems based on info from the following link (https://firebase.google.com/docs/functions/config-env#additional_environment_commands), that you can change it only if you redeploy the function, after you have used the firebase functions:config:set command to change the environmental variable first.

It appears that it could be achieved though, by using gcloud functions commands for deploying the function (gcloud deploy and not firebase deploy), with the --set-env-vars command (and different syntax to access the env. variable). Then this environmental variable can be changed easily by just changing value of the variable by navigating to the specific function at GCP console, and then by going to EDIT -> MORE and changing Environment variables at the bottom. source:
https://cloud.google.com/functions/docs/env-var

So my question is the following: Is there a similar way to change a firebase functions.config() variable without redeploying the function from the cli?


Solution

Update: (credit to Doug Stevenson) Apparantly the only way to change the environment variable is to do a deploy.

Original answer: You can do it the same way. Basically every Firebase Cloud Function is a Google Cloud Function and can be accessed the same way from the GCP console. Every Firebase Cloud Function is also present in the GCP console, and there you can easily just edit the environment variables just as you described in your question)



Answered By - Andrii Rudavko
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, November 3, 2022

[FIXED] Why am I getting 'no dialogflow intent detected' on Lambda but it works fine on Google Cloud Functions?

 November 03, 2022     dialogflow-es, google-cloud-functions, lambda, node.js     No comments   

Issue

I am building a Dialogflow agent and am migrating the fulfilment code from Google Cloud Functions over to AWS Lambda. Here is the entry code:

    'use strict';

/* CONSTANTS AND GLOBAL VARIABLES */

const functions = require('firebase-functions');
const { dialogflow } = require('actions-on-google');

const app = dialogflow({ debug: true });
const intents = require('./intentsController.js');

app.middleware(conv => {
    conv.hasScreen =
        conv.surface.capabilities.has('actions.capability.SCREEN_OUTPUT');
    conv.hasAudioPlayback =
        conv.surface.capabilities.has('actions.capability.AUDIO_OUTPUT');
});

app.intent('Welcome Intent', intents.welcomeIntent)

/* INTENT HANDLERS */

app.intent('Default Fallback Intent', intents.fallBackIntent);

app.intent('Find Multiple Posts Intent', intents.multiplePostsIntent);

exports.testFunction = functions.https.onRequest(app);

When viewing the cloudwatch logs from Lambda, Im getting this error:

"errorType": "Runtime.UnhandledPromiseRejection", "errorMessage": "Error: No intent was provided and fallback handler is not defined.",

When viewing the requests on AWS vs Google Cloud, AWS looks like its keeping the JSON in the request body as a string. Why would this work differently on Lambda and what am I doing wrong here?


Solution

It turns out that I was using the wrong API Gateway type. I was creating an http API when I should have used a REST API. Switching over to REST fixed the issue.



Answered By - Adam B
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, October 20, 2022

[FIXED] how to find from which application user authenticated in firebase authentication

 October 20, 2022     firebase, firebase-authentication, google-cloud-functions, node.js     No comments   

Issue

I am working on this project which has

  1. franchise --> website --> jsr_franchise.com
  2. customer --> website --> jsr_customer.com

I am using phone authentication Only. both use same authentication to login

how do i distinguish wherther user logged in from customer franchise website? When I use firebase function

exports.new_User_Added = functions.auth.user()
    .onCreate(async (user) => {
        database.ref(`/accountCreation/${user.uid}/phoneNumber/`).set(user.phoneNumber)
        database.ref(`/accountCreation/${user.uid}/TIMESTAMP/`).set(admin.database.ServerValue.TIMESTAMP)
        return Promise.resolve()
    })

I am able to get phone number and time stamp. But how do I determine? Whether your user used Customer website or franchise website to authenticate.


Solution

With Firebase Authentication a user doesn't log in to a specific site, but they log in to the entire Firebase project. No information about what site triggered that log-in is passed to Cloud Functions.

The most common workaround I know of is to pass all the information that is needed to create the user into a callable Cloud Function or HTTP Cloud Function, create the account there, set a custom claim on their profile with the extra information you want to maintain, and only then sign the user in on the client.



Answered By - Frank van Puffelen
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, September 26, 2022

[FIXED] How do I deploy Cloud Functions while ignoring existing functions?

 September 26, 2022     continuous-deployment, firebase, google-cloud-functions     No comments   

Issue

Say I have the following four functions in my Firebase projects:

openDoor(europe-west1)
closeDoor(europe-west1)
openWindow(europe-west1)
closeWindow(europe-west1)

Now, these functions live in two separate Node packages, i.e. one that contains openDoor and closeDoor and another one that contains openWindow and closeWindow.

Error

If I try to run firebase deploy from the package with the door functions, the following error will be thrown (in non-interactive mode):

Error: The following functions are found in your project but do not exist in your local source code:
    openWindow(europe-west1)
    closeWindow(europe-west1)

This is a problem because it will cancel any CD workflow that tries to deploy these functions.

Force delete

There is an option to force-delete any existing functions:

  -f, --force              delete Cloud Functions missing from the current 
                           working directory without confirmation

However, I want the opposite. I want to keep all existing functions.

Theoretical workaround

There is one workaround that I found would work in theory, which is:

yes N | firebase deploy --interactive

Piping N into the interactive deploy command, which will answer N to the deletion prompt:

The following functions are found in your project but do not exist in your local source code:
    openWindow(europe-west1)
    closeWindow(europe-west1)

If you are renaming a function or changing its region, it is recommended that you create the new function first before deleting the old one to prevent event loss. For more info, visit https://firebase.google.com/docs/functions/manage-functions#modify

? Would you like to proceed with deletion? Selecting no will continue the rest of the deployments. (y/N)

The problem now is that I am using https://github.com/w9jds/firebase-action to deploy the functions, which means that I need to have a built-in Firebase solution.


Solution

You can make use of the new codebases feature in Firebase.

By specifying a codebase in your firebase.json functions configuration, this problem is solved. The Firebase CLI will no longer prompt you to delete other functions as it only considers the functions of the same codebase.

If your firebase.json previously looked like this:

{
  "functions": {
    "source": "cloud_functions",
    "ignore": [...],
    "predeploy": [...],
    "postdeploy": [...]
  }
}

You only need to add "codebase": "<name>" to the config:

{
  "functions": {
    "source": "cloud_functions",
    "codebase": "window",
    "ignore": [...],
    "predeploy": [...],
    "postdeploy": [...]
  }
}

The deploy will now look like this:

i  functions: updating Node.js 16 function window:openWindow(europe-west1)...
i  functions: updating Node.js 16 function window:closeWindow(europe-west1)...

Note that the actual function name does not change, i.e. the function will still only be called openWindow (without the prefix) in the Firebase / Google Cloud Console. So this is basically the perfect solution to the problem.



Answered By - creativecreatorormaybenot
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, September 4, 2022

[FIXED] How can I store a bearer token and it's expiration date using Firebase cloud functions?

 September 04, 2022     authentication, firebase, google-cloud-functions, spotify     No comments   

Issue

I am writing an app using Firebase and the Spotify API.

I want my app to use the search endpoint of the Spotify API. The endpoint needs an OAuth token. I am using the Spotify Client credentials authorization to get the bearer token for my app.

I want to let the user call a cloud function via a HTTP request, with the parameters being the name of the song he's searching. The cloud function should be handling all the spotify OAuth stuff and the request to the endpoint. The cloud function should request a new bearer token every hour for the connection between my app and the API to be live. (I will use a CRON job for this).

How should I store the bearer token and its expiration date using cloud functions? I thought about saving them in a Firestore document, but I realized that would mean more document reads and writes just for the usage of the search function of the API.

What should I do in this situation? Where is the place to store such information that expires every hour within a firebase app using cloud functions?


Solution

Did you consider storing the token in a temp file on disk?

While Cloud Functions don't have permanent storage, they do have a writeable temp drive that might fit your needs. While the instance that runs your Cloud Functions (and thus that contains your temp files) could be wiped at any time, it sounds like you could then just reauthenticate with the API when a new instance is spun up and cache that in a temp file again.



Answered By - Frank van Puffelen
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, August 21, 2022

[FIXED] How to avoid plain text environment variables in a Google Cloud Function and instead pass them secretly?

 August 21, 2022     environment-variables, google-cloud-functions, parameter-passing, security     No comments   

Issue

Up to now I added plain text environment variables in the first step of creating the Cloud Function, and in the second step I called for examples the db connection URL variables including the sensitive credentials with:

def my_cloud_function(request):
    from os import environ
    
    ...
    db_user = environ["DB_USER"]
    db_pass = environ["DB_PASS"]
    db_name = environ["DB_NAME"]
    db_host = environ["DB_HOST"]
    db_port = environ["DB_PORT"]
    ...

(or use os.getenv() instead of os.environ()).

But I do not want to expose these sensitive connection parameters in this variables menu, available to anyone with the rights who clicked on the "Variables" tab. It is awkward if I can click on the variables and see the login credentials of a colleague. But also the other parts of the db URL should just better be kept secret.

How can I use environment variables without exposing them to anyone, at best from an unreadable encrypted file that I can also push to git?

There are a couple of Q&A on Stack Overflow that go into this direction, but I could not find the answer:

  • How can i pass variable to a google cloud function
  • Setting environment variables in Google Cloud Platform using Cloud Functions
  • Using Google Cloud Secret as environment variables in Google Cloud Build
  • and some more.

I guess that this will need secrets, but how would that be done, where would they be stored? Or are there other ways like using the json that is passed as the request parameter?


Solution

The recommended way to manage secrets in Cloud Function is mounting the secrets from Secret Manager. This documentation explains very well how to set it up: https://cloud.google.com/functions/docs/configuring/secrets

In a nutshell:

  1. Create your secrets under Secret Manager;

enter image description here

  1. Edit your Cloud Function -> Advanced Options -> Security;
  2. Map the secrets you would like to be available during runtime;
  3. Grant the role roles/secretmanager.secretAccessor to the service account binded to the Cloud Function;
  4. Once done, you can use the secrets as environment variable (like you are used to and mentioned in your description);

enter image description here



Answered By - CaioT
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, August 5, 2022

[FIXED] How do I know who changed my Cloud Function

 August 05, 2022     firebase, google-cloud-functions, google-cloud-platform     No comments   

Issue

Yesterday, on a beautiful Saturday, I was resting. When suddenly the phone rings and the "system has stopped working". When I observed the "cloud functions" one of them had an upload that I did not do, probably another member of the team. After all, I was resting!

Now, my manager wants the deployment history for all functions. How to know and where to get this information?

Entering the "cloud function" I can even see that there was the deploy, but it does not say "which user did it".


Solution

There are audit logs kept for all user actions. You can determine who updated the function by:

  1. Go to Logging > Logs Explorer

  2. In the Query Builder text box, add the following search term:

protoPayload.methodName="google.cloud.functions.v1.CloudFunctionsService.UpdateFunction"

  1. Click the Run Query button and then filter down by the date and time of when it was deployed and you'll see the user's email in the principal_email property.


Answered By - Brian Burton
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How do I call a callable v2 Cloud Function in Flutter?

 August 05, 2022     firebase, flutter, google-cloud-functions     No comments   

Issue

I have a Flutter app that uses cloud functions. I upgraded one function to a v2 function and it no longer works. The function cannot be found. The function logs do not show that it is being called. It is in the us-central1 region, as is the rest of the project.

final result = await FirebaseFunctions.instance.httpsCallable('addMessage').call();

Instead of addMessage I have tried the full function URL found in the firebase console, but that does not work either.

Function declaration:

exports.addMessage = onCall(async (request) => {
  //Run function
});

How do I call a v2 cloud function in flutter?


Solution

Conclusion: as of now you cannot call a v2 cloud function using the flutter cloud_functions package. You must use a regular http request to the full function URL (the cloud_functions package does not support using full URLs). You can use the dart http package to do this, handling the request and response manually.



Answered By - user11015833
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, January 22, 2022

[FIXED] Php equivalent for gcloud auth print-identity-token

 January 22, 2022     gcloud, google-cloud-functions, google-cloud-platform, php     No comments   

Issue

My goal is to trigger a google cloud function through my php code. For that I need an identity token as the Bearer, but my server does not have gcloud installed on it. I have a working service-account and I created an object through the Google_Client ("google/apiclient": "2.10.1"):

$this->setAuthConfig($serviceJson);
$scope = [Google_Service_Compute::CLOUD_PLATFORM, 'openid', 'email'];
$this->addScope($scope);
if ($this->isAccessTokenExpired()) {
  $this->fetchAccessTokenWithAssertion();
}
$this->getAccessToken()

Using this client I can fetch only the access_token (which is unauthorized to trigger a cloud function) but the id_token is always empty.

How can I get the id_token? Is there a php library that can help or do I need to do a separate POST request(s) to get the id_token?


Solution

The only way I found is like this:

  1. Generate a JWT manually (from the data that is in the service account)
  2. send it to https://www.googleapis.com/oauth2/v4/token and receive a token
  3. use the token in the CF call


Answered By - George7a
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing