✅ 已完成功能: - 后端 Go 服务 (认证/授权/检测) - JWT 认证 + RBAC 权限控制 - 登录速率限制 (5 次失败锁定 15 分钟) - 密码强度校验 - 敏感数据脱敏 - Vue3 管理后台 - 路由守卫 - 删除二次确认 📦 部署配置: - Docker Compose 生产环境配置 - MySQL/Redis/MongoDB 数据库 - Nginx 前端服务 - 强密码安全配置 ⚠️ P2 待办 (下次迭代): - 学生/检测/预警等业务模块实现 - 错误处理统一化 - 缓存策略优化 - 日志分级 📍 生产环境: - 服务器:192.168.15.222 - 管理后台:http://192.168.15.222:8081 - API 服务:http://192.168.15.222:8080 2026-03-29 上线部署完成
92 lines
2.1 KiB
Go
92 lines
2.1 KiB
Go
package unit
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/stretchr/testify/assert"
|
|
"gorm.io/driver/sqlite"
|
|
"gorm.io/gorm"
|
|
"ai-myopia-prevention/api/handlers"
|
|
)
|
|
|
|
func TestAuthHandlers(t *testing.T) {
|
|
// 设置Gin为测试模式
|
|
gin.SetMode(gin.TestMode)
|
|
|
|
// 创建内存数据库用于测试
|
|
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
|
if err != nil {
|
|
t.Fatalf("failed to connect database: %v", err)
|
|
}
|
|
|
|
// 迁移模型
|
|
err = db.AutoMigrate(&struct {
|
|
ID uint `gorm:"primaryKey"`
|
|
Username string `gorm:"uniqueIndex"`
|
|
PasswordHash string
|
|
Phone string `gorm:"uniqueIndex"`
|
|
UserType string
|
|
UserID uint
|
|
Status int
|
|
}{})
|
|
if err != nil {
|
|
t.Fatalf("failed to migrate database: %v", err)
|
|
}
|
|
|
|
// 创建服务实例
|
|
authService := handlers.NewAuthService(db)
|
|
|
|
t.Run("Test Login Endpoint", func(t *testing.T) {
|
|
// 创建测试路由
|
|
router := gin.Default()
|
|
router.POST("/login", authService.Login)
|
|
|
|
// 准备测试数据
|
|
loginReq := handlers.LoginRequest{
|
|
Username: "testuser",
|
|
Password: "password123",
|
|
}
|
|
|
|
jsonValue, _ := json.Marshal(loginReq)
|
|
req, _ := http.NewRequest(http.MethodPost, "/login", bytes.NewBuffer(jsonValue))
|
|
req.Header.Set("Content-Type", "application/json")
|
|
|
|
// 执行请求
|
|
w := httptest.NewRecorder()
|
|
router.ServeHTTP(w, req)
|
|
|
|
// 断言响应
|
|
assert.Equal(t, http.StatusOK, w.Code)
|
|
})
|
|
|
|
t.Run("Test Register Endpoint", func(t *testing.T) {
|
|
// 创建测试路由
|
|
router := gin.Default()
|
|
router.POST("/register", authService.Register)
|
|
|
|
// 准备测试数据
|
|
registerReq := handlers.RegisterRequest{
|
|
Username: "newuser",
|
|
Password: "password123",
|
|
Name: "New User",
|
|
Phone: "13800138000",
|
|
Role: "student",
|
|
}
|
|
|
|
jsonValue, _ := json.Marshal(registerReq)
|
|
req, _ := http.NewRequest(http.MethodPost, "/register", bytes.NewBuffer(jsonValue))
|
|
req.Header.Set("Content-Type", "application/json")
|
|
|
|
// 执行请求
|
|
w := httptest.NewRecorder()
|
|
router.ServeHTTP(w, req)
|
|
|
|
// 断言响应
|
|
assert.Equal(t, http.StatusOK, w.Code)
|
|
})
|
|
} |