Search code examples
firebasecrongoogle-cloud-functionshttp-authentication

Firebase CronJobs - how to allow http triggers from one cronjob site


Since Firebase (Real-time DB) does not support cron-jobs I am using cron-job.org to schedule http triggers. This function should fire once at the end of every day, so at around 11:55pm. The thing is I would like only cron-job.org to be able to trigger the http endpoint and no one else (e.g. someone malicious trying to trigger it many times a day). How can I achieve this in my cloud function?

I have setup the cronjob and this is all the code I have right now:

exports.findAndDeleteSevenDayJobs = functions.https.onRequest((req, res) => {
  console.log('req',req);
});

Also, cron-job.org offers this:

enter image description here

And I have no idea how to use it.


Solution

  • To create cron-jobs in firebase RDB use a third party service like cron-job.org

    1) CREATING THE KEY

    To make everything secure you have to generate a secure key, from now on called YourSelfGeneratedButSecureKey.

    You can generate one in your terminal by typing: node -e "console.log(require('crypto').randomBytes(20).toString('hex'))"

    2) CREATING CRON JOB

    Create a new cron-job that will hit your cloud function end-point and attach the created key as a url-query like so:

    https://{projectSpecific}.cloudfunctions.net/{nameOfFunction}?key={YourSelfGeneratedButSecureKey}

    Setup the key into your env by using the following command in your terminal: firebase functions:config:set cron.key="{YourSelfGeneratedButSecureKey}"

    3) CLOUD FUNCTION

    To make sure everything is maximum security you can install secure-compare by typing npm install --save secure-compare;

    Then in your cloud function:

    const secureCompare = require('secure-compare');
    
    exports.{nameOfFunction} = functions.https.onRequest((req, res) => {
    
      const { key } = req.query;
    
      if (!secureCompare(key, functions.config().cron.key)) {
        console.log('Key in request and in env do NOT match');
        res.status(403).send('Security key does not match.');
        return null;
      }
      
      // DO REPETITIVE STUFF SECURELY 
    
    });