feat(t226): add Go ERP session login

This commit is contained in:
QiuSW
2026-07-29 09:51:41 +08:00
parent c2f340d067
commit a5a61c05d0
23 changed files with 1633 additions and 33 deletions
@@ -11,6 +11,7 @@ import (
"time"
"cmroubao/backend-api/internal/domain"
"cmroubao/backend-api/internal/platform/shunyunbao"
"cmroubao/backend-api/internal/transport/authcommon"
"cmroubao/backend-api/internal/usecase"
@@ -30,6 +31,7 @@ type AdminServices struct {
Authorizations *usecase.OrderAuthorizationService
Freight *usecase.FreightService
Procurement *usecase.ProcurementService
ERP *shunyunbao.SessionManager
}
func (s AdminServices) validate() error {
@@ -87,6 +89,9 @@ func registerAdminAPI(routes gin.IRoutes, services AdminServices) error {
handler.createProcurementTask,
)
}
if services.ERP != nil {
registerERPAdminAPI(routes, handler)
}
return nil
}
@@ -23,6 +23,7 @@ import (
"cmroubao/backend-api/internal/platform/assetstore"
"cmroubao/backend-api/internal/platform/database"
"cmroubao/backend-api/internal/platform/migration"
"cmroubao/backend-api/internal/platform/shunyunbao"
repository "cmroubao/backend-api/internal/repository/sqlite"
"cmroubao/backend-api/internal/usecase"
@@ -60,6 +61,100 @@ func TestCandidateDecisionDatasetResponseIncludesPersistentIdentity(t *testing.T
}
}
func TestERPAdminAPIUsesCaptchaTicketWithoutExposingCredentials(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(
writer http.ResponseWriter,
request *http.Request,
) {
switch request.URL.Path {
case shunyunbao.CaptchaPath:
http.SetCookie(writer, &http.Cookie{Name: "erp", Value: "captcha", Path: "/"})
writer.Header().Set("Content-Type", "image/png")
_, _ = writer.Write([]byte("captcha-image"))
case shunyunbao.LoginPath:
if _, err := request.Cookie("erp"); err != nil {
t.Fatalf("login did not retain captcha cookie: %v", err)
}
http.SetCookie(writer, &http.Cookie{Name: "erp", Value: "login", Path: "/"})
_, _ = writer.Write([]byte(`{"status":true,"data":{"user":{"id":12},"token":"private-token"}}`))
case shunyunbao.UserPath:
if cookie, err := request.Cookie("erp"); err != nil || cookie.Value != "login" {
t.Fatalf("user session cookie = %v / %v", cookie, err)
}
_, _ = writer.Write([]byte(`{"status":true,"data":{"id":12}}`))
default:
writer.WriteHeader(http.StatusNotFound)
}
}))
defer server.Close()
manager, err := shunyunbao.NewSessionManager(shunyunbao.SessionConfig{
BaseURL: server.URL,
Username: "private-user",
Password: "private-password",
Timeout: time.Second,
AllowInsecureHTTP: true,
})
if err != nil {
t.Fatalf("NewSessionManager() error = %v", err)
}
gin.SetMode(gin.TestMode)
router := gin.New()
registerERPAdminAPI(router, &adminHandlers{services: AdminServices{ERP: manager}})
status := performERPRequest(t, router, http.MethodGet, "/api/v1/erp-session", nil, "")
if status.Code != http.StatusOK ||
strings.Contains(status.Body.String(), "private-user") ||
strings.Contains(status.Body.String(), "private-password") {
t.Fatalf("status response = %d / %s", status.Code, status.Body)
}
captcha := performERPRequest(
t,
router,
http.MethodPost,
"/api/v1/erp-session/captcha",
nil,
"",
)
if captcha.Code != http.StatusOK ||
strings.Contains(captcha.Body.String(), "private-password") {
t.Fatalf("captcha response = %d / %s", captcha.Code, captcha.Body)
}
var captchaBody map[string]any
decodeResponse(t, captcha, &captchaBody)
ticket, _ := captchaBody["captcha_ticket"].(string)
if len(ticket) != 43 || responseContainsKey(captchaBody["session"], "captcha_ticket") {
t.Fatalf("captcha response body = %#v", captchaBody)
}
image := performERPRequest(
t,
router,
http.MethodGet,
"/api/v1/erp-session/captcha/"+ticket,
nil,
"",
)
if image.Code != http.StatusOK || image.Header().Get("Cache-Control") != "no-store" ||
image.Body.String() != "captcha-image" {
t.Fatalf("captcha image = %d / %q / %s", image.Code, image.Header(), image.Body)
}
login := performERPRequest(
t,
router,
http.MethodPost,
"/api/v1/erp-session/login",
strings.NewReader(`{"captcha_ticket":"`+ticket+`","captcha_code":"1234"}`),
"application/json",
)
if login.Code != http.StatusOK ||
strings.Contains(login.Body.String(), "private-token") ||
strings.Contains(login.Body.String(), "private-password") {
t.Fatalf("login response = %d / %s", login.Code, login.Body)
}
if !strings.Contains(login.Body.String(), `"authenticated":true`) {
t.Fatalf("login does not report authenticated state: %s", login.Body)
}
}
func TestAdminAPIAssetAndTaskLifecycle(t *testing.T) {
router := newAdminIntegrationRouter(t)
imageBody, imageContentType := referenceUpload(t, "asset-key-1")
@@ -1306,6 +1401,23 @@ func performAdminRequest(
return response
}
func performERPRequest(
t *testing.T,
router http.Handler,
method, target string,
body io.Reader,
contentType string,
) *httptest.ResponseRecorder {
t.Helper()
request := httptest.NewRequest(method, target, body)
if contentType != "" {
request.Header.Set("Content-Type", contentType)
}
response := httptest.NewRecorder()
router.ServeHTTP(response, request)
return response
}
func decodeResponse(
t *testing.T,
response *httptest.ResponseRecorder,
@@ -233,7 +233,8 @@ func denyAdminSession(ctx *gin.Context) {
(next != "/tasks" && !strings.HasPrefix(next, "/tasks?") &&
!strings.HasPrefix(next, "/tasks/") &&
next != "/freight" && !strings.HasPrefix(next, "/freight?") &&
!strings.HasPrefix(next, "/freight/")) {
!strings.HasPrefix(next, "/freight/") &&
next != "/erp" && !strings.HasPrefix(next, "/erp?")) {
next = "/tasks"
}
ctx.Abort()
@@ -0,0 +1,166 @@
package httpapi
import (
"errors"
"net/http"
"strconv"
"strings"
"unicode/utf8"
"cmroubao/backend-api/internal/domain"
"cmroubao/backend-api/internal/platform/shunyunbao"
"github.com/gin-gonic/gin"
)
func registerERPAdminAPI(routes gin.IRoutes, handler *adminHandlers) {
routes.GET("/api/v1/erp-session", handler.erpSessionStatus)
routes.POST("/api/v1/erp-session/captcha", handler.createERPCaptcha)
routes.GET(
"/api/v1/erp-session/captcha/:ticket",
handler.erpCaptchaContent,
)
routes.POST("/api/v1/erp-session/login", handler.loginERP)
}
func (h *adminHandlers) erpSessionStatus(ctx *gin.Context) {
ctx.Header("Cache-Control", "no-store")
ctx.JSON(http.StatusOK, erpSessionResponse(h.services.ERP.Status()))
}
func (h *adminHandlers) createERPCaptcha(ctx *gin.Context) {
status, err := h.services.ERP.FetchCaptcha(ctx.Request.Context())
if err != nil {
writeERPError(ctx, err)
return
}
ctx.Header("Cache-Control", "no-store")
ctx.JSON(http.StatusOK, gin.H{
"session": erpSessionResponse(status),
"captcha_ticket": status.CaptchaTicket,
"captcha_url": "/api/v1/erp-session/captcha/" + status.CaptchaTicket,
})
}
func (h *adminHandlers) erpCaptchaContent(ctx *gin.Context) {
ticket := strings.TrimSpace(ctx.Param("ticket"))
if !validERPTicket(ticket) {
writeERPError(ctx, shunyunbao.ErrCaptchaTicketInvalid)
return
}
image, err := h.services.ERP.OpenCaptcha(ticket)
if err != nil || !strings.HasPrefix(image.ContentType, "image/") ||
len(image.Content) == 0 {
writeERPError(ctx, err)
return
}
ctx.Header("Cache-Control", "no-store")
ctx.Header("Content-Type", image.ContentType)
ctx.Header("Content-Length", strconv.Itoa(len(image.Content)))
ctx.Header("Content-Disposition", "inline")
ctx.Data(http.StatusOK, image.ContentType, image.Content)
}
func (h *adminHandlers) loginERP(ctx *gin.Context) {
if !hasMediaType(ctx, "application/json") {
writePublicError(
ctx,
http.StatusUnsupportedMediaType,
"UNSUPPORTED_MEDIA_TYPE",
"application/json is required",
false,
gin.H{},
)
return
}
var request struct {
CaptchaTicket string `json:"captcha_ticket"`
CaptchaCode string `json:"captcha_code"`
}
if err := decodeJSON(ctx, &request); err != nil ||
!validERPTicket(request.CaptchaTicket) ||
!validERPCaptchaCode(request.CaptchaCode) {
writePublicError(
ctx,
http.StatusBadRequest,
"ERP_LOGIN_INVALID",
"ERP login request is invalid",
false,
gin.H{},
)
return
}
status, err := h.services.ERP.Login(
ctx.Request.Context(),
request.CaptchaTicket,
request.CaptchaCode,
)
if err != nil {
writeERPError(ctx, err)
return
}
ctx.Header("Cache-Control", "no-store")
ctx.JSON(http.StatusOK, erpSessionResponse(status))
}
func erpSessionResponse(status shunyunbao.SessionStatus) gin.H {
return gin.H{
"configured": status.Configured,
"authenticated": status.Authenticated,
"captcha_ready": status.CaptchaReady,
}
}
func validERPTicket(value string) bool {
value = strings.TrimSpace(value)
return len(value) == 43 && utf8.ValidString(value) &&
!strings.ContainsAny(value, " \t\r\n")
}
func validERPCaptchaCode(value string) bool {
value = strings.TrimSpace(value)
if value == "" || len([]byte(value)) > 64 || !utf8.ValidString(value) {
return false
}
for _, character := range value {
if character < 32 || character == 127 {
return false
}
}
return true
}
func writeERPError(ctx *gin.Context, err error) {
status := http.StatusInternalServerError
code := "ERP_INTERNAL_ERROR"
message := "ERP connection operation failed"
retryable := false
switch {
case errors.Is(err, domain.ErrFreightSourceNotConfigured):
status = http.StatusUnprocessableEntity
code = "ERP_NOT_CONFIGURED"
message = "ERP credentials are not configured"
case errors.Is(err, domain.ErrFreightSourceSessionNeeded):
status = http.StatusConflict
code = "ERP_SESSION_REQUIRED"
message = "ERP session is required"
case errors.Is(err, shunyunbao.ErrCaptchaTicketInvalid):
status = http.StatusConflict
code = "ERP_CAPTCHA_INVALID"
message = "ERP captcha must be requested again"
case errors.Is(err, shunyunbao.ErrLoginRejected):
status = http.StatusUnprocessableEntity
code = "ERP_LOGIN_REJECTED"
message = "ERP login was rejected"
case errors.Is(err, domain.ErrFreightSourceProtocol):
status = http.StatusBadGateway
code = "ERP_RESPONSE_INVALID"
message = "ERP response is invalid"
case errors.Is(err, domain.ErrFreightSourceUnavailable):
status = http.StatusServiceUnavailable
code = "ERP_UNAVAILABLE"
message = "ERP is temporarily unavailable"
retryable = true
}
writePublicError(ctx, status, code, message, retryable, gin.H{})
}