# Firebase Cloud Function Proxy Template for Copernicus CDSE

When querying the Copernicus Data Space Ecosystem (CDSE) from a web application, you must exchange your Client Credentials for an OAuth Token. **You cannot do this securely from client-side JavaScript.** 

Use this Firebase Cloud Function template to create a secure proxy.

## 1. Setup Firebase Functions
Initialize functions in your Firebase project (requires Blaze Plan):
```bash
firebase init functions
```
Choose **JavaScript**.

## 2. Install Dependencies
Navigate to the `functions` directory and install axios:
```bash
cd functions
npm install axios cors
```

## 3. Replace index.js
Replace the contents of `functions/index.js` with the following code:

```javascript
const functions = require("firebase-functions");
const axios = require("axios");
const cors = require("cors")({ origin: true });

// Ensure you set these config variables in Firebase:
// firebase functions:config:set copernicus.client_id="YOUR_ID" copernicus.client_secret="YOUR_SECRET"

exports.getCDSEToken = functions.https.onRequest((req, res) => {
  cors(req, res, async () => {
    try {
      const clientId = functions.config().copernicus.client_id;
      const clientSecret = functions.config().copernicus.client_secret;

      const params = new URLSearchParams();
      params.append('client_id', clientId);
      params.append('client_secret', clientSecret);
      params.append('grant_type', 'client_credentials');

      const response = await axios.post(
        'https://identity.dataspace.copernicus.eu/auth/realms/CDSE/protocol/openid-connect/token',
        params,
        {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        }
      );

      // Return only the token to the client frontend
      res.status(200).send({ access_token: response.data.access_token });
      
    } catch (error) {
      console.error("Error fetching token:", error.message);
      res.status(500).send({ error: "Failed to authenticate with CDSE" });
    }
  });
});
```

## 4. Set Environment Variables and Deploy
Set your actual Client ID and Secret in the Firebase environment, then deploy:
```bash
firebase functions:config:set copernicus.client_id="<YOUR_CLIENT_ID>" copernicus.client_secret="<YOUR_CLIENT_SECRET>"
firebase deploy --only functions
```

Your frontend can now safely fetch the token from your Cloud Function URL!
