Skip to content

Commit

Permalink
Merge pull request #85 from shmul/dynamic-filter
Browse files Browse the repository at this point in the history
Added as simple callback with the filter object so it can be dynamically changed
  • Loading branch information
crazy-max authored Aug 16, 2023
2 parents 4b7dcb1 + bf221e9 commit fc52437
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
9 changes: 8 additions & 1 deletion ipfilter.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,11 @@ type Config struct {

// Block by default.
BlockByDefault bool

// called with the newly created filter object to allow for
// controlling the filter during runtime.
// The underlying filter implementation is thankfully threadsafe
CreatedFilter func(*ipfilter.IPFilter)
}

// DefaultConfig is the default IPFilter middleware config
Expand Down Expand Up @@ -55,7 +60,9 @@ func MiddlewareWithConfig(config Config) echo.MiddlewareFunc {
BlockByDefault: config.BlockByDefault,
Logger: nil,
})

if config.CreatedFilter != nil {
config.CreatedFilter(filter)
}
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if config.Skipper(c) {
Expand Down
31 changes: 31 additions & 0 deletions ipfilter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"testing"

ipfilter "github.com/crazy-max/echo-ipfilter"
jpillorafilter "github.com/jpillora/ipfilter"
"github.com/labstack/echo/v4"
)

Expand Down Expand Up @@ -94,6 +95,36 @@ func TestMiddlewareWithConfig(t *testing.T) {
ip: "10.1.4.1:80",
err: nil,
},
{
name: "dynamically allowed by whitelist",
config: ipfilter.Config{
WhiteList: []string{
"10.1.2.0/24",
// this will be dynamically added "10.1.4.0/24",
},
BlockByDefault: true,
CreatedFilter: func(filter *jpillorafilter.IPFilter) {
filter.AllowIP("10.1.4.0/24")
},
},
ip: "10.1.4.1:80",
err: nil,
},
{
name: "dynamically allowed by whitelist",
config: ipfilter.Config{
WhiteList: []string{
"10.1.2.0/24", // will be dynamicaly blocked
"10.1.4.0/24",
},
BlockByDefault: true,
CreatedFilter: func(filter *jpillorafilter.IPFilter) {
filter.BlockIP("10.1.2.0/24")
},
},
ip: "10.1.2.7:80",
err: echo.NewHTTPError(http.StatusForbidden, fmt.Sprintf("IP address %s not allowed", "10.1.2.7")),
},
}

for _, tt := range cases {
Expand Down

0 comments on commit fc52437

Please sign in to comment.