1

firebase.json:

{
  "hosting": {
    "public": "public",
    "rewrites": [
      {
        "source": "**",
        "function": "app"
      }
    ]
  }
}

functions/index.js

const functions = require('firebase-functions')

exports.app = functions.https.onRequest((req, res) => {
  res.send(`Hello`)
)}

When directing hosting requests to a function how to get the current authenticated user that sends the request from within the function?

On https://firebase.google.com/docs/hosting/functions / Using Cookies / __session is mentioned but I'm not sure how to use it. I would be nice to see an example.

Update

This is how I did it:

const functions = require('firebase-functions')
const admin = require('firebase-admin')
admin.initializeApp(functions.config().firebase)
const getCookies = req => {
  let list = {}
  const rc = req.headers.cookie
  rc && rc.split(';').forEach(cookie => {
    var parts = cookie.split('=')
    list[parts.shift().trim()] = decodeURI(parts.join('='))
  })
  return list
}
const validateFirebaseIdToken = (req, res, next) => {
  var idToken = getCookies(req)['__session']
  if (typeof idToken !== 'undefined') {
    admin.auth().verifyIdToken(idToken).then(decodedIdToken => {
      console.log('ID Token decoded:', decodedIdToken)
      req.user = decodedIdToken
      next()
    }).catch(error => {
      console.error('Error decoding ID Token:', error)
      res.status(403).send('Unauthorized')
    })
  } else {
    console.error('No __session')
    res.status(403).send('Unauthorized')
  }
}
exports.app = functions.https.onRequest((req, res) => {
  validateFirebaseIdToken(req, res, () => {
    res.send(req.user.email)
  })
})

There are better ways of doing it for sure but important is that I understand the process now.

Alin C
  • 565
  • 2
  • 6
  • 10

0 Answers0