2016-01-05 00:32:53 +01:00
|
|
|
package util
|
|
|
|
|
|
|
|
import (
|
2017-02-23 00:21:49 +01:00
|
|
|
"net/http"
|
2016-01-05 00:32:53 +01:00
|
|
|
"strconv"
|
|
|
|
"strings"
|
2019-07-09 14:56:03 +02:00
|
|
|
|
2018-03-27 22:12:47 +02:00
|
|
|
log "github.com/Sirupsen/logrus"
|
2019-07-09 14:56:03 +02:00
|
|
|
"github.com/gorilla/mux"
|
2016-01-05 00:32:53 +01:00
|
|
|
)
|
|
|
|
|
2017-02-22 23:17:36 +01:00
|
|
|
func isXHR(w http.ResponseWriter, r *http.Request) bool {
|
|
|
|
accept := r.Header.Get("Accept")
|
2018-03-27 22:12:47 +02:00
|
|
|
return !strings.Contains(accept, "text/html")
|
2016-01-05 00:32:53 +01:00
|
|
|
}
|
|
|
|
|
2018-03-27 22:12:47 +02:00
|
|
|
// AuthFailed write a status unauthorized header unless it is an XHR request
|
|
|
|
// TODO - never called!
|
2019-07-09 14:56:03 +02:00
|
|
|
func AuthFailed(next http.Handler) http.Handler {
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
if !isXHR(w, r) {
|
|
|
|
http.Redirect(w, r, "/?hai", http.StatusFound)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
w.WriteHeader(http.StatusUnauthorized)
|
2016-01-05 00:32:53 +01:00
|
|
|
|
2019-07-09 17:55:42 +02:00
|
|
|
if (next != nil) {
|
|
|
|
next.ServeHTTP(w, r)
|
|
|
|
}
|
2019-07-09 14:56:03 +02:00
|
|
|
})
|
2016-01-05 00:32:53 +01:00
|
|
|
}
|
|
|
|
|
2018-03-27 22:12:47 +02:00
|
|
|
// GetIntParam fetches a parameter from the route variables as an integer
|
|
|
|
// redirects to a 404 or writes bad request state depending on error state
|
2017-02-22 23:17:36 +01:00
|
|
|
func GetIntParam(name string, w http.ResponseWriter, r *http.Request) (int, error) {
|
2017-02-23 00:21:49 +01:00
|
|
|
intParam, err := strconv.Atoi(mux.Vars(r)[name])
|
|
|
|
|
2016-01-05 00:32:53 +01:00
|
|
|
if err != nil {
|
2018-03-27 22:12:47 +02:00
|
|
|
if !isXHR(w, r) {
|
2017-02-23 00:21:49 +01:00
|
|
|
http.Redirect(w, r, "/404", http.StatusFound)
|
2016-01-05 00:32:53 +01:00
|
|
|
} else {
|
2017-02-22 23:17:36 +01:00
|
|
|
w.WriteHeader(http.StatusBadRequest)
|
2016-01-05 00:32:53 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
return 0, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return intParam, nil
|
|
|
|
}
|
2018-03-27 22:12:47 +02:00
|
|
|
|
|
|
|
// ScanErrorChecker deals with errors encountered while scanning lines
|
|
|
|
// since we do not fail on these errors currently we can simply note them
|
|
|
|
// and move on
|
|
|
|
func ScanErrorChecker(n int, err error) {
|
|
|
|
if err != nil {
|
|
|
|
log.Warn("An input error occured:" + err.Error())
|
|
|
|
}
|
|
|
|
}
|