CookieAuth extracts the auth cookie and forwards it to the Authorization header.
(cookieName string)
| 23 | // CookieAuth extracts the auth cookie and forwards it |
| 24 | // to the Authorization header. |
| 25 | func CookieAuth(cookieName string) MiddlewareFunc { |
| 26 | return func(next http.Handler) http.Handler { |
| 27 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 28 | if r.Header.Get("Authorization") != "" { |
| 29 | next.ServeHTTP(w, r) |
| 30 | return |
| 31 | } |
| 32 | cookieValue, err := r.Cookie(cookieName) |
| 33 | if err != nil { |
| 34 | next.ServeHTTP(w, r) |
| 35 | return |
| 36 | } |
| 37 | sc, err := GetSecureCookie(r.Context()) |
| 38 | if err != nil { |
| 39 | next.ServeHTTP(w, r) |
| 40 | return |
| 41 | } |
| 42 | authCookie := &auth.CookieShape{} |
| 43 | err = sc.Decode(cookieName, cookieValue.Value, authCookie) |
| 44 | if err != nil { |
| 45 | next.ServeHTTP(w, r) |
| 46 | return |
| 47 | } |
| 48 | if authCookie.SessionSecret != "" { |
| 49 | key := auth.JoinToken(auth.SessionToken, authCookie.SessionID, authCookie.SessionSecret) |
| 50 | r.Header.Set("Authorization", "Bearer "+key) |
| 51 | } |
| 52 | next.ServeHTTP(w, r) |
| 53 | }) |
| 54 | } |
| 55 | } |