package middlewares import ( "net/http" "path" "strings" "git.secnex.io/secnex/api-gateway/config" "git.secnex.io/secnex/api-gateway/res" "git.secnex.io/secnex/masterlog" ) func authPathMatches(pattern, requestPath string) bool { if pattern == "*" { return true } if pattern == requestPath { return true } if strings.Contains(pattern, "*") { matched, _ := path.Match(pattern, requestPath) return matched } return false } func Auth(next http.Handler, authType string, authHeader string, authPath config.AuthPathConfiguration) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { masterlog.Debug("Auth middleware", map[string]interface{}{ "path": r.URL.Path, "include": authPath.Include, "exclude": authPath.Exclude, }) if len(authPath.Include) > 0 { matched := false for _, include := range authPath.Include { if authPathMatches(include, r.URL.Path) { matched = true break } } if !matched { next.ServeHTTP(w, r) return } } else { for _, exclude := range authPath.Exclude { if authPathMatches(exclude, r.URL.Path) { next.ServeHTTP(w, r) return } } } if r.Header.Get(authHeader) == "" { res.Unauthorized(w) return } r.Header.Del(authHeader) next.ServeHTTP(w, r) }) }