gosimplenpm/middlewares/auth.go

56 lines
1.4 KiB
Go
Raw Normal View History

package middlewares
import (
"gosimplenpm/config"
"net/http"
"strings"
)
func AuthMiddleware(cfg config.Config) Middleware {
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)
}
}
}
// func AuthMiddleware(next http.HandlerFunc) http.HandlerFunc {
// return func(w http.ResponseWriter, r *http.Request) {
// if cfg == nil {
// log.Println("Config load error")
// http.Error(w, "Config load error", http.StatusInternalServerError)
// return
// }
// log.Println("Config was loaded")
// // 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
// }
// fmt.Println("Authorized")
// next(w, r)
// }
// }