|
| 1 | +// Copyright 2024 The casbin Authors. All Rights Reserved. |
| 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 rule |
| 16 | + |
| 17 | +import ( |
| 18 | + "fmt" |
| 19 | + "net/http" |
| 20 | + "regexp" |
| 21 | + "strings" |
| 22 | + |
| 23 | + "github.com/casbin/caswaf/object" |
| 24 | +) |
| 25 | + |
| 26 | +type UrlPathRule struct{} |
| 27 | + |
| 28 | +func (r *UrlPathRule) checkRule(expressions []*object.Expression, req *http.Request) (*RuleResult, error) { |
| 29 | + path := req.URL.Path |
| 30 | + for _, expression := range expressions { |
| 31 | + pattern := expression.Value |
| 32 | + reason := fmt.Sprintf("expression matched: \"%s %s %s\"", path, expression.Operator, expression.Value) |
| 33 | + switch expression.Operator { |
| 34 | + case "contains": |
| 35 | + if strings.Contains(path, pattern) { |
| 36 | + return &RuleResult{Reason: reason}, nil |
| 37 | + } |
| 38 | + case "does not contain": |
| 39 | + if !strings.Contains(path, pattern) { |
| 40 | + return &RuleResult{Reason: reason}, nil |
| 41 | + } |
| 42 | + case "equals": |
| 43 | + if path == pattern { |
| 44 | + return &RuleResult{Reason: reason}, nil |
| 45 | + } |
| 46 | + case "does not equal": |
| 47 | + if strings.Compare(path, pattern) != 0 { |
| 48 | + return &RuleResult{Reason: reason}, nil |
| 49 | + } |
| 50 | + case "match": |
| 51 | + isHit, err := regexp.MatchString(pattern, path) |
| 52 | + if err != nil { |
| 53 | + return nil, err |
| 54 | + } |
| 55 | + if isHit { |
| 56 | + return &RuleResult{Reason: reason}, nil |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + return nil, nil |
| 62 | +} |
0 commit comments