Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save glauberramos/65f8c2669ca3863342f1a2f9d65ff280 to your computer and use it in GitHub Desktop.
Save glauberramos/65f8c2669ca3863342f1a2f9d65ff280 to your computer and use it in GitHub Desktop.
Firebase Auth Middleware
'use strict'
require('firebase-functions/lib/logger/compat')
const functions = require('firebase-functions')
const admin = require('firebase-admin')
const express = require('express')
const cookieParser = require('cookie-parser')
const cors = require('cors')
try {
admin.initializeApp(functions.config().firebase)
} catch (e) {
// You do that because the admin SDK can only be initialized once.
}
const validateFirebaseIdToken = async (req, res, next) => {
if (
(!req.headers.authorization ||
!req.headers.authorization.startsWith('Bearer '))
) {
res.status(403).send('Unauthorized')
return
}
let idToken
if (
req.headers.authorization &&
req.headers.authorization.startsWith('Bearer ')
) {
idToken = req.headers.authorization.split('Bearer ')[1]
} else {
res.status(403).send('Unauthorized')
return
}
try {
const decodedIdToken = await admin.auth().verifyIdToken(idToken)
req.user = decodedIdToken
next()
return
} catch (error) {
res.status(403).send('Unauthorized')
return
}
}
const app = express()
app.use(
cors({
origin: [
/.*localhost:\d*/,
/.*funretro-pro-test\.firebaseapp\.com/,
/.*easyretro\.io/
],
credentials: true
})
)
app.use(cookieParser())
app.use(validateFirebaseIdToken)
app.post('/', async (req, res) => {
res.send({message: 'Hello' })
})
module.exports = functions.https.onRequest(app)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment