2023-05-19 21:47:46 +08:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
2024-06-04 22:29:05 +08:00
|
|
|
"errors"
|
2023-09-20 12:02:20 +08:00
|
|
|
"net"
|
2023-05-19 21:47:46 +08:00
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/1Panel-dev/1Panel/backend/app/api/v1/helper"
|
2023-06-01 10:38:11 +08:00
|
|
|
"github.com/1Panel-dev/1Panel/backend/app/repo"
|
2023-05-19 21:47:46 +08:00
|
|
|
"github.com/1Panel-dev/1Panel/backend/constant"
|
2023-09-20 12:02:20 +08:00
|
|
|
"github.com/1Panel-dev/1Panel/backend/global"
|
2023-05-19 21:47:46 +08:00
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
)
|
|
|
|
|
|
|
|
func WhiteAllow() gin.HandlerFunc {
|
|
|
|
return func(c *gin.Context) {
|
2023-06-01 10:38:11 +08:00
|
|
|
settingRepo := repo.NewISettingRepo()
|
|
|
|
status, err := settingRepo.Get(settingRepo.WithByKey("AllowIPs"))
|
|
|
|
if err != nil {
|
2023-06-25 11:50:13 +08:00
|
|
|
helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err)
|
2023-06-01 10:38:11 +08:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(status.Value) == 0 {
|
2023-05-19 21:47:46 +08:00
|
|
|
c.Next()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
clientIP := c.ClientIP()
|
2023-06-01 10:38:11 +08:00
|
|
|
for _, ip := range strings.Split(status.Value, ",") {
|
2023-09-20 12:02:20 +08:00
|
|
|
if len(ip) == 0 {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
if ip == clientIP || (strings.Contains(ip, "/") && checkIpInCidr(ip, clientIP)) {
|
2023-05-19 21:47:46 +08:00
|
|
|
c.Next()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
2024-06-04 22:29:05 +08:00
|
|
|
if LoadErrCode("err-ip") != 200 {
|
|
|
|
helper.ErrResponse(c, LoadErrCode("err-ip"))
|
|
|
|
return
|
|
|
|
}
|
|
|
|
helper.ErrorWithDetail(c, constant.CodeErrIP, constant.ErrTypeInternalServer, errors.New("IP address not allowed"))
|
2023-05-19 21:47:46 +08:00
|
|
|
}
|
|
|
|
}
|
2023-09-20 12:02:20 +08:00
|
|
|
|
|
|
|
func checkIpInCidr(cidr, checkIP string) bool {
|
|
|
|
ip, ipNet, err := net.ParseCIDR(cidr)
|
|
|
|
if err != nil {
|
|
|
|
global.LOG.Errorf("parse CIDR %s failed, err: %v", cidr, err)
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
for ip := ip.Mask(ipNet.Mask); ipNet.Contains(ip); incIP(ip) {
|
|
|
|
if ip.String() == checkIP {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
func incIP(ip net.IP) {
|
|
|
|
for j := len(ip) - 1; j >= 0; j-- {
|
|
|
|
ip[j]++
|
|
|
|
if ip[j] > 0 {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|