This repository has been archived by the owner on Mar 16, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
85 lines (70 loc) · 1.75 KB
/
handler.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
package persona
import (
"log"
"net/http"
)
func New(store Store, audience string, users []string) PersonaHandlers {
return PersonaHandlers{
SignIn: signInHandler{store, audience},
SignOut: signOutHandler{store},
Protect: Protector(store, users),
Switch: Switcher(store, users),
}
}
type Protect func(http.Handler) http.Handler
type Switch func(http.Handler, http.Handler) http.Handler
type PersonaHandlers struct {
SignIn http.Handler
SignOut http.Handler
Protect Protect
Switch Switch
}
func isSignedIn(toCheck string, users []string) bool {
for _, user := range users {
if user == toCheck {
return true
}
}
return false
}
func Switcher(store Store, users []string) Switch {
return func(good, bad http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !isSignedIn(store.Get(r), users) {
bad.ServeHTTP(w, r)
return
}
good.ServeHTTP(w, r)
})
}
}
var forbidden = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "403 forbidden", http.StatusForbidden)
})
func Protector(store Store, users []string) Protect {
return func(handler http.Handler) http.Handler {
return Switcher(store, users)(handler, forbidden)
}
}
type signInHandler struct {
store Store
audience string
}
func (s signInHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
assertion := r.PostFormValue("assertion")
email, err := assert(s.audience, assertion)
if err != nil {
log.Print("persona:", err)
w.WriteHeader(403)
return
}
s.store.Set(email, w, r)
w.WriteHeader(200)
}
type signOutHandler struct {
store Store
}
func (s signOutHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.store.Set("-", w, r)
http.Redirect(w, r, "/", 307)
}