Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import * as admin from 'firebase-admin'
- const {
- FIREBASE_INFO,
- FIREBASE_DATABASE_URL
- } = process.env
- let serviceAccount = JSON.parse(FIREBASE_INFO)
- admin.initializeApp({
- credential: admin.credential.cert(serviceAccount),
- databaseURL: FIREBASE_DATABASE_URL
- })
- // when decoded successfully, the ID Token content will be added as `req.user`.
- export function validateFirebaseIdToken(req, res, next) {
- // Unauthenticated routes go here
- if (['/health', '/users/emails'].includes(req.path)) return next();
- if ((!req.headers.authorization || !req.headers.authorization.startsWith('Bearer ')) &&
- !(req.cookies && req.cookies.__session)) {
- res.status(403).send('Unauthorized');
- return;
- }
- let idToken;
- if (req.headers.authorization && req.headers.authorization.startsWith('Bearer ')) {
- // Read the ID Token from the Authorization header.
- idToken = req.headers.authorization.split('Bearer ')[1];
- } else if(req.cookies) {
- // Read the ID Token from cookie.
- idToken = req.cookies.__session;
- } else {
- // No cookie
- res.status(403).send('Unauthorized');
- return;
- }
- admin.auth().verifyIdToken(idToken).then((decodedIdToken) => {
- req.user = decodedIdToken;
- return next();
- }).catch((error) => {
- res.status(403).send('Unauthorized');
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement