From 69eb2b0cc8b88981b00586e7b45f3734c93072f3 Mon Sep 17 00:00:00 2001 From: Menci Date: Sat, 8 Jul 2017 23:53:58 +0800 Subject: [PATCH] Add CSRF token --- app.js | 3 +++ package.json | 1 + static/script.js | 15 +++++++++++++++ views/header.ejs | 2 +- 4 files changed, 20 insertions(+), 1 deletion(-) diff --git a/app.js b/app.js index 59e9bea..de79564 100644 --- a/app.js +++ b/app.js @@ -60,6 +60,9 @@ global.syzoj = { let multer = require('multer'); app.multer = multer({ dest: syzoj.utils.resolvePath(syzoj.config.upload_dir, 'tmp') }); + let csurf = require('csurf'); + app.use(csurf({ cookie: true })); + await this.connectDatabase(); this.loadHooks(); this.loadModules(); diff --git a/package.json b/package.json index 30ccf85..6071104 100644 --- a/package.json +++ b/package.json @@ -29,6 +29,7 @@ "cheerio": "^1.0.0-rc.1", "cookie-parser": "^1.4.3", "cssfilter": "0.0.10", + "csurf": "^1.9.0", "download": "^5.0.3", "ejs": "^2.5.2", "express": "^4.14.0", diff --git a/static/script.js b/static/script.js index 9b62439..28dcb7b 100644 --- a/static/script.js +++ b/static/script.js @@ -7,7 +7,22 @@ $(function () { form.method = 'post'; form.action = $(this).attr('href-post'); form.target = '_self'; + + var input = document.createElement('input'); + input.type = 'hidden'; + input.name = '_csrf'; + input.value = document.head.getAttribute('data-csrf-token'); + form.appendChild(input); + document.body.appendChild(form); form.submit(); }); + + $('form').each(function () { + var input = document.createElement('input'); + input.type = 'hidden'; + input.name = '_csrf'; + input.value = document.head.getAttribute('data-csrf-token'); + this.appendChild(input); + }); }); diff --git a/views/header.ejs b/views/header.ejs index 6215ee6..010026c 100644 --- a/views/header.ejs +++ b/views/header.ejs @@ -1,7 +1,7 @@ <% include util %> - + <%= title %> - <%= syzoj.config.title %>