Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 17 additions & 10 deletions Node-1st-gen/url-shortener/functions/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,26 +16,33 @@
'use strict';

const functions = require('firebase-functions/v1');
const {onInit} = require('firebase-functions/v1/init');
const {defineSecret} = require('firebase-functions/params');
const { BitlyClient } = require('bitly');
// TODO: Make sure to set the `BITLY_ACCESS_TOKEN` secret using the CLI.
const bitlyAccessToken = defineSecret('BITLY_ACCESS_TOKEN');

let bitly;
onInit(() => {
bitly = new BitlyClient(bitlyAccessToken.value());
});
async function shortenBitly(url, token) {
const res = await fetch('https://api-ssl.bitly.com/v4/shorten', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ long_url: url })
});
if (!res.ok) {
throw new Error(`Bitly API failed: ${res.status} ${await res.text()}`);
}
const data = await res.json();
return data.link;
}

// Shorten URL written to /links/{linkID}.
exports.shortenUrl = functions.runWith({secrets: [bitlyAccessToken]}).database.ref('/links/{linkID}').onCreate(async (snap) => {
const originalUrl = snap.val();
const response = await bitly.shorten(originalUrl);
// @ts-ignore
const shortUrl = response.url;
const shortUrl = await shortenBitly(originalUrl, bitlyAccessToken.value());
Comment on lines 41 to +42

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The database trigger onCreate fires whenever any data is created at /links/{linkID}. Since Firebase Realtime Database is schemaless, a client or administrator could write a non-string value (such as an object or a number) to this path. If originalUrl is not a string, passing it to shortenBitly will result in an invalid API request and cause the function to fail. Adding a type check ensures the function handles unexpected data structures gracefully.

  const originalUrl = snap.val();
  if (typeof originalUrl !== 'string') {
    functions.logger.error('Expected a string URL, but received:', originalUrl);
    return null;
  }
  const shortUrl = await shortenBitly(originalUrl, bitlyAccessToken.value());


return snap.ref.set({
original: originalUrl,
short: shortUrl,
})
});
});
Loading
Loading