package middleware

import (
	"net/http"

	"git.clustercockpit.org/moebiusband/go-http-skeleton/internal/auth"
	"git.clustercockpit.org/moebiusband/go-http-skeleton/web"
)

func SecuredCheck(next http.Handler) http.Handler {
	authHandle := auth.GetAuthInstance()

	return authHandle.Auth(
		// On success;
		next,

		// On failure:
		func(rw http.ResponseWriter, r *http.Request, err error) {
			rw.WriteHeader(http.StatusUnauthorized)
			web.RenderTemplate(rw, "login", web.PageData{
				Title:    "Authentication failed - ClusterCockpit",
				MsgType:  "alert-danger",
				Message:  err.Error(),
				Redirect: r.RequestURI,
			})
		})
}
