github.com/greenpau/go-authcrunch@v1.1.4/pkg/acl/path.go (about)

     1  // Copyright 2022 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 acl
    16  
    17  import (
    18  	"regexp"
    19  	"strings"
    20  )
    21  
    22  var pathACLPatterns map[string]*regexp.Regexp
    23  
    24  func init() {
    25  	pathACLPatterns = make(map[string]*regexp.Regexp)
    26  }
    27  
    28  // MatchPathBasedACL matches pattern in a URI.
    29  func MatchPathBasedACL(pattern, uri string) bool {
    30  	// First, handle the case where there are no wildcards
    31  	if pattern == "" {
    32  		return false
    33  	}
    34  	if !strings.Contains(pattern, "*") {
    35  		if pattern == uri {
    36  			return true
    37  		}
    38  		return false
    39  	}
    40  
    41  	// Next, handle the case where wildcards are present
    42  	var regex *regexp.Regexp
    43  	var found bool
    44  
    45  	// Check cached entries
    46  	regex, found = pathACLPatterns[pattern]
    47  	if !found {
    48  		// advPattern = strings.ReplaceAll(pattern, "/", "\\/")
    49  		advPattern := strings.ReplaceAll(pattern, "**", "[a-zA-Z0-9_/.~-]+")
    50  		advPattern = strings.ReplaceAll(advPattern, "*", "[a-zA-Z0-9_.~-]+")
    51  		advPattern = "^" + advPattern + "$"
    52  		r, err := regexp.Compile(advPattern)
    53  		if err != nil {
    54  			pathACLPatterns[pattern] = nil
    55  			return false
    56  		}
    57  		pathACLPatterns[pattern] = r
    58  		regex = r
    59  	}
    60  	if regex == nil {
    61  		return false
    62  	}
    63  
    64  	return regex.MatchString(uri)
    65  }