29 lines
691 B
Go
29 lines
691 B
Go
package middlewares
|
|
|
|
import (
|
|
"gosimplenpm/config"
|
|
"net/http"
|
|
"strings"
|
|
)
|
|
|
|
func AuthMiddleware(cfg config.Config) func(http.HandlerFunc) http.HandlerFunc {
|
|
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)
|
|
}
|
|
}
|
|
}
|