diff --git a/src/app.js b/src/app.js index fef317c..d45d813 100644 --- a/src/app.js +++ b/src/app.js @@ -14,6 +14,7 @@ const handle404 = require("./middlewares/handle404"); const errorHandler = require("./middlewares/errorHandler"); const headers = require("./middlewares/headers"); const auth = require("./middlewares/auth"); +const audit = require("./middlewares/audit") // Configure application @@ -51,6 +52,8 @@ app.use(logger(function (tokens, req, res) { + " " + chalk.white((req.user && req.user.email) || "(anonymous)"); })); +app.use(audit); + // Routes const collegesRouter = require("./routes/colleges"); const eventsRouter = require("./routes/events"); diff --git a/src/middlewares/audit.js b/src/middlewares/audit.js new file mode 100644 index 0000000..80d167d --- /dev/null +++ b/src/middlewares/audit.js @@ -0,0 +1,24 @@ +"use strict"; + +const AuditModel = require("../models/Audit"); + +module.exports = async (req, res, next) => { + res.on("finish", async () => { + if (req.method == "GET") + return; + let { method, url, baseUrl, user } = req; + let entry = { + method, + url: `${baseUrl}/${url}`, + user: user ? user.email : "(unknown)", + time: new Date() + }; + try { + await AuditModel.create(entry); + } + catch (e) { + console.log("Audit Log failed", e); + } + }); + next(); +}; diff --git a/src/models/Audit.js b/src/models/Audit.js new file mode 100644 index 0000000..7f0b185 --- /dev/null +++ b/src/models/Audit.js @@ -0,0 +1,28 @@ +const mongoose = require("mongoose"); + +const schema = { + method: { + type: String, + required: true, + }, + time: { + type: Date, + required: true, + }, + user: { + type: String, + required: true + }, + url: { + type: String, + required: true, + }, +}; + +const options = { + autoCreate: true, +}; + +const auditSchema = new mongoose.Schema(schema, options); + +module.exports = mongoose.model("Audit", auditSchema);