统一密码重置请求解析并修复JSON提示
This commit is contained in:
parent
fb8e6217b9
commit
f74c8f1f24
@ -9,10 +9,10 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// bindJSON ???? JSON ?????????????????? JSON?
|
||||
// bindJSON 严格解析 JSON 请求,并拒绝未知字段和多段 JSON。
|
||||
func bindJSON(c *gin.Context, target any, limit int64) error {
|
||||
if c == nil || c.Request == nil || c.Request.Body == nil {
|
||||
return errors.New("???????")
|
||||
return errors.New("请求上下文或请求体为空")
|
||||
}
|
||||
if limit > 0 {
|
||||
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, limit)
|
||||
@ -24,7 +24,7 @@ func bindJSON(c *gin.Context, target any, limit int64) error {
|
||||
}
|
||||
if err := decoder.Decode(&struct{}{}); err != io.EOF {
|
||||
if err == nil {
|
||||
return errors.New("????????? JSON ??")
|
||||
return errors.New("请求体包含多段 JSON 数据")
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
@ -1,7 +1,6 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@ -27,11 +26,8 @@ type passwordResetResolution struct {
|
||||
|
||||
// resolvePasswordResetAccount 根据账户标识返回对应的密码处理内容。
|
||||
func (s *Server) resolvePasswordResetAccount(c *gin.Context) {
|
||||
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, passwordResetResolveBodyLimit)
|
||||
var request passwordResetResolveRequest
|
||||
decoder := json.NewDecoder(c.Request.Body)
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(&request); err != nil {
|
||||
if err := bindJSON(c, &request, passwordResetResolveBodyLimit); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "账户信息格式无效"})
|
||||
return
|
||||
}
|
||||
|
||||
27
backend/internal/httpapi/password_reset_account_test.go
Normal file
27
backend/internal/httpapi/password_reset_account_test.go
Normal file
@ -0,0 +1,27 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/config"
|
||||
)
|
||||
|
||||
func TestPasswordResetResolutionRejectsTrailingJSON(t *testing.T) {
|
||||
server := New(Dependencies{Config: config.Default(t.TempDir()), Repository: &stubDomainRepository{}})
|
||||
tests := []string{
|
||||
`{"identifier":"admin","unexpected":true}`,
|
||||
`{"identifier":"admin"}{"identifier":"again"}`,
|
||||
}
|
||||
for _, body := range tests {
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/password-reset/resolve", strings.NewReader(body))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
if response.Code != http.StatusBadRequest {
|
||||
t.Fatalf("无效密码重置请求应返回 400,实际为 %d:%s", response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user