Files
go-sms-V2/internal/api/http/v1/account_day22_test.go
T

160 lines
4.7 KiB
Go

package v1
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/gin-gonic/gin"
"github.com/glebarez/sqlite"
"gorm.io/gorm"
"go-sms/internal/middleware"
"go-sms/internal/model/entity"
"go-sms/internal/service/account"
)
const testSecret22 = "day22-secret"
// newAuthRouter 带 JWT+状态校验的路由(验收:禁用后 Token 失效)。
func newAuthRouter(t *testing.T) (*gin.Engine, *gorm.DB, *account.Service) {
t.Helper()
gin.SetMode(gin.TestMode)
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
if err != nil {
t.Fatal(err)
}
if err := db.AutoMigrate(&entity.AccountUser{}, &entity.AccountConfig{}, &entity.AccountBalanceLog{}, &entity.MessageDetail{}); err != nil {
t.Fatal(err)
}
svc := account.NewService(db, account.BcryptMinCost)
// 预置超管(id=1,鉴权/状态校验依赖其存在)
db.Exec("INSERT INTO account_user (username, password_hash, role, status) VALUES ('admin','x','admin',1)")
r := gin.New()
// Group 构造期挂中间件(确保先于 handler 执行)
rg := r.Group("/api/v1", middleware.AuthJWTWithChecker(testSecret22, svc.CheckEnabled))
Register(rg, Deps{Account: svc})
return r, db, svc
}
func doReq(r *gin.Engine, method, path, token string) *httptest.ResponseRecorder {
w := httptest.NewRecorder()
req := httptest.NewRequest(method, path, nil)
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
r.ServeHTTP(w, req)
return w
}
// TestAPI_ListPagedAndAuth 列表分页 + 鉴权拦截(Day 22 验收)。
func TestAPI_ListPagedAndAuth(t *testing.T) {
r, _, _ := newAuthRouter(t)
// 未带 Token:401
if w := doReq(r, http.MethodGet, "/api/v1/accounts", ""); w.Code != http.StatusUnauthorized {
t.Fatalf("无 Token 应 401, got %d", w.Code)
}
// 有效 Token:200 分页
tok, _ := middleware.SignAccessToken(testSecret22, 1, "admin", "admin", time.Hour)
w := doReq(r, http.MethodGet, "/api/v1/accounts?page=1&page_size=10", tok)
if w.Code != http.StatusOK {
t.Fatalf("列表应 200, got %d body=%s", w.Code, w.Body.String())
}
var page struct {
Code string `json:"code"`
Data struct {
Total int `json:"total"`
List []struct {
Username string `json:"username"`
} `json:"list"`
} `json:"data"`
}
_ = json.Unmarshal(w.Body.Bytes(), &page)
if page.Code != "ISC:000" {
t.Fatalf("响应码 = %s", page.Code)
}
}
// TestAPI_DisableInvalidatesToken 验收:禁用后 Token 立即失效(中间件级直测,
// 经 svc.CheckEnabled 真实 DB 状态;HTTP 全链由 e2e Day39 覆盖)。
func TestAPI_DisableInvalidatesToken(t *testing.T) {
_, db, svc := newAuthRouter(t)
ctx := context.Background()
u, err := svc.CreateAccount(ctx, &account.CreateAccountRequest{
Username: "victim", Password: "secret66", Role: "customer", Business: account.BusinessSMS,
})
if err != nil {
t.Fatal(err)
}
tok, _ := middleware.SignAccessToken(testSecret22, u.ID, "victim", "customer", time.Hour)
run := func() int {
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodGet, "/t", nil)
c.Request.Header.Set("Authorization", "Bearer "+tok)
middleware.AuthJWTWithChecker(testSecret22, svc.CheckEnabled)(c)
return w.Code
}
if code := run(); code != 200 {
t.Fatalf("禁用前应放行(200), got %d", code)
}
if err := svc.SetStatus(ctx, u.ID, 0); err != nil {
t.Fatal(err)
}
if code := run(); code != http.StatusUnauthorized {
t.Fatalf("禁用后应 401, got %d", code)
}
_ = db
}
func contains(s, sub string) bool {
return len(s) >= len(sub) && (func() bool {
for i := 0; i+len(sub) <= len(s); i++ {
if s[i:i+len(sub)] == sub {
return true
}
}
return false
})()
}
// TestAPI_DeleteActiveRejected 活跃账号删除业务拒绝(ISC:032)。
func TestAPI_DeleteActiveRejected(t *testing.T) {
r, db, svc := newAuthRouter(t)
ctx := context.Background()
u, _ := svc.CreateAccount(ctx, &account.CreateAccountRequest{
Username: "busy", Password: "secret66", Role: "customer", Business: account.BusinessSMS,
})
db.Create(&entity.MessageDetail{SnowflakeModel: entity.SnowflakeModel{ID: 7302}, AccountID: u.ID, Mobile: "13900139000"})
tok, _ := middleware.SignAccessToken(testSecret22, 1, "admin", "admin", time.Hour)
w := doReq(r, http.MethodDelete, "/api/v1/accounts/"+itoa(u.ID), tok)
if w.Code != http.StatusTooManyRequests { // SendLimited.HTTPStatus=429
t.Fatalf("活跃删除应 429, got %d body=%s", w.Code, w.Body.String())
}
if !contains(w.Body.String(), "ISC:032") {
t.Fatalf("应含 ISC:032: %s", w.Body.String())
}
}
func itoa(n int64) string {
if n == 0 {
return "0"
}
var b [20]byte
i := len(b)
for n > 0 {
i--
b[i] = byte('0' + n%10)
n /= 10
}
return string(b[i:])
}