From d6c2ba58121019a7773e608e2cae351c263b5d25 Mon Sep 17 00:00:00 2001 From: Nazar Kanaev Date: Mon, 4 Jan 2021 14:15:28 +0000 Subject: [PATCH] simple csrf protection --- assets/javascripts/api.js | 7 +++++-- server/server.go | 8 ++++++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/assets/javascripts/api.js b/assets/javascripts/api.js index 2698d5f..ca95207 100644 --- a/assets/javascripts/api.js +++ b/assets/javascripts/api.js @@ -2,9 +2,12 @@ (function() { var api = function(method, endpoint, data) { + var headers = {'Content-Type': 'application/json'} + if (['get', 'post', 'put'].indexOf(method) !== -1) + headers['x-requested-by'] = 'yarr' return fetch(endpoint, { method: method, - headers: {'Content-Type': 'application/json'}, + headers: headers, body: JSON.stringify(data), }) } @@ -12,7 +15,7 @@ var json = function(res) { return res.json() } - + var param = function(query) { if (!query) return '' return '?' + Object.keys(query).map(function(key) { diff --git a/server/server.go b/server/server.go index a3fd25b..2a16298 100644 --- a/server/server.go +++ b/server/server.go @@ -43,6 +43,10 @@ func (h *Handler) Start() { } } +func unsafeMethod(method string) bool { + return method == "POST" || method == "PUT" || method == "DELETE" +} + func (h Handler) ServeHTTP(rw http.ResponseWriter, req *http.Request) { route, vars := getRoute(req) if route == nil { @@ -51,6 +55,10 @@ func (h Handler) ServeHTTP(rw http.ResponseWriter, req *http.Request) { } if h.requiresAuth() && !route.manualAuth { + if unsafeMethod(req.Method) && req.Header.Get("X-Requested-By") != "yarr" { + rw.WriteHeader(http.StatusUnauthorized) + return + } if !userIsAuthenticated(req, h.Username, h.Password) { rw.WriteHeader(http.StatusUnauthorized) return