github.com/greenpau/go-authcrunch@v1.1.4/pkg/redirects/redirect_match.go (about)

     1  // Copyright 2024 Paul Greenberg greenpau@outlook.com
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package redirects
    16  
    17  import (
    18  	"net/url"
    19  	"strings"
    20  )
    21  
    22  // Match matches HTTP URL to the bypass configuration.
    23  func Match(u *url.URL, cfgs []*RedirectURIMatchConfig) bool {
    24  	pathMatched := false
    25  	domainMatched := false
    26  
    27  	for _, cfg := range cfgs {
    28  		switch cfg.pathMatch {
    29  		case matchExact:
    30  			if cfg.Path == u.Path {
    31  				pathMatched = true
    32  			}
    33  		case matchPartial:
    34  			if strings.Contains(u.Path, cfg.Path) {
    35  				pathMatched = true
    36  			}
    37  		case matchPrefix:
    38  			if strings.HasPrefix(u.Path, cfg.Path) {
    39  				pathMatched = true
    40  			}
    41  		case matchSuffix:
    42  			if strings.HasSuffix(u.Path, cfg.Path) {
    43  				pathMatched = true
    44  			}
    45  		case matchRegex:
    46  			if cfg.pathRegex.MatchString(u.Path) {
    47  				pathMatched = true
    48  			}
    49  		}
    50  		if pathMatched {
    51  			break
    52  		}
    53  	}
    54  	if !pathMatched {
    55  		return false
    56  	}
    57  	for _, cfg := range cfgs {
    58  		switch cfg.domainMatch {
    59  		case matchExact:
    60  			if cfg.Domain == u.Host {
    61  				domainMatched = true
    62  			}
    63  		case matchPartial:
    64  			if strings.Contains(u.Host, cfg.Domain) {
    65  				domainMatched = true
    66  			}
    67  		case matchPrefix:
    68  			if strings.HasPrefix(u.Host, cfg.Domain) {
    69  				domainMatched = true
    70  			}
    71  		case matchSuffix:
    72  			if strings.HasSuffix(u.Host, cfg.Domain) {
    73  				domainMatched = true
    74  			}
    75  		case matchRegex:
    76  			if cfg.domainRegex.MatchString(u.Host) {
    77  				domainMatched = true
    78  			}
    79  		}
    80  		if domainMatched {
    81  			break
    82  		}
    83  	}
    84  	return domainMatched
    85  }