forked from vmware-archive/atc
-
Notifications
You must be signed in to change notification settings - Fork 1
/
cookie_set_handler.go
35 lines (28 loc) · 885 Bytes
/
cookie_set_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
package auth
import (
"context"
"net/http"
)
type CookieSetHandler struct {
Handler http.Handler
}
func (handler CookieSetHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie(AuthCookieName)
if err == nil {
ctx := context.WithValue(r.Context(), CSRFRequiredKey, handler.isCSRFRequired(r))
r = r.WithContext(ctx)
if r.Header.Get("Authorization") == "" {
r.Header.Set("Authorization", cookie.Value)
}
}
handler.Handler.ServeHTTP(w, r)
}
// We don't validate CSRF token for GET requests
// since they are not changing the state
func (handler CookieSetHandler) 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
}