const admin = require('firebase-admin'); const Logger = require('../Logger'); const mLogger = new Logger('admin', 'superAuth'); module.exports = (req, res, next) => { mLogger.start(); res.set('Access-Control-Allow-Origin', ['*']); if (req.method === 'OPTIONS') { mLogger.success('OPTIONS CALL', { URL: req.url }); res.status(200).send(); return next(); } if (req.headers.authorization) { try { const token = req.headers.authorization.split(' ')[1]; const reqToken = token.split(':')[0]; const reqUid = token.split(':')[1]; admin .auth() .verifyIdToken(reqToken) .then((user) => { if (user.uid === 'PTjxbs2rAxMvCD6Pj5P6Z2U6d5A3' && user.uid === reqUid) { if (req.method === 'POST') { const bodydata = JSON.parse(req.body); bodydata.uid = user.uid; req.body = JSON.stringify(bodydata); } if (req.method === 'GET' || req.method === 'DELETE' || req.method === 'PUT') { req.body = JSON.stringify({ uid: user.uid }); } mLogger.success('AUTHORIZED', { URL: req.url, UID: reqUid }); return next(); } else { mLogger.success('NOT AUTHORIZED', { URL: req.url }); return res.status(401).send({ message: 'Unauthorized' }); } }) .catch((err) => { mLogger.error('AUTH VALIDATE FIREBASE ERROR', { URL: req.url, Error: err, }); return res.status(500).send({ message: 'Unable to verify user token' }); }); } catch (err) { mLogger.error('AUTH VALIDATE ERROR', { URL: req.url, Error: err }); return res.status(401).send({ message: 'Something went wrong when authorizing' }); } } else { mLogger.error('NO AUTH TOKEN', { URL: req.url }); res.status(401).send({ message: 'Got no user token' }); } return 0; };