forked from concourse/concourse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
web_auth_handler.go
68 lines (52 loc) · 1.67 KB
/
web_auth_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
package auth
import (
"context"
"net/http"
"github.com/pf-qiu/concourse/v6/skymarshal/token"
)
//go:generate counterfeiter net/http.Handler
func NewResponseWrapper(w http.ResponseWriter, m token.Middleware) *responseWrapper {
return &responseWrapper{w, m}
}
type responseWrapper struct {
http.ResponseWriter
token.Middleware
}
func (r *responseWrapper) WriteHeader(statusCode int) {
// we need to unset cookies before writing the header
if statusCode == http.StatusUnauthorized {
r.Middleware.UnsetAuthToken(r.ResponseWriter)
r.Middleware.UnsetCSRFToken(r.ResponseWriter)
}
r.ResponseWriter.WriteHeader(statusCode)
}
func (r *responseWrapper) Flush() {
r.ResponseWriter.(http.Flusher).Flush()
}
type WebAuthHandler struct {
Handler http.Handler
Middleware token.Middleware
}
func (handler WebAuthHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
tokenString := handler.Middleware.GetAuthToken(r)
if tokenString != "" {
ctx := context.WithValue(r.Context(), CSRFRequiredKey, handler.isCSRFRequired(r))
r = r.WithContext(ctx)
if r.Header.Get("Authorization") == "" {
r.Header.Set("Authorization", tokenString)
}
wrapper := NewResponseWrapper(w, handler.Middleware)
handler.Handler.ServeHTTP(wrapper, r)
} else {
handler.Handler.ServeHTTP(w, r)
}
}
// We don't validate CSRF token for GET requests
// since they are not changing the state
func (handler WebAuthHandler) isCSRFRequired(r *http.Request) bool {
return (r.Method != http.MethodGet && r.Method != http.MethodHead && r.Method != http.MethodOptions)
}
func IsCSRFRequired(r *http.Request) bool {
required, ok := r.Context().Value(CSRFRequiredKey).(bool)
return ok && required
}