Created
May 24, 2022 19:49
-
-
Save jaredallard/0ff282a2c9eadd7e0f363ef3e0d6772b to your computer and use it in GitHub Desktop.
Revisions
-
jaredallard created this gist
May 24, 2022 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,55 @@ token, err := conf.Token.Data(ctx) if err != nil { log.Error(ctx, "failed to get token", events.NewErrorInfo(err)) } tokenByt := []byte(token) tokenLength := int32(len(tokenByt)) // Check the auth token base.Use(mux.MiddlewareFunc(func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { checkAuth, err := fflags.Bool(r.Context(), "checkAuth", false) if err != nil { log.Error(r.Context(), "failed to get checkAuth flag", events.Err(err)) } // If we're not checking the auth token, just pass the request through if !checkAuth { next.ServeHTTP(w, r) return } unauthorized := func() { w.WriteHeader(http.StatusUnauthorized) w.Write([]byte("Unauthorized")) } // if no user information, fail the request if r.URL.User == nil { unauthorized() return } suppliedToken, ok := r.URL.User.Password() if !ok { unauthorized() return } suppliedTokenByt := []byte(suppliedToken) // check the length first because constant compare needs to be the same length if subtle.ConstantTimeEq(tokenLength, int32(len(suppliedTokenByt))) == 0 { unauthorized() return } // check the token if subtle.ConstantTimeCompare(tokenByt, suppliedTokenByt) == 0 { unauthorized() return } // pass the request through next.ServeHTTP(w, r) }) }))