2023-05-19 13:47:46 +00:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
2023-09-20 04:02:20 +00:00
|
|
|
"net"
|
2023-05-19 13:47:46 +00:00
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/1Panel-dev/1Panel/backend/app/api/v1/helper"
|
2023-06-01 02:38:11 +00:00
|
|
|
"github.com/1Panel-dev/1Panel/backend/app/repo"
|
2023-05-19 13:47:46 +00:00
|
|
|
"github.com/1Panel-dev/1Panel/backend/constant"
|
2023-09-20 04:02:20 +00:00
|
|
|
"github.com/1Panel-dev/1Panel/backend/global"
|
2023-05-19 13:47:46 +00:00
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
)
|
|
|
|
|
|
|
|
func WhiteAllow() gin.HandlerFunc {
|
|
|
|
return func(c *gin.Context) {
|
2023-06-01 02:38:11 +00:00
|
|
|
settingRepo := repo.NewISettingRepo()
|
|
|
|
status, err := settingRepo.Get(settingRepo.WithByKey("AllowIPs"))
|
|
|
|
if err != nil {
|
2023-06-25 03:50:13 +00:00
|
|
|
helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err)
|
2023-06-01 02:38:11 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(status.Value) == 0 {
|
2023-05-19 13:47:46 +00:00
|
|
|
c.Next()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
clientIP := c.ClientIP()
|
2023-06-01 02:38:11 +00:00
|
|
|
for _, ip := range strings.Split(status.Value, ",") {
|
2023-09-20 04:02:20 +00:00
|
|
|
if len(ip) == 0 {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
if ip == clientIP || (strings.Contains(ip, "/") && checkIpInCidr(ip, clientIP)) {
|
2023-05-19 13:47:46 +00:00
|
|
|
c.Next()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
helper.ErrorWithDetail(c, constant.CodeErrIP, constant.ErrTypeInternalServer, errors.New("IP address not allowed"))
|
|
|
|
}
|
|
|
|
}
|
2023-09-20 04:02:20 +00: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
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|