Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added as simple callback with the filter object so it can be dynamically changed #85

Merged
merged 2 commits into from
Aug 16, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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