Last active
June 9, 2023 04:45
-
-
Save filipelinhares/7a4ec753ae4e623ddfabdffc123abb43 to your computer and use it in GitHub Desktop.
Firebase Auth Middleware
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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*/ | |
], | |
credentials: true | |
}) | |
) | |
app.use(cookieParser()) | |
app.use(validateFirebaseIdToken) | |
app.post('/', async (req, res) => { | |
res.send({message: 'Hello' }) | |
}) | |
module.exports = functions.https.onRequest(app) |
fetch(functionURL, {
method: 'POST',
headers: new Headers({
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json'
}),
body
})
I don't know if it is the answer you are looking for. Can you be more specific in that case?
Yes it is. Thank you!
thanks
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample request?