forked from volatiletech/authboss-sample
/
middleware.go
63 lines (56 loc) · 1.44 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
package main
import (
"fmt"
"log"
"net/http"
"github.com/justinas/nosurf"
)
type authProtector struct {
f http.HandlerFunc
}
func authProtect(f http.HandlerFunc) authProtector {
return authProtector{f}
}
func (ap authProtector) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if u, err := ab.CurrentUser(w, r); err != nil {
log.Println("Error fetching current user:", err)
w.WriteHeader(http.StatusInternalServerError)
} else if u == nil {
log.Println("Redirecting unauthorized user from:", r.URL.Path)
http.Redirect(w, r, "/", http.StatusFound)
} else {
ap.f(w, r)
}
}
func nosurfing(h http.Handler) http.Handler {
surfing := nosurf.New(h)
surfing.SetFailureHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println("Failed to validate XSRF Token:", nosurf.Reason(r))
w.WriteHeader(http.StatusBadRequest)
}))
return surfing
}
func logger(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Printf("\n%s %s %s\n", r.Method, r.URL.Path, r.Proto)
session, err := sessionStore.Get(r, sessionCookieName)
if err == nil {
fmt.Print("Session: ")
first := true
for k, v := range session.Values {
if first {
first = false
} else {
fmt.Print(", ")
}
fmt.Printf("%s = %v", k, v)
}
fmt.Println()
}
fmt.Print("Database: ")
for _, u := range database.Users {
fmt.Printf("%#v\n", u)
}
h.ServeHTTP(w, r)
})
}