2023-06-17 04:08:50 +00:00
|
|
|
package middlewares
|
|
|
|
|
|
|
|
import (
|
|
|
|
"gosimplenpm/config"
|
|
|
|
"net/http"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
2023-06-17 22:41:07 +00:00
|
|
|
func AuthMiddleware(cfg config.Config) func(http.HandlerFunc) http.HandlerFunc {
|
2023-06-17 04:08:50 +00:00
|
|
|
return func(next http.HandlerFunc) http.HandlerFunc {
|
|
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
// get headers
|
|
|
|
authHeader := r.Header.Get("Authorization")
|
|
|
|
authFields := strings.Fields(authHeader)
|
|
|
|
if len(authFields) != 2 || strings.ToLower(authFields[0]) != "bearer" {
|
|
|
|
http.Error(w, "Authentication Error", http.StatusForbidden)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
token := authFields[1]
|
|
|
|
if token != cfg.Token {
|
|
|
|
http.Error(w, "Authentication Error", http.StatusForbidden)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
next(w, r)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|