diff --git a/lib/common.js b/lib/common.js index 57f4949..8f8fcf4 100755 --- a/lib/common.js +++ b/lib/common.js @@ -53,13 +53,35 @@ exports.restrict = (req, res, next) => { exports.checkLogin(req, res, next); }; -exports.checkLogin = (req, res, next) => { +exports.checkLogin = async (req, res, next) => { + const db = req.app.db; // if not protecting we check for public pages and don't checkLogin if(req.session.needsSetup === true){ res.redirect('/admin/setup'); return; } + // If API key, check for a user + if(req.headers.apikey){ + try{ + const user = await db.users.findOne({ + apiKey: ObjectId(req.headers.apikey), + isAdmin: true + }); + if(!user){ + res.status(400).json({message: 'Access denied'}); + return; + } + // Set API authenticated in the req + req.apiAuthenticated = true; + next(); + return; + }catch(ex){ + res.status(400).json({message: 'Access denied'}); + return; + } + } + if(req.session.user){ next(); return; @@ -263,10 +285,18 @@ exports.getConfig = () => { exports.getPaymentConfig = () => { let siteConfig = this.getConfig(); + const gateConfigFile = path.join(__dirname, '../config', `${siteConfig.paymentGateway}.json`); let config = []; - if(fs.existsSync(path.join(__dirname, '../config/' + siteConfig.paymentGateway + '.json'))){ - config = JSON.parse(fs.readFileSync(path.join(__dirname, '../config/' + siteConfig.paymentGateway + '.json'), 'utf8')); + if(fs.existsSync(gateConfigFile)){ + config = JSON.parse(fs.readFileSync(gateConfigFile, 'utf8')); + } + + // If a local config we combine the objects. Local configs are .gitignored + let localConfig = path.join(__dirname, '../config', `${siteConfig.paymentGateway}-local.json`); + if(fs.existsSync(localConfig)){ + const localConfigObj = JSON.parse(fs.readFileSync(localConfig, 'utf8')); + config = Object.assign(config, localConfigObj); } return config;