-
Notifications
You must be signed in to change notification settings - Fork 31
/
middleware.go
executable file
·96 lines (80 loc) · 2.21 KB
/
middleware.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package auth
import (
"errors"
"net/http"
"github.com/gorilla/mux"
"github.com/rs/cors"
"github.com/tendermint/dex-demo/embedded/session"
)
const (
keybaseIDKey = "keybaseID"
keybasePassphraseKey = "keybasePassphrase"
csrfTokenKey = "csrfToken"
otpHeader = "X-OTP-Token"
csrfHeader = "X-CSRF-Token"
)
func DefaultAuthMW(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
LoginRequiredMW(next).ServeHTTP(w, r)
})
}
func LoginRequiredMW(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
store, err := session.SessionStore.Get(r, sessionName)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
kbID, ok := store.Values[keybaseIDKey]
if !ok || GetKB(kbID.(string)) == nil {
http.Error(w, "Not logged in.", http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}
func OTPRequiredMW(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
header := r.Header.Get(otpHeader)
if header == "" {
http.Error(w, "No OTP header provided.", http.StatusUnauthorized)
return
}
next(w, r)
}
}
func ProtectCSRFMW(skipRoutes []string) mux.MiddlewareFunc {
skipMap := make(map[string]bool)
for _, route := range skipRoutes {
skipMap[route] = true
}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
//TEMPORARY: just for hackathon
next.ServeHTTP(w, r)
return
})
}
}
func HandleCORSMW(next http.Handler) http.Handler {
// TODO: Pull from config
return cors.New(cors.Options{
AllowOriginFunc: func(origin string) bool {
return true
},
AllowedMethods: []string{"HEAD", "GET", "POST", "PUT", "PATCH", "DELETE"},
AllowedHeaders: []string{"*"},
AllowCredentials: true,
}).Handler(next)
}
func GetCSRFToken(r *http.Request) (string, error) {
store, _ := session.SessionStore.Get(r, sessionName)
token := store.Values[csrfTokenKey]
if token == nil {
return "", errors.New("CSRF token not found")
}
return token.(string), nil
}
func genCsrfToken() string {
return ReadStr32()
}