package util

import (
	"net/http"

	"github.com/pingcap/errcode"
	"github.com/pingcap/errors"
)

// MWRequireAuth checks whether the current HTTP request is at least authenticated by one of the
// authenticator in the middleware pipeline. If request is not authenticated by any authenticator,
// "unauthorized" errors will be thrown.
func MWRequireAuth(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// Don't authenticate an OPTIONS request
		if r.Method == http.MethodOptions {
			next.ServeHTTP(w, r)
			return
		}

		if r.Context().Value(AuthProcessedByKey) != nil {
			// Authenticated by other middlewares, skip.
			next.ServeHTTP(w, r)
			return
		}

		// TODO: Better to show previous failure authenticate messages.
		authErr := errcode.NewNotAuthenticatedErr(errors.New("unauthorized"))
		code := errcode.CodeChain(authErr)
		http.Error(w, authErr.Error(), code.Code().HTTPCode())
	})
}

func MWRemoveAuthHeader(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		r.Header.Del("Authorization")
		next.ServeHTTP(w, r)
	})
}
