-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathhook.js
87 lines (67 loc) · 2.38 KB
/
hook.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
const express = require("express");
const bodyParser = require("body-parser");
const dotenv = require("dotenv");
const mongoose = require("mongoose");
const pino = require("pino");
const path = require("path");
const verification = require("./verification");
const utils = require("./utils");
// --------------------------------------------------------------------------------- //
const result = dotenv.config();
if (result.error) {
throw result.error;
}
const secret = process.env.SECRET;
const db_uri = process.env.DB_CONNECTION;
const provider = process.env.PROVIDER;
const sigHeaderName = utils.getHeader(provider);
//TODO: Use `useLevelLabels`
const logger = pino({ level: process.env.LOG_LEVEL || "info" });
const app = express();
//FIXME: Change bodyparser
app.use(bodyParser.json());
let Schema, collectionSchema, collection;
mongoose.connect(db_uri, { autoCreate: true });
const connection = mongoose.connection;
connection.once("open", function () {
logger.info("MongoDB connection established");
Schema = mongoose.Schema;
collectionSchema = new Schema({}, { strict: false });
collection = mongoose.model(provider, collectionSchema);
});
// --------------------------------------------------------------------------------- //
function verifyPostData(req, _, next) {
if (req.query.trusted) {
if (req.query.trusted == process.env.TRUST_KEY) {
return next();
} else {
logger.info("Trust key is wrong");
}
}
const payload = JSON.stringify(req.body);
if (!payload) {
return next("Request body empty");
}
if (!verification.verify(req.get(sigHeaderName), payload, secret)) {
return next("Request body digest did not match");
}
return next();
}
function response(req, res) {
logger.debug("Data received");
const collectionData = new collection(req.body);
collectionData.save();
res.status(200).send();
}
// --------------------------------------------------------------------------------- //
app.get("/", function (_, res) {
res.sendFile(path.join(__dirname + "/index.html"));
});
app.post(["/github", "/gitlab", "/gitea", "/gogs"], verifyPostData, response);
// --------------------------------------------------------------------------------- //
app.use((err, _, res, __) => {
if (err) logger.error(err);
res.status(403).send("Request body was not signed or verification failed");
});
logger.info("Handler is runnig");
app.listen(3000);