Webhook endpoint with secret in config

This commit is contained in:
Klemek
2019-06-20 19:55:59 +02:00
parent 553aa40fb3
commit c1c8672380
4 changed files with 75 additions and 94 deletions
+16 -44
View File
@@ -14,16 +14,6 @@ const cons = {
error: '\x1b[31m✘\x1b[0m %s',
};
const randStr = (length) => {
let result = '';
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const charactersLength = characters.length;
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
};
module.exports = (config) => {
const fw = require('./file_walker')(config);
const renderer = require('./renderer')(config);
@@ -35,7 +25,6 @@ module.exports = (config) => {
const articles = {};
let lastRSS = '';
let webhookSecret;
/**
* Fetch articles from the data folder and send success as a response
@@ -64,35 +53,6 @@ module.exports = (config) => {
if (config['test'])
app.reload = reload;
/**
* Fetch or create secret token for git webhook
* @param success
* @param error
*/
const checkSecret = (success, error) => {
if (!config['modules']['webhook'])
success();
fs.readFile(config['webhook']['secret_file'], {encoding: 'UTF-8'}, (err, data) => {
if (err) {
webhookSecret = randStr(32);
fs.writeFile(config['webhook']['secret_file'], webhookSecret, {encoding: 'UTF-8'}, (err) => {
if (err) {
console.error(cons.error, 'error creating secret : ' + err);
return error ? error() : null;
}
console.log(cons.ok,'created git secret at '+config['webhook']['secret_file']);
success();
});
} else {
webhookSecret = data;
console.log(cons.ok,'loaded git secret from '+config['webhook']['secret_file']);
success();
}
});
};
if (config['test'])
app.checkSecret = checkSecret;
/**
* Render the page with the view engine and catch errors
* @param res
@@ -164,6 +124,20 @@ module.exports = (config) => {
}
});
//webhook endpoint
app.post(config['webhook']['endpoint'], (req, res) => {
if (config['modules']['webhook']) {
if (config['webhook']['secret_header'] && req.get(config['webhook']['secret_header']) !== config['webhook']['secret_value']) {
res.sendStatus(403);
} else {
res.sendStatus(200);
//TODO reload
}
} else {
res.sendStatus(400);
}
});
// catch all article urls and render them
app.get('*', (req, res, next) => {
if (/^\/\d{4}\/\d{2}\/\d{2}\/(\w*\/)?$/.test(req.path)) {
@@ -222,10 +196,8 @@ module.exports = (config) => {
// must be use in a server.js to start the server
app.start = () => {
reload(() => {
checkSecret(() => {
app.listen(config['node_port'], () => {
console.log(cons.ok, `gitblog.md server listening on port ${config['node_port']}`);
});
app.listen(config['node_port'], () => {
console.log(cons.ok, `gitblog.md server listening on port ${config['node_port']}`);
});
});
};
+2 -1
View File
@@ -30,7 +30,8 @@
},
"webhook": {
"endpoint": "/webhook",
"secret_file": "git_secret"
"secret_value": "",
"secret_header": ""
},
"showdown": {
"parseImgDimensions": true,