ShaneBonkowski / ShanesGames

Repository for all of the files needed for webdev on ShanesGames
MIT License
0 stars 0 forks source link

[URGENT] Store private info server-side after moving to a hosting site #158

Closed ShaneBonkowski closed 3 months ago

ShaneBonkowski commented 4 months ago

Relies on https://github.com/ShaneBonkowski/ShanesGames/issues/138 since I need to have a host site first.

ShaneBonkowski commented 4 months ago

How to do this:

step 00.) ONE TIME STEP, NEVER NEED TO DO THIS AGAIN WHEN MAKING FUTURE CLOUD FUNCTIONS. Set up project to use firebase functions from the CLI firebase init functions

step 0.) Store Google Analytics API key in Firestore database. Ensure that only authenticated users (including the Cloud Function) have access to this data.

step 1.) make a firebase cloud function to retrieve the api key from the database. CLoud functions can be written in the functions/index.js file (or other files if preferred).

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const express = require('express');
const cors = require('cors');

admin.initializeApp();
const firestore = admin.firestore();

const app = express();
app.use(cors());

// Cloud Function to retrieve Google Analytics API key
app.get('/getAnalyticsApiKey', async (req, res) => {
    try {
        // Retrieve the API key from Firestore
        const snapshot = await firestore.collection('config').doc('analytics').get();
        const apiKey = snapshot.data().apiKey;

        // Return the API key in the response
        res.status(200).send(apiKey);
    } catch (error) {
        console.error('Error retrieving API key:', error);
        res.status(500).send('Error retrieving API key');
    }
});

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

step 2.) Deploy the firebase cloud function to my firebase app from the CLI (TODO: make a README file explaining how to add new cloud functions and use them. Need documentation for adding new cloud functions and the general workflow which is similar to this. Honestly maybe these steps or similar can be in the README)

firebase deploy --only functions

step 3.) Create the JS function that will be used to get the API key and then use it for whatever I want!

async function getAnalyticsApiKey() {
    try {
        const response = await fetch('https://us-central1-your-project-id.cloudfunctions.net/getAnalyticsApiKey');
        if (response.ok) {
            const apiKey = await response.text();
            console.log('Google Analytics API Key:', apiKey);
        } else {
            console.error('Failed to fetch API key:', response.statusText);
        }
    } catch (error) {
        console.error('Error fetching API key:', error);
    }
}

// Call the function to get the API key
getAnalyticsApiKey();

Replace your-project-id with the actual Firebase project ID.

Final step:

ShaneBonkowski commented 4 months ago

TODO:

Automate pushing functions to firebase by running the push command only if the functions folder has changes when merging into main. Essentially add something similar to the following to the .yml file I use to push the website to firebase:

name: Deploy Firebase Functions

on:
  push:
    branches:
      - main

jobs:
  deploy:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout code
        uses: actions/checkout@v2

      - name: Install Firebase CLI
        run: npm install -g firebase-tools

      - name: Login to Firebase
        run: firebase login:ci --no-localhost --token ${{ secrets.FIREBASE_TOKEN }}

      - name: Check for changes in functions directory
        id: check_changes
        run: |
          if git diff --quiet HEAD^ HEAD -- functions; then
            echo "No changes in functions directory. Skipping deployment."
            exit 1
          fi

      - name: Deploy Firebase Functions
        if: steps.check_changes.outcome == 'success'
        run: firebase deploy --only functions
ShaneBonkowski commented 3 months ago

Closing since https://github.com/ShaneBonkowski/ShanesGames/issues/211 is the new ticket