aboutsummaryrefslogtreecommitdiff
path: root/echo/middleware/ip_filter.go
blob: 007791e7841543d3112e4517b8256bad6c853c57 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package middleware

import (
	"net"

	"github.com/labstack/echo/v4"
)

func NewIPFilter(allowedRanges []*net.IPNet) echo.MiddlewareFunc {
	return func(next echo.HandlerFunc) echo.HandlerFunc {
		return func(c echo.Context) error {
			if allowedRanges == nil {
				c.Logger().Error("No allowed IPs configured for filter")
				return echo.ErrNotFound
			}

			ip := net.ParseIP(c.RealIP())
			if ip == nil {
				c.Logger().Error("Unable to parse IP in IPFilter")
				return echo.ErrNotFound
			}

			found := false
			for _, ipnet := range allowedRanges {
				if ipnet.Contains(ip) {
					found = true
					break
				}
			}

			if !found {
				c.Logger().Errorf("IP %s not in range for filter", c.RealIP())
				return echo.ErrNotFound
			}

			return next(c)
		}
	}
}