github.com/hellofresh/janus@v0.0.0-20230925145208-ce8de8183c67/pkg/plugin/basic/middleware.go (about) 1 package basic 2 3 import ( 4 "github.com/hellofresh/janus/pkg/plugin/basic/encrypt" 5 "net/http" 6 7 "github.com/hellofresh/janus/pkg/errors" 8 log "github.com/sirupsen/logrus" 9 ) 10 11 // NewBasicAuth is a HTTP basic auth middleware 12 func NewBasicAuth(repo Repository) func(http.Handler) http.Handler { 13 return func(handler http.Handler) http.Handler { 14 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 15 log.Debug("Starting basic auth middleware") 16 logger := log.WithFields(log.Fields{ 17 "path": r.RequestURI, 18 "origin": r.RemoteAddr, 19 }) 20 21 username, password, authOK := r.BasicAuth() 22 if !authOK { 23 errors.Handler(w, r, ErrNotAuthorized) 24 return 25 } 26 27 var found bool 28 users, err := repo.FindAll() 29 if err != nil { 30 log.WithError(err).Error("Error when getting all users") 31 errors.Handler(w, r, errors.New(http.StatusInternalServerError, "there was an error when looking for users")) 32 return 33 } 34 35 hash := encrypt.Hash{} 36 37 for _, u := range users { 38 //if username == u.Username && (subtle.ConstantTimeCompare([]byte(password), []byte(u.Password)) == 1) { 39 if username == u.Username && (hash.Compare(u.Password, password) == nil) { 40 found = true 41 break 42 } 43 } 44 45 if !found { 46 logger.Debug("Invalid user/password provided.") 47 errors.Handler(w, r, ErrNotAuthorized) 48 return 49 } 50 51 handler.ServeHTTP(w, r) 52 }) 53 } 54 }