82 lines
2.6 KiB
Go
82 lines
2.6 KiB
Go
package clientapi
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"github.com/gin-gonic/gin"
|
|
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
|
|
"go-admin/app/goauto/clientkey"
|
|
"go-admin/app/goauto/models"
|
|
"go-admin/app/goauto/product"
|
|
"go-admin/common/middleware"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
)
|
|
|
|
func TestClientCanCreateProductWithoutLoginAndReplay(t *testing.T) {
|
|
db, s := fixture(t)
|
|
if err := db.AutoMigrate(&models.PDDProduct{}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
_, token, err := s.Create(context.Background(), "test", []clientkey.Grant{{Module: "pdd_products", Write: true}}, 1)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
e := Endpoint{Method: "POST", Path: "/pdd-products", Module: "pdd_products", Capability: "write"}
|
|
router := gin.New()
|
|
router.Use(func(c *gin.Context) { c.Set("db", db); c.Next() })
|
|
router.POST("/api/client/v1/pdd-products", Gate(db, e), product.Handler{}.Create)
|
|
for n := 0; n < 2; n++ {
|
|
req := httptest.NewRequest("POST", "https://example.test/api/client/v1/pdd-products", strings.NewReader(`{"requestId":"00000000-0000-4000-8000-000000000237","url":"https://mobile.yangkeduo.com/goods.html?goods_id=100000000001"}`))
|
|
req.Header.Set("Authorization", "Bearer "+token)
|
|
rr := httptest.NewRecorder()
|
|
router.ServeHTTP(rr, req)
|
|
if rr.Code != 200 {
|
|
t.Fatalf("product create failed status %d", rr.Code)
|
|
}
|
|
var body struct {
|
|
Data struct {
|
|
Replayed bool `json:"replayed"`
|
|
}
|
|
}
|
|
json.Unmarshal(rr.Body.Bytes(), &body)
|
|
if (n == 1) != body.Data.Replayed {
|
|
t.Fatal("business idempotency changed")
|
|
}
|
|
}
|
|
var count int64
|
|
db.Model(&models.PDDProduct{}).Count(&count)
|
|
if count != 1 {
|
|
t.Fatal("duplicate business write")
|
|
}
|
|
}
|
|
|
|
func TestManagementRequiresAdminNotClientIdentity(t *testing.T) {
|
|
db, s := fixture(t)
|
|
h := clientkey.Handler{DB: db, Modules: s.Modules}
|
|
for _, role := range []string{"admin", "purchaser", "client", ""} {
|
|
for _, scheme := range []string{"http", "https"} {
|
|
router := gin.New()
|
|
router.Use(func(c *gin.Context) {
|
|
c.Set(jwt.JwtPayloadKey, jwt.MapClaims{"rolekey": role, "identity": float64(7)})
|
|
c.Next()
|
|
})
|
|
router.POST("/keys", middleware.RequireRoleKey("admin"), NoStore, h.Create)
|
|
req := httptest.NewRequest("POST", scheme+"://example.test/keys", strings.NewReader(`{"name":"test","grants":[{"module":"pdd_products","write":false,"actions":[]}]}`))
|
|
rr := httptest.NewRecorder()
|
|
router.ServeHTTP(rr, req)
|
|
want := 403
|
|
if role == "admin" {
|
|
want = 200
|
|
}
|
|
if rr.Code != want {
|
|
t.Fatalf("role %q status %d", role, rr.Code)
|
|
}
|
|
if role == "admin" && rr.Header().Get("Cache-Control") != "no-store" {
|
|
t.Fatal("one-time secret cacheable")
|
|
}
|
|
}
|
|
}
|
|
}
|