/**************************************************************************************
 *
 *     Project:    kvmstoreserver
 *     File name:  urlIntegretyCHecker.go
 *     Version:    1.0.0
 *     Date:       2018-01-14
 *
 *     Autor:      Bogdanovic Theodor
 *     Contact:    t.bogdanovic@hotmail.com
 *
 *     License:    GPLv3
 *
 **************************************************************************************/
/**************************************************************************************
 * Copyright 2018 Bogdanovic Theodor
 *
 * This file is part of kvmstoreserver.
 *
 * kvmstoreserver is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * kvmstoreserver is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with kvmstoreserver.  If not, see <http://www.gnu.org/licenses/>.
 **************************************************************************************/
/**************************************************************************************
 *  Further explanations:  This source code is under the license specified by the
 *                         Autor above. Core components or other packages are still
 *                         in source code form, under the license specified by the
 *                         respective author.
 **************************************************************************************/

package middlewareFunctions

import (
	"errors"
	es "essentials"
	"fmt"
	eh "kvmstoreserver_utils/errorHandling"
	"net/http"
	"strings"

	log "github.com/judwhite/logrjack"
)

//*****************************************************************************
//*
//*      Declarations
//*
//*****************************************************************************

var validParams = []string{"rev", "search"}

//*****************************************************************************
//*
//*      Public Functions: Middleware functionality
//*
//*****************************************************************************

// MWareCheckKeyInURL checks if a key name exist in the the URL call
// from the client.
func MWareCheckKeyInURL(nextFunc http.Handler) http.Handler {

	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

		// BEGIN Handler Logic ->

		keyInUrlwithoutParams := es.CutKeyFromURL(r.RequestURI)

		if keyInUrlwithoutParams == "" ||
			strings.Contains(keyInUrlwithoutParams, "%26") {

			result := eh.IfErrBuildJSONAndOrPanic(w,
				errors.New("Missing key name as a segment of the URL"),
				http.StatusBadRequest, "Error in Middleware", es.DontPanic)

			log.Warnf("Request without key name received and abort from -> (%v)",
				r.RemoteAddr)

			if result != eh.Ok {
				return
			}
		}

		nextFunc.ServeHTTP(w, r)
		// <- END Handler Logic

	})
}

// MwareCheckParamIntegrity allows only the known parameters
// (define in validParams). All other parameter calls are not allowed
func MwareCheckParamIntegrity(nextFunc http.Handler) http.Handler {

	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

		// BEGIN Handler Logic ->
	outer:
		for param := range r.URL.Query() {
			for _, vaildParam := range validParams {
				if param == vaildParam {
					continue outer
				}
			}

			result := eh.IfErrBuildJSONAndOrPanic(w,
				fmt.Errorf("This parameter is not allowed -> (%v)", param),
				http.StatusBadRequest, "Error in Middleware", es.DontPanic)

			log.Warnf("Request aborted - unknown parameter -> (%v) was detected from -> (%v)",
				param, r.RemoteAddr)

			if result != eh.Ok {
				return
			}
		}

		nextFunc.ServeHTTP(w, r)
		// <- END Handler Logic

	})
}
