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) }) }))