feat: now able to limit ip range for token now (close #1275)

This commit is contained in:
JustSong
2024-04-05 10:09:16 +08:00
parent f02c7138ea
commit c49778c254
10 changed files with 78 additions and 6 deletions

16
common/network/ip.go Normal file
View File

@@ -0,0 +1,16 @@
package network
import (
"context"
"github.com/songquanpeng/one-api/common/logger"
"net"
)
func IsIpInSubnet(ctx context.Context, ip string, subnet string) bool {
_, ipNet, err := net.ParseCIDR(subnet)
if err != nil {
logger.Errorf(ctx, "failed to parse subnet: %s, subnet: %s", err.Error(), subnet)
return false
}
return ipNet.Contains(net.ParseIP(ip))
}

19
common/network/ip_test.go Normal file
View File

@@ -0,0 +1,19 @@
package network
import (
"context"
"testing"
. "github.com/smartystreets/goconvey/convey"
)
func TestIsIpInSubnet(t *testing.T) {
ctx := context.Background()
ip1 := "192.168.0.5"
ip2 := "125.216.250.89"
subnet := "192.168.0.0/24"
Convey("TestIsIpInSubnet", t, func() {
So(IsIpInSubnet(ctx, ip1, subnet), ShouldBeTrue)
So(IsIpInSubnet(ctx, ip2, subnet), ShouldBeFalse)
})
}