添加全局验证器,优化白名单创建请求的参数验证
This commit is contained in:
@@ -1,8 +1,10 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net"
|
||||
"platform/web/auth"
|
||||
"platform/web/common"
|
||||
g "platform/web/globals"
|
||||
m "platform/web/models"
|
||||
q "platform/web/queries"
|
||||
"platform/web/services"
|
||||
@@ -69,8 +71,8 @@ func ListWhitelist(c *fiber.Ctx) error {
|
||||
}
|
||||
|
||||
type CreateWhitelistReq struct {
|
||||
Host string `json:"host" validate:"required"`
|
||||
Remark string `json:"remark"`
|
||||
Host string `json:"host" validate:"required,ip"`
|
||||
Remark string `json:"remark,omitempty"`
|
||||
}
|
||||
|
||||
func CreateWhitelist(c *fiber.Ctx) error {
|
||||
@@ -83,21 +85,22 @@ func CreateWhitelist(c *fiber.Ctx) error {
|
||||
|
||||
// 解析请求参数
|
||||
req := new(CreateWhitelistReq)
|
||||
if err := c.BodyParser(req); err != nil {
|
||||
err = g.Validator.Validate(c, req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if req.Host == "" {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "host is required")
|
||||
|
||||
err = secureAddr(req.Host)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 创建白名单
|
||||
whitelist := &m.Whitelist{
|
||||
err = q.Whitelist.Create(&m.Whitelist{
|
||||
UserID: authContext.Payload.Id,
|
||||
Host: req.Host,
|
||||
Remark: req.Remark,
|
||||
}
|
||||
|
||||
err = q.Whitelist.Create(whitelist)
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -183,3 +186,15 @@ func RemoveWhitelist(c *fiber.Ctx) error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func secureAddr(str string) error {
|
||||
var addr = net.ParseIP(str)
|
||||
if addr == nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "IP 解析失败")
|
||||
}
|
||||
|
||||
if addr.IsGlobalUnicast() {
|
||||
return nil
|
||||
}
|
||||
return fiber.NewError(fiber.StatusBadRequest, "IP 地址不可用")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user