Skip to content
This repository has been archived by the owner on Jan 3, 2022. It is now read-only.

Commit

Permalink
Fix
Browse files Browse the repository at this point in the history
  • Loading branch information
Neztore committed Aug 2, 2020
1 parent 9e6800c commit b64673d
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/client/util/apiFetch.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
module.exports.apiFetch = async function (url, options) {
const a = module.exports.getCookie("auth");
const csrf = module.exports.getCookie("CSRF-Token");

options = options || {};
options.credentials = "include";
options.headers = options.headers || {};
options.headers.Authorization = `Bearer ${a}`;
options.headers["CSRF-Token"] = csrf;

let json;
try {
Expand Down
47 changes: 47 additions & 0 deletions src/server/csrf.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
// CSRF Protection

const { randomBytes } = require("crypto");

function generateToken (length = 100){
return new Promise(((resolve, reject) => {
// we'll never use all the bytes, but might as well make sure
randomBytes(length, (err, buffer) => {
if (err) {
return reject(err);
}
const token = buffer.toString("hex");
return resolve(token.substr(0, length));
});
}));
}
const protectedMethods = ["post", "patch", "put", "delete"];
module.exports = function (req, res, next) {
function fail () {
return res.status(400).send({
error: {
status: 400,
message: "Failed CSRF token validation"
}
});
}
if (protectedMethods.includes(req.method)) {
// Validate CSRF presence
if (req.cookies["CSRF-Token"] && req.get("CSRF-Token")) {
if (req.cookies["CSRF-Token"] === req.get("CSRF-Token")) {
console.log("CSRF pass")
return next();
}
}
return fail();
} else {
// It's a get
if (!req.cookies["CSRF-Token"]) {
res.cookie("CSRF-Token", generateToken(20), {
maxAge: 172800000,
sameSite: "strict",
httpOnly: false
});
}
return next();
}
};
5 changes: 5 additions & 0 deletions src/server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@ const app = express();
// Require statements
const path = require("path");
const bodyParser = require('body-parser');
const cookieParser = require("cookie-parser");
const fs = require("fs");
const api = require('./api.js');
const config = require('./config.js');
const csrf = require("./csrf");

// Sentry
const Sentry = require('@sentry/node');
Expand All @@ -27,12 +29,15 @@ app.use('/api', api);

app.use('/public', express.static(staticPath));
app.use('/', express.static(distPath));
app.use(cookieParser());
app.use(csrf);
// Setup
let fileExists;
fs.access(filePath, fs.constants.F_OK, (err) => {
fileExists = !err;
});


// STATIC FILES
app.get('/', function (req, res) {
console.log(`Request to index from ${req.ip}`);
Expand Down

0 comments on commit b64673d

Please sign in to comment.