diff options
Diffstat (limited to 'echo/middleware/ip_filter.go')
-rw-r--r-- | echo/middleware/ip_filter.go | 39 |
1 files changed, 39 insertions, 0 deletions
diff --git a/echo/middleware/ip_filter.go b/echo/middleware/ip_filter.go new file mode 100644 index 0000000..007791e --- /dev/null +++ b/echo/middleware/ip_filter.go | |||
@@ -0,0 +1,39 @@ | |||
1 | package middleware | ||
2 | |||
3 | import ( | ||
4 | "net" | ||
5 | |||
6 | "github.com/labstack/echo/v4" | ||
7 | ) | ||
8 | |||
9 | func NewIPFilter(allowedRanges []*net.IPNet) echo.MiddlewareFunc { | ||
10 | return func(next echo.HandlerFunc) echo.HandlerFunc { | ||
11 | return func(c echo.Context) error { | ||
12 | if allowedRanges == nil { | ||
13 | c.Logger().Error("No allowed IPs configured for filter") | ||
14 | return echo.ErrNotFound | ||
15 | } | ||
16 | |||
17 | ip := net.ParseIP(c.RealIP()) | ||
18 | if ip == nil { | ||
19 | c.Logger().Error("Unable to parse IP in IPFilter") | ||
20 | return echo.ErrNotFound | ||
21 | } | ||
22 | |||
23 | found := false | ||
24 | for _, ipnet := range allowedRanges { | ||
25 | if ipnet.Contains(ip) { | ||
26 | found = true | ||
27 | break | ||
28 | } | ||
29 | } | ||
30 | |||
31 | if !found { | ||
32 | c.Logger().Errorf("IP %s not in range for filter", c.RealIP()) | ||
33 | return echo.ErrNotFound | ||
34 | } | ||
35 | |||
36 | return next(c) | ||
37 | } | ||
38 | } | ||
39 | } | ||