-
Notifications
You must be signed in to change notification settings - Fork 0
/
csrf.go
58 lines (54 loc) · 1.39 KB
/
csrf.go
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
// Copyright 2015 Afshin Darian. All rights reserved.
// Use of this source code is governed by The MIT License
// that can be found in the LICENSE file.
package wares
import (
"bytes"
"encoding/json"
"io/ioutil"
"net/http"
"github.com/ursiform/bear"
"github.com/ursiform/forest"
)
func CSRF(app *forest.App) func(ctx *bear.Context) {
type postBody struct {
SessionID string `json:"sessionid"` // forest.SessionID == "sessionid"
}
return func(ctx *bear.Context) {
if ctx.Request.Body == nil {
app.Response(ctx, http.StatusBadRequest,
forest.Failure, app.Error("CSRF")).Write(nil)
return
}
pb := new(postBody)
body, _ := ioutil.ReadAll(ctx.Request.Body)
if body == nil || len(body) < 2 { // smallest JSON body is {}, 2 chars
app.Response(
ctx,
http.StatusBadRequest,
forest.Failure,
app.Error("Parse")).Write(nil)
return
}
// set ctx.Request.Body back to an untouched io.ReadCloser
ctx.Request.Body = ioutil.NopCloser(bytes.NewBuffer(body))
if err := json.Unmarshal(body, pb); err != nil {
app.Response(
ctx,
http.StatusBadRequest,
forest.Failure,
app.Error("Parse")+": "+err.Error()).Write(nil)
return
}
sessionID, ok := ctx.Get(forest.SessionID).(string)
if !ok || sessionID != pb.SessionID {
app.Response(
ctx,
http.StatusBadRequest,
forest.Failure,
app.Error("CSRF")).Write(nil)
return
}
ctx.Next()
}
}