fix: harden auth flows and align api contracts
This commit is contained in:
@@ -368,15 +368,15 @@ func TestProtectedEndpoints_Contract(t *testing.T) {
|
||||
// TestHTTPStatusCodes_Contract 验证 HTTP 状态码使用规范
|
||||
func TestHTTPStatusCodes_Contract(t *testing.T) {
|
||||
statusCodes := map[int]string{
|
||||
http.StatusOK: "成功响应",
|
||||
http.StatusCreated: "资源创建成功",
|
||||
http.StatusBadRequest: "请求参数错误",
|
||||
http.StatusUnauthorized: "未认证",
|
||||
http.StatusForbidden: "无权限",
|
||||
http.StatusNotFound: "资源不存在",
|
||||
http.StatusConflict: "资源冲突",
|
||||
http.StatusTooManyRequests: "请求过于频繁",
|
||||
http.StatusInternalServerError: "服务器内部错误",
|
||||
http.StatusOK: "成功响应",
|
||||
http.StatusCreated: "资源创建成功",
|
||||
http.StatusBadRequest: "请求参数错误",
|
||||
http.StatusUnauthorized: "未认证",
|
||||
http.StatusForbidden: "无权限",
|
||||
http.StatusNotFound: "资源不存在",
|
||||
http.StatusConflict: "资源冲突",
|
||||
http.StatusTooManyRequests: "请求过于频繁",
|
||||
http.StatusInternalServerError: "服务器内部错误",
|
||||
}
|
||||
|
||||
for code, desc := range statusCodes {
|
||||
|
||||
@@ -295,7 +295,7 @@ func (h *AuthHandler) Logout(c *gin.Context) {
|
||||
// @Success 200 {object} Response{data=service.LoginResponse} "刷新成功"
|
||||
// @Failure 400 {object} Response{code=int,message=string} "请求参数错误"
|
||||
// @Failure 401 {object} Response{code=int,message=string} "refresh_token无效或已过期"
|
||||
// @Router /api/v1/auth/refresh-token [post]
|
||||
// @Router /api/v1/auth/refresh [post]
|
||||
func (h *AuthHandler) RefreshToken(c *gin.Context) {
|
||||
var req struct {
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
@@ -361,7 +361,7 @@ func (h *AuthHandler) GetUserInfo(c *gin.Context) {
|
||||
// @Description 由于系统使用JWT Bearer Token认证,不存在CSRF风险,返回空token
|
||||
// @Tags 认证
|
||||
// @Produce json
|
||||
// @Success 200 {object} map "CSRF token(为空)"
|
||||
// @Success 200 {object} Response{data=CSRFTokenResponse} "CSRF token(为空)"
|
||||
// @Router /api/v1/auth/csrf-token [get]
|
||||
func (h *AuthHandler) GetCSRFToken(c *gin.Context) {
|
||||
// 系统使用 JWT Bearer Token 认证,Bearer Token 不会被浏览器自动携带(非 cookie)
|
||||
@@ -422,7 +422,7 @@ func (h *AuthHandler) OAuthCallback(c *gin.Context) {
|
||||
// @Produce json
|
||||
// @Param provider path string true "OAuth提供商"
|
||||
// @Success 200 {object} Response "OAuth未配置"
|
||||
// @Router /api/v1/auth/oauth/{provider}/exchange [post]
|
||||
// @Router /api/v1/auth/oauth/exchange [post]
|
||||
func (h *AuthHandler) OAuthExchange(c *gin.Context) {
|
||||
c.JSON(http.StatusServiceUnavailable, gin.H{"code": http.StatusServiceUnavailable, "message": "OAuth exchange is not configured"})
|
||||
}
|
||||
@@ -432,7 +432,7 @@ func (h *AuthHandler) OAuthExchange(c *gin.Context) {
|
||||
// @Description 返回系统已配置并启用的OAuth提供商列表
|
||||
// @Tags OAuth
|
||||
// @Produce json
|
||||
// @Success 200 {object} Response{data=map} "提供商列表"
|
||||
// @Success 200 {object} Response{data=OAuthProvidersResponse} "提供商列表"
|
||||
// @Router /api/v1/auth/oauth/providers [get]
|
||||
func (h *AuthHandler) GetEnabledOAuthProviders(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"code": 0, "message": "success", "data": gin.H{"providers": []string{}}})
|
||||
@@ -471,7 +471,7 @@ func (h *AuthHandler) ActivateEmail(c *gin.Context) {
|
||||
// @Param request body ResendActivationRequest true "邮箱地址"
|
||||
// @Success 200 {object} Response "激活邮件已发送(如果邮箱已注册)"
|
||||
// @Failure 400 {object} Response "邮箱格式错误"
|
||||
// @Router /api/v1/auth/resend-activation-email [post]
|
||||
// @Router /api/v1/auth/resend-activation [post]
|
||||
func (h *AuthHandler) ResendActivationEmail(c *gin.Context) {
|
||||
var req struct {
|
||||
Email string `json:"email" binding:"required,email"`
|
||||
@@ -525,7 +525,7 @@ func (h *AuthHandler) SendEmailCode(c *gin.Context) {
|
||||
// @Success 200 {object} Response{data=service.LoginResponse} "登录成功"
|
||||
// @Failure 400 {object} Response "请求参数错误"
|
||||
// @Failure 401 {object} Response "验证码错误或已过期"
|
||||
// @Router /api/v1/auth/login-by-email-code [post]
|
||||
// @Router /api/v1/auth/login/email-code [post]
|
||||
func (h *AuthHandler) LoginByEmailCode(c *gin.Context) {
|
||||
var req struct {
|
||||
Email string `json:"email" binding:"required,email"`
|
||||
@@ -645,7 +645,7 @@ func (h *AuthHandler) BootstrapAdmin(c *gin.Context) {
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} Response "功能未配置"
|
||||
// @Router /api/v1/auth/email/bind/send [post]
|
||||
// @Router /api/v1/users/me/bind-email/code [post]
|
||||
func (h *AuthHandler) SendEmailBindCode(c *gin.Context) {
|
||||
c.JSON(http.StatusServiceUnavailable, gin.H{"code": http.StatusServiceUnavailable, "message": "email binding is not configured"})
|
||||
}
|
||||
@@ -657,7 +657,7 @@ func (h *AuthHandler) SendEmailBindCode(c *gin.Context) {
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} Response "功能未配置"
|
||||
// @Router /api/v1/auth/email/bind [post]
|
||||
// @Router /api/v1/users/me/bind-email [post]
|
||||
func (h *AuthHandler) BindEmail(c *gin.Context) {
|
||||
c.JSON(http.StatusServiceUnavailable, gin.H{"code": http.StatusServiceUnavailable, "message": "email binding is not configured"})
|
||||
}
|
||||
@@ -669,7 +669,7 @@ func (h *AuthHandler) BindEmail(c *gin.Context) {
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} Response "功能未配置"
|
||||
// @Router /api/v1/auth/email/unbind [post]
|
||||
// @Router /api/v1/users/me/bind-email [delete]
|
||||
func (h *AuthHandler) UnbindEmail(c *gin.Context) {
|
||||
c.JSON(http.StatusServiceUnavailable, gin.H{"code": http.StatusServiceUnavailable, "message": "email binding is not configured"})
|
||||
}
|
||||
@@ -681,7 +681,7 @@ func (h *AuthHandler) UnbindEmail(c *gin.Context) {
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} Response "功能未配置"
|
||||
// @Router /api/v1/auth/phone/bind/send [post]
|
||||
// @Router /api/v1/users/me/bind-phone/code [post]
|
||||
func (h *AuthHandler) SendPhoneBindCode(c *gin.Context) {
|
||||
c.JSON(http.StatusServiceUnavailable, gin.H{"code": http.StatusServiceUnavailable, "message": "phone binding is not configured"})
|
||||
}
|
||||
@@ -693,7 +693,7 @@ func (h *AuthHandler) SendPhoneBindCode(c *gin.Context) {
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} Response "功能未配置"
|
||||
// @Router /api/v1/auth/phone/bind [post]
|
||||
// @Router /api/v1/users/me/bind-phone [post]
|
||||
func (h *AuthHandler) BindPhone(c *gin.Context) {
|
||||
c.JSON(http.StatusServiceUnavailable, gin.H{"code": http.StatusServiceUnavailable, "message": "phone binding is not configured"})
|
||||
}
|
||||
@@ -705,7 +705,7 @@ func (h *AuthHandler) BindPhone(c *gin.Context) {
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} Response "功能未配置"
|
||||
// @Router /api/v1/auth/phone/unbind [post]
|
||||
// @Router /api/v1/users/me/bind-phone [delete]
|
||||
func (h *AuthHandler) UnbindPhone(c *gin.Context) {
|
||||
c.JSON(http.StatusServiceUnavailable, gin.H{"code": http.StatusServiceUnavailable, "message": "phone binding is not configured"})
|
||||
}
|
||||
@@ -717,7 +717,7 @@ func (h *AuthHandler) UnbindPhone(c *gin.Context) {
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Success 200 {object} Response "社交账号列表"
|
||||
// @Router /api/v1/auth/social-accounts [get]
|
||||
// @Router /api/v1/users/me/social-accounts [get]
|
||||
func (h *AuthHandler) GetSocialAccounts(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"code": 0, "message": "success", "data": gin.H{"accounts": []interface{}{}}})
|
||||
}
|
||||
@@ -729,7 +729,7 @@ func (h *AuthHandler) GetSocialAccounts(c *gin.Context) {
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} Response "功能未配置"
|
||||
// @Router /api/v1/auth/social/bind [post]
|
||||
// @Router /api/v1/users/me/bind-social [post]
|
||||
func (h *AuthHandler) BindSocialAccount(c *gin.Context) {
|
||||
c.JSON(http.StatusServiceUnavailable, gin.H{"code": http.StatusServiceUnavailable, "message": "social binding is not configured"})
|
||||
}
|
||||
@@ -741,7 +741,7 @@ func (h *AuthHandler) BindSocialAccount(c *gin.Context) {
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} Response "功能未配置"
|
||||
// @Router /api/v1/auth/social/unbind [post]
|
||||
// @Router /api/v1/users/me/bind-social/{provider} [delete]
|
||||
func (h *AuthHandler) UnbindSocialAccount(c *gin.Context) {
|
||||
c.JSON(http.StatusServiceUnavailable, gin.H{"code": http.StatusServiceUnavailable, "message": "social binding is not configured"})
|
||||
}
|
||||
|
||||
@@ -169,12 +169,19 @@ func (h *AvatarHandler) UploadAvatar(c *gin.Context) {
|
||||
|
||||
// Save file to disk
|
||||
dstPath := filepath.Join(uploadDir, avatarFilename)
|
||||
data := make([]byte, file.Size)
|
||||
if _, err := src.Read(data); err != nil {
|
||||
dst, err := os.Create(dstPath)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"code": 500, "message": "failed to save avatar file"})
|
||||
return
|
||||
}
|
||||
if _, err := io.Copy(dst, src); err != nil {
|
||||
dst.Close()
|
||||
os.Remove(dstPath)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"code": 500, "message": "failed to read uploaded file"})
|
||||
return
|
||||
}
|
||||
if err := os.WriteFile(dstPath, data, 0o644); err != nil {
|
||||
if err := dst.Close(); err != nil {
|
||||
os.Remove(dstPath)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"code": 500, "message": "failed to save avatar file"})
|
||||
return
|
||||
}
|
||||
@@ -202,9 +209,9 @@ func (h *AvatarHandler) UploadAvatar(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"code": 0,
|
||||
"message": "avatar uploaded successfully",
|
||||
"data": gin.H{
|
||||
"avatar_url": avatarURL,
|
||||
"thumbnail": avatarURL,
|
||||
"data": AvatarResponse{
|
||||
AvatarURL: avatarURL,
|
||||
Thumbnail: avatarURL,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -39,7 +39,7 @@ func doUploadAvatar(url, token string, userID string, filename string, content [
|
||||
// Create multipart form
|
||||
var body bytes.Buffer
|
||||
writer := multipart.NewWriter(&body)
|
||||
|
||||
|
||||
// Add file
|
||||
part, _ := writer.CreateFormFile("avatar", filename)
|
||||
part.Write(content)
|
||||
@@ -76,7 +76,7 @@ func TestAvatarHandler_UploadAvatar_Success(t *testing.T) {
|
||||
// Get user ID by getting user info
|
||||
resp, body := doGet(server.URL+"/api/v1/users/me", token)
|
||||
defer resp.Body.Close()
|
||||
|
||||
|
||||
userID := "1" // Default to 1, adjust based on response
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
// Parse user ID from response
|
||||
@@ -129,7 +129,7 @@ func TestAvatarHandler_UploadAvatar_OtherUser_Forbidden(t *testing.T) {
|
||||
|
||||
registerUser(server.URL, "usera", "usera@test.com", "Pass123!")
|
||||
tokenA := getToken(server.URL, "usera", "Pass123!")
|
||||
|
||||
|
||||
registerUser(server.URL, "userb", "userb@test.com", "Pass123!")
|
||||
// userB token - but we try to upload to userA
|
||||
|
||||
@@ -200,7 +200,10 @@ func TestAvatarHandler_UploadAvatar_NoFile(t *testing.T) {
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
|
||||
client := &http.Client{}
|
||||
resp, _ := client.Do(req)
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("request failed: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
// Should reject missing file
|
||||
@@ -220,7 +223,7 @@ func TestAvatarHandler_UploadAvatar_FileTooLarge(t *testing.T) {
|
||||
// Create oversized file (6MB > 5MB limit)
|
||||
largeContent := make([]byte, 6*1024*1024)
|
||||
copy(largeContent, []byte{0x89, 0x50, 0x4E, 0x47}) // PNG header
|
||||
|
||||
|
||||
resp, _ := doUploadAvatar(server.URL, token, "1", "large.png", largeContent)
|
||||
defer resp.Body.Close()
|
||||
|
||||
@@ -239,7 +242,7 @@ func TestAvatarHandler_UploadAvatar_AllowedFormats(t *testing.T) {
|
||||
assert.NotEmpty(t, token)
|
||||
|
||||
formats := []string{".png", ".jpg", ".jpeg", ".gif", ".webp"}
|
||||
|
||||
|
||||
for i, ext := range formats {
|
||||
imageData := createTestImage(ext)
|
||||
// Ensure we don't slice beyond the length
|
||||
@@ -248,9 +251,9 @@ func TestAvatarHandler_UploadAvatar_AllowedFormats(t *testing.T) {
|
||||
dataSize = 100
|
||||
}
|
||||
resp, respBody := doUploadAvatar(server.URL, token, "1", "avatar"+ext, imageData[:dataSize])
|
||||
|
||||
|
||||
t.Logf("Format %s returned status: %d", ext, resp.StatusCode)
|
||||
|
||||
|
||||
// Accept various responses based on image validity
|
||||
if i == len(formats)-1 {
|
||||
resp.Body.Close()
|
||||
@@ -269,12 +272,12 @@ func TestAvatarHandler_UploadAvatar_DisallowedExtensions(t *testing.T) {
|
||||
assert.NotEmpty(t, token)
|
||||
|
||||
disallowed := []string{".exe", ".php", ".sh", ".bat", ".pdf", ".doc"}
|
||||
|
||||
|
||||
for _, ext := range disallowed {
|
||||
fakeContent := []byte("fake content")
|
||||
resp, _ := doUploadAvatar(server.URL, token, "1", "file"+ext, fakeContent)
|
||||
defer resp.Body.Close()
|
||||
|
||||
|
||||
// Should reject disallowed extensions
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
assert.True(t, resp.StatusCode == http.StatusBadRequest || resp.StatusCode == http.StatusInternalServerError,
|
||||
|
||||
@@ -24,7 +24,7 @@ func NewCaptchaHandler(captchaService *service.CaptchaService) *CaptchaHandler {
|
||||
// @Tags 验证码
|
||||
// @Produce json
|
||||
// @Success 200 {object} Response{data=CaptchaResponse} "验证码信息"
|
||||
// @Router /api/v1/captcha/generate [get]
|
||||
// @Router /api/v1/auth/captcha [get]
|
||||
func (h *CaptchaHandler) GenerateCaptcha(c *gin.Context) {
|
||||
result, err := h.captchaService.Generate(c.Request.Context())
|
||||
if err != nil {
|
||||
@@ -49,7 +49,7 @@ func (h *CaptchaHandler) GenerateCaptcha(c *gin.Context) {
|
||||
// @Produce json
|
||||
// @Param captcha_id query string false "验证码ID"
|
||||
// @Success 200 {object} Response "验证码图片"
|
||||
// @Router /api/v1/captcha/image [get]
|
||||
// @Router /api/v1/auth/captcha/image [get]
|
||||
func (h *CaptchaHandler) GetCaptchaImage(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"code": 0, "message": "success"})
|
||||
}
|
||||
@@ -63,7 +63,7 @@ func (h *CaptchaHandler) GetCaptchaImage(c *gin.Context) {
|
||||
// @Param request body VerifyCaptchaRequest true "验证码信息"
|
||||
// @Success 200 {object} Response{data=VerifyResponse} "验证成功"
|
||||
// @Failure 400 {object} Response "验证码无效"
|
||||
// @Router /api/v1/captcha/verify [post]
|
||||
// @Router /api/v1/auth/captcha/verify [post]
|
||||
func (h *CaptchaHandler) VerifyCaptcha(c *gin.Context) {
|
||||
var req struct {
|
||||
CaptchaID string `json:"captcha_id" binding:"required"`
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/user-management-system/internal/auth"
|
||||
)
|
||||
|
||||
func init() {
|
||||
@@ -15,7 +16,14 @@ func init() {
|
||||
}
|
||||
|
||||
func TestSSOHandlerAuthorize_InvalidContextTypes_ReturnsUnauthorized(t *testing.T) {
|
||||
h := &SSOHandler{}
|
||||
h := &SSOHandler{clientsStore: auth.NewDefaultSSOClientsStore()}
|
||||
store := h.clientsStore.(*auth.DefaultSSOClientsStore)
|
||||
store.RegisterClient(&auth.SSOClient{
|
||||
ClientID: "test-client",
|
||||
ClientSecret: "test-secret",
|
||||
RedirectURIs: []string{"https://example.com/callback"},
|
||||
})
|
||||
|
||||
engine := gin.New()
|
||||
engine.GET("/authorize", func(c *gin.Context) {
|
||||
c.Set("user_id", "not-int64")
|
||||
|
||||
@@ -27,10 +27,10 @@ func NewCustomFieldHandler(customFieldService *service.CustomFieldService) *Cust
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param request body service.CreateFieldRequest true "字段定义"
|
||||
// @Success 201 {object} Response{data=domain.CustomField} "创建成功"
|
||||
// @Success 201 {object} Response{data=SwaggerCustomField} "创建成功"
|
||||
// @Failure 400 {object} Response "请求参数错误"
|
||||
// @Failure 403 {object} Response "无权限"
|
||||
// @Router /api/v1/fields [post]
|
||||
// @Router /api/v1/custom-fields [post]
|
||||
func (h *CustomFieldHandler) CreateField(c *gin.Context) {
|
||||
var req service.CreateFieldRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
@@ -60,11 +60,11 @@ func (h *CustomFieldHandler) CreateField(c *gin.Context) {
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "字段ID"
|
||||
// @Param request body service.UpdateFieldRequest true "更新信息"
|
||||
// @Success 200 {object} Response{data=domain.CustomField} "更新成功"
|
||||
// @Success 200 {object} Response{data=SwaggerCustomField} "更新成功"
|
||||
// @Failure 400 {object} Response "请求参数错误"
|
||||
// @Failure 403 {object} Response "无权限"
|
||||
// @Failure 404 {object} Response "字段不存在"
|
||||
// @Router /api/v1/fields/{id} [put]
|
||||
// @Router /api/v1/custom-fields/{id} [put]
|
||||
func (h *CustomFieldHandler) UpdateField(c *gin.Context) {
|
||||
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
@@ -101,7 +101,7 @@ func (h *CustomFieldHandler) UpdateField(c *gin.Context) {
|
||||
// @Success 200 {object} Response "删除成功"
|
||||
// @Failure 403 {object} Response "无权限"
|
||||
// @Failure 404 {object} Response "字段不存在"
|
||||
// @Router /api/v1/fields/{id} [delete]
|
||||
// @Router /api/v1/custom-fields/{id} [delete]
|
||||
func (h *CustomFieldHandler) DeleteField(c *gin.Context) {
|
||||
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
@@ -127,9 +127,9 @@ func (h *CustomFieldHandler) DeleteField(c *gin.Context) {
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "字段ID"
|
||||
// @Success 200 {object} Response{data=domain.CustomField} "字段信息"
|
||||
// @Success 200 {object} Response{data=SwaggerCustomField} "字段信息"
|
||||
// @Failure 404 {object} Response "字段不存在"
|
||||
// @Router /api/v1/fields/{id} [get]
|
||||
// @Router /api/v1/custom-fields/{id} [get]
|
||||
func (h *CustomFieldHandler) GetField(c *gin.Context) {
|
||||
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
@@ -156,8 +156,8 @@ func (h *CustomFieldHandler) GetField(c *gin.Context) {
|
||||
// @Tags 自定义字段
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Success 200 {object} Response{data=[]domain.CustomField} "字段列表"
|
||||
// @Router /api/v1/fields [get]
|
||||
// @Success 200 {object} Response{data=[]SwaggerCustomField} "字段列表"
|
||||
// @Router /api/v1/custom-fields [get]
|
||||
func (h *CustomFieldHandler) ListFields(c *gin.Context) {
|
||||
fields, err := h.customFieldService.ListFields(c.Request.Context())
|
||||
if err != nil {
|
||||
@@ -183,7 +183,7 @@ func (h *CustomFieldHandler) ListFields(c *gin.Context) {
|
||||
// @Success 200 {object} Response "设置成功"
|
||||
// @Failure 400 {object} Response "请求参数错误"
|
||||
// @Failure 401 {object} Response "未认证"
|
||||
// @Router /api/v1/users/me/fields [put]
|
||||
// @Router /api/v1/users/me/custom-fields [put]
|
||||
func (h *CustomFieldHandler) SetUserFieldValues(c *gin.Context) {
|
||||
userID, ok := getUserIDFromContext(c)
|
||||
if !ok {
|
||||
@@ -217,9 +217,9 @@ func (h *CustomFieldHandler) SetUserFieldValues(c *gin.Context) {
|
||||
// @Tags 自定义字段
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Success 200 {object} Response{data=map} "字段值"
|
||||
// @Success 200 {object} Response{data=CustomFieldValuesResponse} "字段值"
|
||||
// @Failure 401 {object} Response "未认证"
|
||||
// @Router /api/v1/users/me/fields [get]
|
||||
// @Router /api/v1/users/me/custom-fields [get]
|
||||
func (h *CustomFieldHandler) GetUserFieldValues(c *gin.Context) {
|
||||
userID, ok := getUserIDFromContext(c)
|
||||
if !ok {
|
||||
|
||||
@@ -31,7 +31,7 @@ func TestCustomFieldHandler_CreateField_Success(t *testing.T) {
|
||||
})
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.True(t, resp.StatusCode == http.StatusCreated || resp.StatusCode == http.StatusForbidden ||
|
||||
assert.True(t, resp.StatusCode == http.StatusCreated || resp.StatusCode == http.StatusForbidden ||
|
||||
resp.StatusCode == http.StatusBadRequest || resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusInternalServerError,
|
||||
"should create field, got %d: %s", resp.StatusCode, body)
|
||||
}
|
||||
@@ -138,7 +138,7 @@ func TestCustomFieldHandler_GetField_NotFound(t *testing.T) {
|
||||
resp, _ := doGet(server.URL+"/api/v1/fields/99999", token)
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.True(t, resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusBadRequest ||
|
||||
assert.True(t, resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusBadRequest ||
|
||||
resp.StatusCode == http.StatusInternalServerError || resp.StatusCode == http.StatusOK,
|
||||
"should handle NotFound, got %d", resp.StatusCode)
|
||||
}
|
||||
@@ -156,7 +156,7 @@ func TestCustomFieldHandler_GetField_InvalidID(t *testing.T) {
|
||||
resp, _ := doGet(server.URL+"/api/v1/fields/invalid", token)
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.True(t, resp.StatusCode == http.StatusBadRequest || resp.StatusCode == http.StatusNotFound ||
|
||||
assert.True(t, resp.StatusCode == http.StatusBadRequest || resp.StatusCode == http.StatusNotFound ||
|
||||
resp.StatusCode == http.StatusInternalServerError || resp.StatusCode == http.StatusOK,
|
||||
"should handle InvalidID, got %d", resp.StatusCode)
|
||||
}
|
||||
@@ -204,7 +204,7 @@ func TestCustomFieldHandler_UpdateField_NotFound(t *testing.T) {
|
||||
})
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.True(t, resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusBadRequest ||
|
||||
assert.True(t, resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusBadRequest ||
|
||||
resp.StatusCode == http.StatusInternalServerError || resp.StatusCode == http.StatusOK,
|
||||
"should handle NotFound, got %d", resp.StatusCode)
|
||||
}
|
||||
@@ -265,7 +265,7 @@ func TestCustomFieldHandler_DeleteField_NotFound(t *testing.T) {
|
||||
resp, _ := doDelete(server.URL+"/api/v1/fields/99999", token)
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.True(t, resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusBadRequest ||
|
||||
assert.True(t, resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusBadRequest ||
|
||||
resp.StatusCode == http.StatusInternalServerError || resp.StatusCode == http.StatusOK,
|
||||
"should handle NotFound, got %d", resp.StatusCode)
|
||||
}
|
||||
@@ -283,7 +283,7 @@ func TestCustomFieldHandler_DeleteField_InvalidID(t *testing.T) {
|
||||
resp, _ := doDelete(server.URL+"/api/v1/fields/invalid", token)
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.True(t, resp.StatusCode == http.StatusBadRequest || resp.StatusCode == http.StatusNotFound ||
|
||||
assert.True(t, resp.StatusCode == http.StatusBadRequest || resp.StatusCode == http.StatusNotFound ||
|
||||
resp.StatusCode == http.StatusInternalServerError || resp.StatusCode == http.StatusOK,
|
||||
"should handle InvalidID, got %d", resp.StatusCode)
|
||||
}
|
||||
@@ -385,7 +385,7 @@ func TestCustomFieldHandler_FieldTypes_Support(t *testing.T) {
|
||||
fieldTypes := []string{"text", "number", "date", "boolean", "select"}
|
||||
for _, ft := range fieldTypes {
|
||||
resp, _ := doPost(server.URL+"/api/v1/fields", token, map[string]interface{}{
|
||||
"name": "field_" + ft,
|
||||
"name": "field_" + ft,
|
||||
"label": "Field " + ft,
|
||||
"type": ft,
|
||||
})
|
||||
|
||||
@@ -31,7 +31,7 @@ func NewDeviceHandler(deviceService *service.DeviceService) *DeviceHandler {
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param request body service.CreateDeviceRequest true "设备信息"
|
||||
// @Success 201 {object} Response{data=domain.Device} "设备创建成功"
|
||||
// @Success 201 {object} Response{data=SwaggerDevice} "设备创建成功"
|
||||
// @Failure 401 {object} Response "未认证"
|
||||
// @Router /api/v1/devices [post]
|
||||
func (h *DeviceHandler) CreateDevice(c *gin.Context) {
|
||||
@@ -109,7 +109,7 @@ func (h *DeviceHandler) GetMyDevices(c *gin.Context) {
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "设备ID"
|
||||
// @Success 200 {object} Response{data=domain.Device} "设备信息"
|
||||
// @Success 200 {object} Response{data=SwaggerDevice} "设备信息"
|
||||
// @Failure 404 {object} Response "设备不存在"
|
||||
// @Router /api/v1/devices/{id} [get]
|
||||
func (h *DeviceHandler) GetDevice(c *gin.Context) {
|
||||
@@ -140,7 +140,7 @@ func (h *DeviceHandler) GetDevice(c *gin.Context) {
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "设备ID"
|
||||
// @Param request body service.UpdateDeviceRequest true "更新信息"
|
||||
// @Success 200 {object} Response{data=domain.Device} "更新成功"
|
||||
// @Success 200 {object} Response{data=SwaggerDevice} "更新成功"
|
||||
// @Failure 400 {object} Response "请求参数错误"
|
||||
// @Failure 404 {object} Response "设备不存在"
|
||||
// @Router /api/v1/devices/{id} [put]
|
||||
@@ -245,6 +245,7 @@ func (h *DeviceHandler) UpdateDeviceStatus(c *gin.Context) {
|
||||
status = domain.DeviceStatusActive
|
||||
case "inactive", "0":
|
||||
status = domain.DeviceStatusInactive
|
||||
|
||||
default:
|
||||
c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": "invalid status"})
|
||||
return
|
||||
@@ -272,7 +273,7 @@ func (h *DeviceHandler) UpdateDeviceStatus(c *gin.Context) {
|
||||
// @Param page_size query int false "每页数量"
|
||||
// @Success 200 {object} Response{data=DeviceListResponse} "设备列表"
|
||||
// @Failure 403 {object} Response "无权限"
|
||||
// @Router /api/v1/users/{id}/devices [get]
|
||||
// @Router /api/v1/devices/users/{id} [get]
|
||||
func (h *DeviceHandler) GetUserDevices(c *gin.Context) {
|
||||
// IDOR 修复:检查当前用户是否有权限查看指定用户的设备
|
||||
currentUserID, ok := getUserIDFromContext(c)
|
||||
@@ -430,7 +431,7 @@ func (h *DeviceHandler) TrustDevice(c *gin.Context) {
|
||||
// @Param request body TrustDeviceRequest true "信任配置"
|
||||
// @Success 200 {object} Response "设置成功"
|
||||
// @Failure 401 {object} Response "未认证"
|
||||
// @Router /api/v1/devices/trust/{deviceId} [post]
|
||||
// @Router /api/v1/devices/by-device-id/{deviceId}/trust [post]
|
||||
func (h *DeviceHandler) TrustDeviceByDeviceID(c *gin.Context) {
|
||||
userID, ok := getUserIDFromContext(c)
|
||||
if !ok {
|
||||
@@ -502,9 +503,9 @@ func (h *DeviceHandler) UntrustDevice(c *gin.Context) {
|
||||
// @Tags 设备管理
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Success 200 {object} Response{data=[]domain.Device} "信任设备列表"
|
||||
// @Success 200 {object} Response{data=[]SwaggerDevice} "信任设备列表"
|
||||
// @Failure 401 {object} Response "未认证"
|
||||
// @Router /api/v1/devices/trusted [get]
|
||||
// @Router /api/v1/devices/me/trusted [get]
|
||||
func (h *DeviceHandler) GetMyTrustedDevices(c *gin.Context) {
|
||||
userID, ok := getUserIDFromContext(c)
|
||||
if !ok {
|
||||
@@ -535,7 +536,7 @@ func (h *DeviceHandler) GetMyTrustedDevices(c *gin.Context) {
|
||||
// @Success 200 {object} Response "登出成功"
|
||||
// @Failure 400 {object} Response "无效的设备ID"
|
||||
// @Failure 401 {object} Response "未认证"
|
||||
// @Router /api/v1/devices/logout-others [post]
|
||||
// @Router /api/v1/devices/me/logout-others [post]
|
||||
func (h *DeviceHandler) LogoutAllOtherDevices(c *gin.Context) {
|
||||
userID, ok := getUserIDFromContext(c)
|
||||
if !ok {
|
||||
|
||||
@@ -27,14 +27,14 @@ func NewExportHandler(exportService *service.ExportService) *ExportHandler {
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param format query string false "导出格式" default(csv) Enums(csv, excel)
|
||||
// @Param format query string false "导出格式" default(csv) Enums(csv, xlsx)
|
||||
// @Param fields query string false "导出字段,逗号分隔"
|
||||
// @Param keyword query string false "关键词过滤"
|
||||
// @Param status query int false "用户状态过滤"
|
||||
// @Success 200 {file} file "用户数据文件"
|
||||
// @Failure 401 {object} Response "未认证"
|
||||
// @Failure 500 {object} Response "服务器错误"
|
||||
// @Router /api/v1/exports/users [get]
|
||||
// @Router /api/v1/admin/users/export [get]
|
||||
func (h *ExportHandler) ExportUsers(c *gin.Context) {
|
||||
format := c.DefaultQuery("format", "csv")
|
||||
fieldsStr := c.Query("fields")
|
||||
@@ -49,9 +49,11 @@ func (h *ExportHandler) ExportUsers(c *gin.Context) {
|
||||
var status *int
|
||||
if statusStr != "" {
|
||||
s, err := strconvAtoi(statusStr)
|
||||
if err == nil {
|
||||
status = &s
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": "invalid status"})
|
||||
return
|
||||
}
|
||||
status = &s
|
||||
}
|
||||
|
||||
req := &service.ExportUsersRequest{
|
||||
@@ -81,12 +83,12 @@ func (h *ExportHandler) ExportUsers(c *gin.Context) {
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param file formData file true "导入文件"
|
||||
// @Param format query string false "文件格式" default(csv) Enums(csv, excel)
|
||||
// @Param format query string false "文件格式" default(csv) Enums(csv, xlsx)
|
||||
// @Success 200 {object} Response "导入结果"
|
||||
// @Failure 400 {object} Response "请求参数错误"
|
||||
// @Failure 401 {object} Response "未认证"
|
||||
// @Failure 500 {object} Response "服务器错误"
|
||||
// @Router /api/v1/exports/users [post]
|
||||
// @Router /api/v1/admin/users/import [post]
|
||||
func (h *ExportHandler) ImportUsers(c *gin.Context) {
|
||||
file, _, err := c.Request.FormFile("file")
|
||||
if err != nil {
|
||||
@@ -120,11 +122,11 @@ func (h *ExportHandler) ImportUsers(c *gin.Context) {
|
||||
// @Tags 数据导入导出
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param format query string false "模板格式" default(csv) Enums(csv, excel)
|
||||
// @Param format query string false "模板格式" default(csv) Enums(csv, xlsx)
|
||||
// @Success 200 {file} file "导入模板文件"
|
||||
// @Failure 401 {object} Response "未认证"
|
||||
// @Failure 500 {object} Response "服务器错误"
|
||||
// @Router /api/v1/exports/template [get]
|
||||
// @Router /api/v1/admin/users/import/template [get]
|
||||
func (h *ExportHandler) GetImportTemplate(c *gin.Context) {
|
||||
format := c.DefaultQuery("format", "csv")
|
||||
data, filename, contentType, err := h.exportService.GetImportTemplateByFormat(format)
|
||||
@@ -139,10 +141,13 @@ func (h *ExportHandler) GetImportTemplate(c *gin.Context) {
|
||||
}
|
||||
|
||||
func strconvAtoi(s string) (int, error) {
|
||||
if s == "" {
|
||||
return 0, http.ErrNoLocation
|
||||
}
|
||||
var n int
|
||||
for _, c := range s {
|
||||
if c < '0' || c > '9' {
|
||||
return 0, nil
|
||||
return 0, http.ErrNotSupported
|
||||
}
|
||||
n = n*10 + int(c-'0')
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ func TestExportHandler_ExportUsers_Success(t *testing.T) {
|
||||
t.Fatal("bootstrap admin token should succeed")
|
||||
}
|
||||
|
||||
resp, _ := doGet(server.URL+"/api/v1/exports/users", token)
|
||||
resp, _ := doGet(server.URL+"/api/v1/admin/users/export", token)
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.True(t, resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusForbidden || resp.StatusCode == http.StatusInternalServerError,
|
||||
@@ -42,16 +42,17 @@ func TestExportHandler_ExportUsers_WithFormat(t *testing.T) {
|
||||
}
|
||||
|
||||
// CSV format
|
||||
resp1, _ := doGet(server.URL+"/api/v1/exports/users?format=csv", token)
|
||||
resp1, _ := doGet(server.URL+"/api/v1/admin/users/export?format=csv", token)
|
||||
defer resp1.Body.Close()
|
||||
assert.True(t, resp1.StatusCode == http.StatusOK || resp1.StatusCode == http.StatusForbidden,
|
||||
"should export CSV, got %d", resp1.StatusCode)
|
||||
|
||||
// Excel format
|
||||
resp2, _ := doGet(server.URL+"/api/v1/exports/users?format=excel", token)
|
||||
// XLSX format
|
||||
resp2, _ := doGet(server.URL+"/api/v1/admin/users/export?format=xlsx", token)
|
||||
defer resp2.Body.Close()
|
||||
assert.True(t, resp2.StatusCode == http.StatusOK || resp2.StatusCode == http.StatusForbidden || resp2.StatusCode == http.StatusBadRequest,
|
||||
"should export Excel, got %d", resp2.StatusCode)
|
||||
"should export XLSX, got %d", resp2.StatusCode)
|
||||
|
||||
}
|
||||
|
||||
// TestExportHandler_ExportUsers_WithFields 验证指定字段导出
|
||||
@@ -64,7 +65,7 @@ func TestExportHandler_ExportUsers_WithFields(t *testing.T) {
|
||||
t.Fatal("bootstrap admin token should succeed")
|
||||
}
|
||||
|
||||
resp, _ := doGet(server.URL+"/api/v1/exports/users?fields=id,username,email&format=csv", token)
|
||||
resp, _ := doGet(server.URL+"/api/v1/admin/users/export?fields=id,username,email&format=csv", token)
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.True(t, resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusForbidden,
|
||||
@@ -81,13 +82,29 @@ func TestExportHandler_ExportUsers_WithFilter(t *testing.T) {
|
||||
t.Fatal("bootstrap admin token should succeed")
|
||||
}
|
||||
|
||||
resp, _ := doGet(server.URL+"/api/v1/exports/users?keyword=admin&status=1&format=csv", token)
|
||||
resp, _ := doGet(server.URL+"/api/v1/admin/users/export?keyword=admin&status=1&format=csv", token)
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.True(t, resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusForbidden || resp.StatusCode == http.StatusBadRequest,
|
||||
"should export with filter, got %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
// TestExportHandler_ExportUsers_InvalidStatus 验证非法状态参数
|
||||
func TestExportHandler_ExportUsers_InvalidStatus(t *testing.T) {
|
||||
server, cleanup := setupHandlerTestServer(t)
|
||||
defer cleanup()
|
||||
|
||||
token := bootstrapAdminToken(server.URL, "admin", "admin@test.com", "AdminPass123!")
|
||||
if token == "" {
|
||||
t.Fatal("bootstrap admin token should succeed")
|
||||
}
|
||||
|
||||
resp, _ := doGet(server.URL+"/api/v1/admin/users/export?status=abc&format=csv", token)
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
|
||||
}
|
||||
|
||||
// TestExportHandler_ExportUsers_NonAdmin 验证非管理员导出
|
||||
func TestExportHandler_ExportUsers_NonAdmin(t *testing.T) {
|
||||
server, cleanup := setupHandlerTestServer(t)
|
||||
@@ -97,7 +114,7 @@ func TestExportHandler_ExportUsers_NonAdmin(t *testing.T) {
|
||||
token := getToken(server.URL, "regular", "Pass123!")
|
||||
assert.NotEmpty(t, token)
|
||||
|
||||
resp, _ := doGet(server.URL+"/api/v1/exports/users", token)
|
||||
resp, _ := doGet(server.URL+"/api/v1/admin/users/export", token)
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.True(t, resp.StatusCode == http.StatusForbidden || resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusOK,
|
||||
@@ -109,7 +126,7 @@ func TestExportHandler_ExportUsers_Unauthorized(t *testing.T) {
|
||||
server, cleanup := setupHandlerTestServer(t)
|
||||
defer cleanup()
|
||||
|
||||
resp, _ := doGet(server.URL+"/api/v1/exports/users", "")
|
||||
resp, _ := doGet(server.URL+"/api/v1/admin/users/export", "")
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.True(t, resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusForbidden,
|
||||
@@ -134,7 +151,7 @@ func TestExportHandler_ImportUsers_Success(t *testing.T) {
|
||||
part.Write([]byte(csvData))
|
||||
writer.Close()
|
||||
|
||||
req, _ := http.NewRequest("POST", server.URL+"/api/v1/exports/users?format=csv", &body)
|
||||
req, _ := http.NewRequest("POST", server.URL+"/api/v1/admin/users/import?format=csv", &body)
|
||||
req.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
|
||||
@@ -165,16 +182,20 @@ func TestExportHandler_ImportUsers_NoFile(t *testing.T) {
|
||||
writer := multipart.NewWriter(&body)
|
||||
writer.Close()
|
||||
|
||||
req, _ := http.NewRequest("POST", server.URL+"/api/v1/exports/users", &body)
|
||||
req, _ := http.NewRequest("POST", server.URL+"/api/v1/admin/users/import", &body)
|
||||
req.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
|
||||
client := &http.Client{}
|
||||
resp, _ := client.Do(req)
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("request failed: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.True(t, resp.StatusCode == http.StatusBadRequest || resp.StatusCode == http.StatusForbidden || resp.StatusCode == http.StatusOK,
|
||||
"should require file, got %d", resp.StatusCode)
|
||||
|
||||
}
|
||||
|
||||
// TestExportHandler_ImportUsers_InvalidFormat 验证无效格式导入
|
||||
@@ -193,16 +214,20 @@ func TestExportHandler_ImportUsers_InvalidFormat(t *testing.T) {
|
||||
part.Write([]byte("invalid content"))
|
||||
writer.Close()
|
||||
|
||||
req, _ := http.NewRequest("POST", server.URL+"/api/v1/exports/users?format=invalid", &body)
|
||||
req, _ := http.NewRequest("POST", server.URL+"/api/v1/admin/users/import?format=invalid", &body)
|
||||
req.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
|
||||
client := &http.Client{}
|
||||
resp, _ := client.Do(req)
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("request failed: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.True(t, resp.StatusCode == http.StatusBadRequest || resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusForbidden,
|
||||
"should handle invalid format, got %d", resp.StatusCode)
|
||||
|
||||
}
|
||||
|
||||
// TestExportHandler_ImportUsers_NonAdmin 验证非管理员导入
|
||||
@@ -220,12 +245,15 @@ func TestExportHandler_ImportUsers_NonAdmin(t *testing.T) {
|
||||
part.Write([]byte("username,email\nuser1,user1@test.com"))
|
||||
writer.Close()
|
||||
|
||||
req, _ := http.NewRequest("POST", server.URL+"/api/v1/exports/users", &body)
|
||||
req, _ := http.NewRequest("POST", server.URL+"/api/v1/admin/users/import", &body)
|
||||
req.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
|
||||
client := &http.Client{}
|
||||
resp, _ := client.Do(req)
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("request failed: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.True(t, resp.StatusCode == http.StatusForbidden || resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusOK,
|
||||
@@ -242,7 +270,7 @@ func TestExportHandler_GetImportTemplate_Success(t *testing.T) {
|
||||
t.Fatal("bootstrap admin token should succeed")
|
||||
}
|
||||
|
||||
resp, _ := doGet(server.URL+"/api/v1/exports/template", token)
|
||||
resp, _ := doGet(server.URL+"/api/v1/admin/users/import/template", token)
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.True(t, resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusForbidden || resp.StatusCode == http.StatusInternalServerError,
|
||||
@@ -259,7 +287,7 @@ func TestExportHandler_GetImportTemplate_CSV(t *testing.T) {
|
||||
t.Fatal("bootstrap admin token should succeed")
|
||||
}
|
||||
|
||||
resp, _ := doGet(server.URL+"/api/v1/exports/template?format=csv", token)
|
||||
resp, _ := doGet(server.URL+"/api/v1/admin/users/import/template?format=csv", token)
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.True(t, resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusForbidden,
|
||||
@@ -276,11 +304,11 @@ func TestExportHandler_GetImportTemplate_Excel(t *testing.T) {
|
||||
t.Fatal("bootstrap admin token should succeed")
|
||||
}
|
||||
|
||||
resp, _ := doGet(server.URL+"/api/v1/exports/template?format=excel", token)
|
||||
resp, _ := doGet(server.URL+"/api/v1/admin/users/import/template?format=xlsx", token)
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.True(t, resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusForbidden || resp.StatusCode == http.StatusBadRequest,
|
||||
"should get Excel template, got %d", resp.StatusCode)
|
||||
"should get XLSX template, got %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
// TestExportHandler_GetImportTemplate_Unauthorized 验证未认证获取模板
|
||||
@@ -288,7 +316,7 @@ func TestExportHandler_GetImportTemplate_Unauthorized(t *testing.T) {
|
||||
server, cleanup := setupHandlerTestServer(t)
|
||||
defer cleanup()
|
||||
|
||||
resp, _ := doGet(server.URL+"/api/v1/exports/template", "")
|
||||
resp, _ := doGet(server.URL+"/api/v1/admin/users/import/template", "")
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.True(t, resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusForbidden,
|
||||
@@ -305,7 +333,7 @@ func TestExportHandler_ExportResponse_ContentType(t *testing.T) {
|
||||
t.Fatal("bootstrap admin token should succeed")
|
||||
}
|
||||
|
||||
resp, _ := doGet(server.URL+"/api/v1/exports/users?format=csv", token)
|
||||
resp, _ := doGet(server.URL+"/api/v1/admin/users/export?format=csv", token)
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
@@ -325,7 +353,7 @@ func TestExportHandler_ExportResponse_ContentDisposition(t *testing.T) {
|
||||
t.Fatal("bootstrap admin token should succeed")
|
||||
}
|
||||
|
||||
resp, _ := doGet(server.URL+"/api/v1/exports/users?format=csv", token)
|
||||
resp, _ := doGet(server.URL+"/api/v1/admin/users/export?format=csv", token)
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
|
||||
@@ -120,6 +120,8 @@ func setupHandlerTestServer(t *testing.T) (*httptest.Server, func()) {
|
||||
opLogSvc := service.NewOperationLogService(opLogRepo)
|
||||
webhookSvc := service.NewWebhookService(db)
|
||||
captchaSvc := service.NewCaptchaService(cacheManager)
|
||||
exportSvc := service.NewExportService(userRepo, roleRepo)
|
||||
|
||||
totpSvc := service.NewTOTPService(userRepo)
|
||||
pwdResetCfg := service.DefaultPasswordResetConfig()
|
||||
pwdResetSvc := service.NewPasswordResetService(userRepo, cacheManager, pwdResetCfg).
|
||||
@@ -128,6 +130,15 @@ func setupHandlerTestServer(t *testing.T) (*httptest.Server, func()) {
|
||||
themeSvc := service.NewThemeService(themeRepo)
|
||||
avatarH := handler.NewAvatarHandler(userRepo)
|
||||
|
||||
ssoManager := auth.NewSSOManager()
|
||||
ssoClientsStore := auth.NewDefaultSSOClientsStore()
|
||||
ssoClientsStore.RegisterClient(&auth.SSOClient{
|
||||
ClientID: "test-client",
|
||||
ClientSecret: "test-secret",
|
||||
Name: "Handler Test Client",
|
||||
RedirectURIs: []string{"http://localhost/callback"},
|
||||
})
|
||||
ssoH := handler.NewSSOHandler(ssoManager, ssoClientsStore)
|
||||
rateLimitCfg := config.RateLimitConfig{}
|
||||
rateLimitMiddleware := middleware.NewRateLimitMiddleware(rateLimitCfg)
|
||||
authMiddleware := middleware.NewAuthMiddleware(
|
||||
@@ -147,12 +158,13 @@ func setupHandlerTestServer(t *testing.T) (*httptest.Server, func()) {
|
||||
totpHandler := handler.NewTOTPHandler(authSvc, totpSvc)
|
||||
pwdResetHandler := handler.NewPasswordResetHandler(pwdResetSvc)
|
||||
themeHandler := handler.NewThemeHandler(themeSvc)
|
||||
exportHandler := handler.NewExportHandler(exportSvc)
|
||||
|
||||
r := router.NewRouter(
|
||||
authHandler, userHandler, roleHandler, permHandler, deviceHandler,
|
||||
logHandler, authMiddleware, rateLimitMiddleware, opLogMiddleware,
|
||||
pwdResetHandler, captchaHandler, totpHandler, webhookHandler,
|
||||
nil, nil, nil, nil, nil, themeHandler, nil, nil, nil, avatarH,
|
||||
nil, exportHandler, nil, nil, nil, themeHandler, ssoH, nil, nil, avatarH,
|
||||
)
|
||||
engine := r.Setup()
|
||||
|
||||
|
||||
@@ -34,7 +34,7 @@ func NewLogHandler(loginLogService *service.LoginLogService, operationLogService
|
||||
// @Param page_size query int false "每页数量"
|
||||
// @Success 200 {object} Response{data=LoginLogListResponse} "登录日志列表"
|
||||
// @Failure 401 {object} Response "未认证"
|
||||
// @Router /api/v1/users/me/login-logs [get]
|
||||
// @Router /api/v1/logs/login/me [get]
|
||||
func (h *LogHandler) GetMyLoginLogs(c *gin.Context) {
|
||||
userID, ok := getUserIDFromContext(c)
|
||||
if !ok {
|
||||
@@ -76,7 +76,7 @@ func (h *LogHandler) GetMyLoginLogs(c *gin.Context) {
|
||||
// @Param page_size query int false "每页数量"
|
||||
// @Success 200 {object} Response{data=OperationLogListResponse} "操作日志列表"
|
||||
// @Failure 401 {object} Response "未认证"
|
||||
// @Router /api/v1/users/me/operation-logs [get]
|
||||
// @Router /api/v1/logs/operation/me [get]
|
||||
func (h *LogHandler) GetMyOperationLogs(c *gin.Context) {
|
||||
userID, ok := getUserIDFromContext(c)
|
||||
if !ok {
|
||||
@@ -120,7 +120,7 @@ func (h *LogHandler) GetMyOperationLogs(c *gin.Context) {
|
||||
// @Param page_size query int false "每页数量"
|
||||
// @Success 200 {object} Response{data=LoginLogListResponse} "登录日志列表"
|
||||
// @Failure 403 {object} Response "无权限"
|
||||
// @Router /api/v1/admin/logs/login [get]
|
||||
// @Router /api/v1/logs/login [get]
|
||||
func (h *LogHandler) GetLoginLogs(c *gin.Context) {
|
||||
var req service.ListLoginLogRequest
|
||||
if err := c.ShouldBindQuery(&req); err != nil {
|
||||
@@ -175,7 +175,7 @@ func (h *LogHandler) GetLoginLogs(c *gin.Context) {
|
||||
// @Success 200 {object} Response{data=OperationLogListResponse} "操作日志列表"
|
||||
// @Failure 403 {object} Response "无权限"
|
||||
// @Failure 500 {object} Response "服务器错误"
|
||||
// @Router /api/v1/admin/logs/operation [get]
|
||||
// @Router /api/v1/logs/operation [get]
|
||||
func (h *LogHandler) GetOperationLogs(c *gin.Context) {
|
||||
var req service.ListOperationLogRequest
|
||||
if err := c.ShouldBindQuery(&req); err != nil {
|
||||
@@ -229,7 +229,7 @@ func (h *LogHandler) GetOperationLogs(c *gin.Context) {
|
||||
// @Success 200 {file} file "CSV文件"
|
||||
// @Failure 403 {object} Response "无权限"
|
||||
// @Failure 500 {object} Response "服务器错误"
|
||||
// @Router /api/v1/admin/logs/login/export [get]
|
||||
// @Router /api/v1/logs/login/export [get]
|
||||
func (h *LogHandler) ExportLoginLogs(c *gin.Context) {
|
||||
var req service.ExportLoginLogRequest
|
||||
if err := c.ShouldBindQuery(&req); err != nil {
|
||||
|
||||
@@ -41,7 +41,7 @@ type ValidateResetTokenRequest struct {
|
||||
// @Param request body ForgotPasswordRequest true "邮箱地址"
|
||||
// @Success 200 {object} Response "密码重置邮件已发送"
|
||||
// @Failure 400 {object} Response "请求参数错误"
|
||||
// @Router /api/v1/auth/password/forgot [post]
|
||||
// @Router /api/v1/auth/forgot-password [post]
|
||||
func (h *PasswordResetHandler) ForgotPassword(c *gin.Context) {
|
||||
var req struct {
|
||||
Email string `json:"email" binding:"required"`
|
||||
@@ -95,7 +95,7 @@ func (h *PasswordResetHandler) ValidateResetToken(c *gin.Context) {
|
||||
// @Param request body ResetPasswordRequest true "重置请求"
|
||||
// @Success 200 {object} Response "密码重置成功"
|
||||
// @Failure 400 {object} Response "请求参数错误"
|
||||
// @Router /api/v1/auth/password/reset [post]
|
||||
// @Router /api/v1/auth/reset-password [post]
|
||||
func (h *PasswordResetHandler) ResetPassword(c *gin.Context) {
|
||||
var req struct {
|
||||
Token string `json:"token" binding:"required"`
|
||||
@@ -130,7 +130,7 @@ type ForgotPasswordByPhoneRequest struct {
|
||||
// @Success 200 {object} Response "验证码发送成功"
|
||||
// @Failure 400 {object} Response "请求参数错误"
|
||||
// @Failure 503 {object} Response "短信服务未配置"
|
||||
// @Router /api/v1/auth/password/sms/forgot [post]
|
||||
// @Router /api/v1/auth/forgot-password/phone [post]
|
||||
func (h *PasswordResetHandler) ForgotPasswordByPhone(c *gin.Context) {
|
||||
if h.smsService == nil {
|
||||
c.JSON(http.StatusServiceUnavailable, gin.H{"code": 503, "message": "SMS service not configured"})
|
||||
@@ -187,7 +187,7 @@ type ResetPasswordByPhoneRequest struct {
|
||||
// @Failure 400 {object} Response "请求参数错误"
|
||||
// @Failure 401 {object} Response "验证码错误"
|
||||
// @Failure 503 {object} Response "短信服务未配置"
|
||||
// @Router /api/v1/auth/password/sms/reset [post]
|
||||
// @Router /api/v1/auth/reset-password/phone [post]
|
||||
func (h *PasswordResetHandler) ResetPasswordByPhone(c *gin.Context) {
|
||||
var req ResetPasswordByPhoneRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
|
||||
@@ -28,7 +28,7 @@ func NewPermissionHandler(permissionService *service.PermissionService) *Permiss
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param request body service.CreatePermissionRequest true "权限信息"
|
||||
// @Success 201 {object} Response{data=domain.Permission} "创建成功"
|
||||
// @Success 201 {object} Response{data=SwaggerPermission} "创建成功"
|
||||
// @Failure 400 {object} Response "请求参数错误"
|
||||
// @Failure 403 {object} Response "无权限"
|
||||
// @Router /api/v1/permissions [post]
|
||||
@@ -58,7 +58,7 @@ func (h *PermissionHandler) CreatePermission(c *gin.Context) {
|
||||
// @Tags 权限管理
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Success 200 {object} Response{data=[]domain.Permission} "权限列表"
|
||||
// @Success 200 {object} Response{data=[]SwaggerPermission} "权限列表"
|
||||
// @Router /api/v1/permissions [get]
|
||||
func (h *PermissionHandler) ListPermissions(c *gin.Context) {
|
||||
var req service.ListPermissionRequest
|
||||
@@ -87,7 +87,7 @@ func (h *PermissionHandler) ListPermissions(c *gin.Context) {
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "权限ID"
|
||||
// @Success 200 {object} Response{data=domain.Permission} "权限信息"
|
||||
// @Success 200 {object} Response{data=SwaggerPermission} "权限信息"
|
||||
// @Failure 404 {object} Response "权限不存在"
|
||||
// @Router /api/v1/permissions/{id} [get]
|
||||
func (h *PermissionHandler) GetPermission(c *gin.Context) {
|
||||
@@ -119,7 +119,7 @@ func (h *PermissionHandler) GetPermission(c *gin.Context) {
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "权限ID"
|
||||
// @Param request body service.UpdatePermissionRequest true "更新信息"
|
||||
// @Success 200 {object} Response{data=domain.Permission} "更新成功"
|
||||
// @Success 200 {object} Response{data=SwaggerPermission} "更新成功"
|
||||
// @Failure 400 {object} Response "请求参数错误"
|
||||
// @Failure 403 {object} Response "无权限"
|
||||
// @Failure 404 {object} Response "权限不存在"
|
||||
@@ -237,7 +237,7 @@ func (h *PermissionHandler) UpdatePermissionStatus(c *gin.Context) {
|
||||
// @Tags 权限管理
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Success 200 {object} Response{data=[]domain.Permission} "权限树"
|
||||
// @Success 200 {object} Response{data=[]SwaggerPermission} "权限树"
|
||||
// @Router /api/v1/permissions/tree [get]
|
||||
func (h *PermissionHandler) GetPermissionTree(c *gin.Context) {
|
||||
tree, err := h.permissionService.GetPermissionTree(c.Request.Context())
|
||||
|
||||
@@ -663,7 +663,7 @@ func TestPermissionHandler_DeletePermission_Success(t *testing.T) {
|
||||
|
||||
// If creation succeeded, try to delete
|
||||
if permID > 0 {
|
||||
resp2, _ := doDelete(server.URL + "/api/v1/permissions/" + strconv.Itoa(permID), token)
|
||||
resp2, _ := doDelete(server.URL+"/api/v1/permissions/"+strconv.Itoa(permID), token)
|
||||
defer resp2.Body.Close()
|
||||
assert.Equal(t, http.StatusOK, resp2.StatusCode, "should delete permission")
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ func NewRoleHandler(roleService *service.RoleService) *RoleHandler {
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param request body service.CreateRoleRequest true "角色信息"
|
||||
// @Success 201 {object} Response{data=domain.Role} "角色创建成功"
|
||||
// @Success 201 {object} Response{data=SwaggerRole} "角色创建成功"
|
||||
// @Failure 400 {object} Response "请求参数错误"
|
||||
// @Failure 403 {object} Response "无权限"
|
||||
// @Router /api/v1/roles [post]
|
||||
@@ -90,7 +90,7 @@ func (h *RoleHandler) ListRoles(c *gin.Context) {
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "角色ID"
|
||||
// @Success 200 {object} Response{data=domain.Role} "角色信息"
|
||||
// @Success 200 {object} Response{data=SwaggerRole} "角色信息"
|
||||
// @Failure 404 {object} Response "角色不存在"
|
||||
// @Router /api/v1/roles/{id} [get]
|
||||
func (h *RoleHandler) GetRole(c *gin.Context) {
|
||||
@@ -122,7 +122,7 @@ func (h *RoleHandler) GetRole(c *gin.Context) {
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "角色ID"
|
||||
// @Param request body service.UpdateRoleRequest true "更新信息"
|
||||
// @Success 200 {object} Response{data=domain.Role} "更新成功"
|
||||
// @Success 200 {object} Response{data=SwaggerRole} "更新成功"
|
||||
// @Failure 400 {object} Response "请求参数错误"
|
||||
// @Failure 403 {object} Response "无权限"
|
||||
// @Failure 404 {object} Response "角色不存在"
|
||||
@@ -242,7 +242,7 @@ func (h *RoleHandler) UpdateRoleStatus(c *gin.Context) {
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "角色ID"
|
||||
// @Success 200 {object} Response{data=[]domain.Permission} "权限列表"
|
||||
// @Success 200 {object} Response{data=[]SwaggerPermission} "权限列表"
|
||||
// @Failure 404 {object} Response "角色不存在"
|
||||
// @Router /api/v1/roles/{id}/permissions [get]
|
||||
func (h *RoleHandler) GetRolePermissions(c *gin.Context) {
|
||||
@@ -278,7 +278,7 @@ func (h *RoleHandler) GetRolePermissions(c *gin.Context) {
|
||||
// @Failure 400 {object} Response "请求参数错误"
|
||||
// @Failure 403 {object} Response "无权限"
|
||||
// @Failure 404 {object} Response "角色不存在"
|
||||
// @Router /api/v1/roles/{id}/permissions [post]
|
||||
// @Router /api/v1/roles/{id}/permissions [put]
|
||||
func (h *RoleHandler) AssignPermissions(c *gin.Context) {
|
||||
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
|
||||
@@ -43,7 +43,7 @@ func NewSMSHandler(authService *service.AuthService, smsCodeService *service.SMS
|
||||
// @Success 200 {object} Response "发送成功"
|
||||
// @Failure 400 {object} Response "请求参数错误"
|
||||
// @Failure 503 {object} Response "短信服务未配置"
|
||||
// @Router /api/v1/sms/send [post]
|
||||
// @Router /api/v1/auth/send-code [post]
|
||||
func (h *SMSHandler) SendCode(c *gin.Context) {
|
||||
if h.smsCodeService == nil {
|
||||
c.JSON(http.StatusServiceUnavailable, gin.H{"code": 503, "message": "SMS service not configured"})
|
||||
@@ -80,7 +80,7 @@ func (h *SMSHandler) SendCode(c *gin.Context) {
|
||||
// @Failure 400 {object} Response "请求参数错误"
|
||||
// @Failure 401 {object} Response "验证码错误"
|
||||
// @Failure 503 {object} Response "短信登录未配置"
|
||||
// @Router /api/v1/sms/login [post]
|
||||
// @Router /api/v1/auth/login/code [post]
|
||||
func (h *SMSHandler) LoginByCode(c *gin.Context) {
|
||||
if h.authService == nil {
|
||||
c.JSON(http.StatusServiceUnavailable, gin.H{"code": 503, "message": "SMS login not configured"})
|
||||
|
||||
@@ -3,6 +3,7 @@ package handler
|
||||
import (
|
||||
"crypto/subtle"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -35,14 +36,14 @@ type AuthorizeRequest struct {
|
||||
|
||||
// Authorize 处理 SSO 授权请求
|
||||
// @Summary SSO 授权
|
||||
// @Description 处理 SSO 授权请求,返回授权码或访问令牌
|
||||
// @Description 处理 SSO 授权请求,返回授权码
|
||||
// @Tags SSO
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param client_id query string true "客户端ID"
|
||||
// @Param redirect_uri query string true "回调地址"
|
||||
// @Param response_type query string true "响应类型" Enums(code, token)
|
||||
// @Param response_type query string true "响应类型" Enums(code)
|
||||
// @Param scope query string false "授权范围"
|
||||
// @Param state query string false "状态参数"
|
||||
// @Success 302 {string} string "重定向到回调地址"
|
||||
@@ -57,21 +58,16 @@ func (h *SSOHandler) Authorize(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// 验证 response_type
|
||||
if req.ResponseType != "code" && req.ResponseType != "token" {
|
||||
if req.ResponseType != "code" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": "unsupported response_type"})
|
||||
return
|
||||
}
|
||||
|
||||
// 验证 redirect_uri 是否在白名单中
|
||||
if h.clientsStore != nil {
|
||||
if !h.clientsStore.ValidateClientRedirectURI(req.ClientID, req.RedirectURI) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": "invalid redirect_uri"})
|
||||
return
|
||||
}
|
||||
if h.clientsStore == nil || !h.clientsStore.ValidateClientRedirectURI(req.ClientID, req.RedirectURI) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": "invalid redirect_uri"})
|
||||
return
|
||||
}
|
||||
|
||||
// 获取当前登录用户(从 auth middleware 设置的 context)
|
||||
userID, ok := getUserIDFromContext(c)
|
||||
if !ok {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"code": 401, "message": "unauthorized"})
|
||||
@@ -84,60 +80,23 @@ func (h *SSOHandler) Authorize(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// 生成授权码或 access token
|
||||
if req.ResponseType == "code" {
|
||||
code, err := h.ssoManager.GenerateAuthorizationCode(
|
||||
req.ClientID,
|
||||
req.RedirectURI,
|
||||
req.Scope,
|
||||
userID,
|
||||
username,
|
||||
)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"code": 500, "message": "failed to generate code"})
|
||||
return
|
||||
}
|
||||
|
||||
// 重定向回客户端
|
||||
redirectURL := req.RedirectURI + "?code=" + code
|
||||
if req.State != "" {
|
||||
redirectURL += "&state=" + req.State
|
||||
}
|
||||
c.Redirect(http.StatusFound, redirectURL)
|
||||
} else {
|
||||
// implicit 模式,直接返回 token
|
||||
code, err := h.ssoManager.GenerateAuthorizationCode(
|
||||
req.ClientID,
|
||||
req.RedirectURI,
|
||||
req.Scope,
|
||||
userID,
|
||||
username,
|
||||
)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"code": 500, "message": "failed to generate code"})
|
||||
return
|
||||
}
|
||||
|
||||
// 验证授权码获取 session
|
||||
session, err := h.ssoManager.ValidateAuthorizationCode(code)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"code": 500, "message": "failed to validate code"})
|
||||
return
|
||||
}
|
||||
|
||||
token, _, err := h.ssoManager.GenerateAccessToken(req.ClientID, session)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"code": 500, "message": "failed to generate token"})
|
||||
return
|
||||
}
|
||||
|
||||
// 重定向回客户端,带 token
|
||||
redirectURL := req.RedirectURI + "#access_token=" + token + "&expires_in=7200"
|
||||
if req.State != "" {
|
||||
redirectURL += "&state=" + req.State
|
||||
}
|
||||
c.Redirect(http.StatusFound, redirectURL)
|
||||
code, err := h.ssoManager.GenerateAuthorizationCode(
|
||||
req.ClientID,
|
||||
req.RedirectURI,
|
||||
req.Scope,
|
||||
userID,
|
||||
username,
|
||||
)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"code": 500, "message": "failed to generate code"})
|
||||
return
|
||||
}
|
||||
|
||||
redirectURL := req.RedirectURI + "?code=" + code
|
||||
if req.State != "" {
|
||||
redirectURL += "&state=" + req.State
|
||||
}
|
||||
c.Redirect(http.StatusFound, redirectURL)
|
||||
}
|
||||
|
||||
// TokenRequest Token 请求
|
||||
@@ -161,14 +120,14 @@ type TokenResponse struct {
|
||||
// @Summary 获取 Access Token
|
||||
// @Description 使用授权码获取 Access Token(授权码模式第二步)
|
||||
// @Tags SSO
|
||||
// @Accept json
|
||||
// @Accept x-www-form-urlencoded
|
||||
// @Produce json
|
||||
// @Param grant_type formData string true "授权类型" Enums(authorization_code)
|
||||
// @Param code formData string false "授权码"
|
||||
// @Param redirect_uri formData string false "回调地址"
|
||||
// @Param code formData string true "授权码"
|
||||
// @Param redirect_uri formData string true "回调地址"
|
||||
// @Param client_id formData string true "客户端ID"
|
||||
// @Param client_secret formData string true "客户端密钥"
|
||||
// @Success 200 {object} TokenResponse "访问令牌响应"
|
||||
// @Success 200 {object} Response{data=TokenResponse} "访问令牌响应"
|
||||
// @Failure 400 {object} Response "请求参数错误"
|
||||
// @Failure 401 {object} Response "客户端认证失败"
|
||||
// @Failure 500 {object} Response "服务器错误"
|
||||
@@ -180,45 +139,50 @@ func (h *SSOHandler) Token(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// 验证 grant_type
|
||||
if req.GrantType != "authorization_code" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": "unsupported grant_type"})
|
||||
return
|
||||
}
|
||||
|
||||
// 验证客户端凭证
|
||||
if h.clientsStore != nil {
|
||||
client, err := h.clientsStore.GetByClientID(req.ClientID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"code": 401, "message": "invalid client"})
|
||||
return
|
||||
}
|
||||
// 使用常量时间比较防止时序攻击
|
||||
if subtle.ConstantTimeCompare([]byte(req.ClientSecret), []byte(client.ClientSecret)) != 1 {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"code": 401, "message": "invalid client_secret"})
|
||||
return
|
||||
}
|
||||
if req.Code == "" || req.RedirectURI == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": "code and redirect_uri are required"})
|
||||
return
|
||||
}
|
||||
|
||||
client, ok := h.authenticateClient(req.ClientID, req.ClientSecret)
|
||||
if !ok {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"code": 401, "message": "invalid client credentials"})
|
||||
return
|
||||
}
|
||||
if !h.clientsStore.ValidateClientRedirectURI(client.ClientID, req.RedirectURI) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": "invalid redirect_uri"})
|
||||
return
|
||||
}
|
||||
|
||||
// 验证授权码
|
||||
session, err := h.ssoManager.ValidateAuthorizationCode(req.Code)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"code": 401, "message": "invalid code"})
|
||||
return
|
||||
}
|
||||
if session.ClientID != req.ClientID || session.RedirectURI != req.RedirectURI {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": "authorization code does not match client or redirect_uri"})
|
||||
return
|
||||
}
|
||||
|
||||
// 生成 access token
|
||||
token, expiresAt, err := h.ssoManager.GenerateAccessToken(req.ClientID, session)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"code": 500, "message": "failed to generate token"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, TokenResponse{
|
||||
AccessToken: token,
|
||||
TokenType: "Bearer",
|
||||
ExpiresIn: int64(time.Until(expiresAt).Seconds()),
|
||||
Scope: session.Scope,
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": TokenResponse{
|
||||
AccessToken: token,
|
||||
TokenType: "Bearer",
|
||||
ExpiresIn: int64(time.Until(expiresAt).Seconds()),
|
||||
Scope: session.Scope,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -241,33 +205,46 @@ type IntrospectResponse struct {
|
||||
// @Summary 验证 Access Token
|
||||
// @Description 验证 Access Token 的有效性并返回相关信息
|
||||
// @Tags SSO
|
||||
// @Accept json
|
||||
// @Accept x-www-form-urlencoded
|
||||
// @Produce json
|
||||
// @Param token formData string true "Access Token"
|
||||
// @Param client_id formData string false "客户端ID"
|
||||
// @Success 200 {object} IntrospectResponse "Token信息"
|
||||
// @Param client_id formData string true "客户端ID"
|
||||
// @Param client_secret formData string true "客户端密钥"
|
||||
// @Success 200 {object} Response{data=IntrospectResponse} "Token信息"
|
||||
// @Failure 400 {object} Response "请求参数错误"
|
||||
// @Failure 500 {object} Response "服务器错误"
|
||||
// @Failure 401 {object} Response "客户端认证失败"
|
||||
// @Router /api/v1/sso/introspect [post]
|
||||
func (h *SSOHandler) Introspect(c *gin.Context) {
|
||||
var req IntrospectRequest
|
||||
var req struct {
|
||||
Token string `form:"token" binding:"required"`
|
||||
ClientID string `form:"client_id" binding:"required"`
|
||||
ClientSecret string `form:"client_secret" binding:"required"`
|
||||
}
|
||||
if err := c.ShouldBind(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": err.Error()})
|
||||
return
|
||||
}
|
||||
if _, ok := h.authenticateClient(req.ClientID, req.ClientSecret); !ok {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"code": 401, "message": "invalid client credentials"})
|
||||
return
|
||||
}
|
||||
|
||||
info, err := h.ssoManager.IntrospectToken(req.Token)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, IntrospectResponse{Active: false})
|
||||
c.JSON(http.StatusOK, gin.H{"code": 0, "message": "success", "data": IntrospectResponse{Active: false}})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, IntrospectResponse{
|
||||
Active: info.Active,
|
||||
UserID: info.UserID,
|
||||
Username: info.Username,
|
||||
ExpiresAt: info.ExpiresAt.Unix(),
|
||||
Scope: info.Scope,
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": IntrospectResponse{
|
||||
Active: info.Active,
|
||||
UserID: info.UserID,
|
||||
Username: info.Username,
|
||||
ExpiresAt: info.ExpiresAt.Unix(),
|
||||
Scope: info.Scope,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -280,22 +257,30 @@ type RevokeRequest struct {
|
||||
// @Summary 撤销 Access Token
|
||||
// @Description 撤销指定的 Access Token
|
||||
// @Tags SSO
|
||||
// @Accept json
|
||||
// @Accept x-www-form-urlencoded
|
||||
// @Produce json
|
||||
// @Param token formData string true "Access Token"
|
||||
// @Param client_id formData string true "客户端ID"
|
||||
// @Param client_secret formData string true "客户端密钥"
|
||||
// @Success 200 {object} Response "撤销成功"
|
||||
// @Failure 400 {object} Response "请求参数错误"
|
||||
// @Failure 500 {object} Response "服务器错误"
|
||||
// @Failure 401 {object} Response "客户端认证失败"
|
||||
// @Router /api/v1/sso/revoke [post]
|
||||
func (h *SSOHandler) Revoke(c *gin.Context) {
|
||||
var req RevokeRequest
|
||||
var req struct {
|
||||
Token string `form:"token" binding:"required"`
|
||||
ClientID string `form:"client_id" binding:"required"`
|
||||
ClientSecret string `form:"client_secret" binding:"required"`
|
||||
}
|
||||
if err := c.ShouldBind(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
h.ssoManager.RevokeToken(req.Token)
|
||||
|
||||
if _, ok := h.authenticateClient(req.ClientID, req.ClientSecret); !ok {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"code": 401, "message": "invalid client credentials"})
|
||||
return
|
||||
}
|
||||
_ = h.ssoManager.RevokeToken(req.Token)
|
||||
c.JSON(http.StatusOK, gin.H{"code": 0, "message": "token revoked"})
|
||||
}
|
||||
|
||||
@@ -307,24 +292,23 @@ type UserInfoResponse struct {
|
||||
|
||||
// UserInfo 获取当前用户信息
|
||||
// @Summary 获取 SSO 用户信息
|
||||
// @Description 获取当前通过 SSO 授权的用户信息
|
||||
// @Description 获取当前通过 SSO Access Token 授权的用户信息
|
||||
// @Tags SSO
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Success 200 {object} Response{data=UserInfoResponse} "用户信息"
|
||||
// @Failure 401 {object} Response "未认证"
|
||||
// @Failure 500 {object} Response "服务器错误"
|
||||
// @Router /api/v1/sso/userinfo [get]
|
||||
func (h *SSOHandler) UserInfo(c *gin.Context) {
|
||||
userID, ok := getUserIDFromContext(c)
|
||||
if !ok {
|
||||
token := extractBearerToken(c)
|
||||
if token == "" {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"code": 401, "message": "unauthorized"})
|
||||
return
|
||||
}
|
||||
|
||||
username, ok := getUsernameFromContext(c)
|
||||
if !ok {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"code": 401, "message": "unauthorized"})
|
||||
session, err := h.ssoManager.ValidateAccessToken(token)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"code": 401, "message": "invalid access token"})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -332,8 +316,30 @@ func (h *SSOHandler) UserInfo(c *gin.Context) {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": UserInfoResponse{
|
||||
UserID: userID,
|
||||
Username: username,
|
||||
UserID: session.UserID,
|
||||
Username: session.Username,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (h *SSOHandler) authenticateClient(clientID, clientSecret string) (*auth.SSOClient, bool) {
|
||||
if h.clientsStore == nil {
|
||||
return nil, false
|
||||
}
|
||||
client, err := h.clientsStore.GetByClientID(clientID)
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
if subtle.ConstantTimeCompare([]byte(clientSecret), []byte(client.ClientSecret)) != 1 {
|
||||
return nil, false
|
||||
}
|
||||
return client, true
|
||||
}
|
||||
|
||||
func extractBearerToken(c *gin.Context) string {
|
||||
authorization := c.GetHeader("Authorization")
|
||||
if !strings.HasPrefix(authorization, "Bearer ") {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(strings.TrimPrefix(authorization, "Bearer "))
|
||||
}
|
||||
|
||||
@@ -1,347 +1,327 @@
|
||||
package handler_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
// =============================================================================
|
||||
// SSOHandler Tests - Single Sign-On
|
||||
// =============================================================================
|
||||
type ssoWrappedResponse struct {
|
||||
Code int `json:"code"`
|
||||
Message string `json:"message"`
|
||||
Data json.RawMessage `json:"data"`
|
||||
}
|
||||
|
||||
// TestSSOHandler_Authorize_CodeFlow 验证授权码流程
|
||||
func TestSSOHandler_Authorize_CodeFlow(t *testing.T) {
|
||||
type ssoTokenPayload struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresIn int64 `json:"expires_in"`
|
||||
Scope string `json:"scope"`
|
||||
}
|
||||
|
||||
type ssoIntrospectPayload struct {
|
||||
Active bool `json:"active"`
|
||||
UserID int64 `json:"user_id"`
|
||||
Username string `json:"username"`
|
||||
Scope string `json:"scope"`
|
||||
}
|
||||
|
||||
type ssoUserInfoPayload struct {
|
||||
UserID int64 `json:"user_id"`
|
||||
Username string `json:"username"`
|
||||
}
|
||||
|
||||
func doSSOAuthorizeRequest(t *testing.T, rawURL, bearer string) *http.Response {
|
||||
t.Helper()
|
||||
|
||||
req, err := http.NewRequest(http.MethodGet, rawURL, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("build authorize request: %v", err)
|
||||
}
|
||||
if bearer != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+bearer)
|
||||
}
|
||||
|
||||
client := &http.Client{CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
||||
return http.ErrUseLastResponse
|
||||
}}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("execute authorize request: %v", err)
|
||||
}
|
||||
return resp
|
||||
}
|
||||
|
||||
func doSSOFormPost(t *testing.T, rawURL string, form url.Values, bearer string) (*http.Response, []byte) {
|
||||
t.Helper()
|
||||
|
||||
req, err := http.NewRequest(http.MethodPost, rawURL, strings.NewReader(form.Encode()))
|
||||
if err != nil {
|
||||
t.Fatalf("build form request: %v", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
if bearer != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+bearer)
|
||||
}
|
||||
|
||||
resp, err := (&http.Client{}).Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("execute form request: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body := new(bytes.Buffer)
|
||||
if _, err := body.ReadFrom(resp.Body); err != nil {
|
||||
t.Fatalf("read form response: %v", err)
|
||||
}
|
||||
return resp, body.Bytes()
|
||||
}
|
||||
|
||||
func decodeSSOWrappedResponse(t *testing.T, body []byte) ssoWrappedResponse {
|
||||
t.Helper()
|
||||
|
||||
var wrapped ssoWrappedResponse
|
||||
if err := json.Unmarshal(body, &wrapped); err != nil {
|
||||
t.Fatalf("decode wrapped response failed: %v body=%s", err, string(body))
|
||||
}
|
||||
return wrapped
|
||||
}
|
||||
|
||||
func extractAuthorizationCode(t *testing.T, location string) string {
|
||||
t.Helper()
|
||||
|
||||
parsed, err := url.Parse(location)
|
||||
if err != nil {
|
||||
t.Fatalf("parse redirect location failed: %v", err)
|
||||
}
|
||||
code := parsed.Query().Get("code")
|
||||
if code == "" {
|
||||
t.Fatalf("redirect location missing code: %s", location)
|
||||
}
|
||||
return code
|
||||
}
|
||||
|
||||
func issueSSOAuthCode(t *testing.T, serverURL, bearer string) string {
|
||||
t.Helper()
|
||||
|
||||
resp := doSSOAuthorizeRequest(t, serverURL+"/api/v1/sso/authorize?client_id=test-client&redirect_uri=http://localhost/callback&response_type=code&scope=profile&state=abc", bearer)
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusFound {
|
||||
t.Fatalf("authorize expected 302, got %d", resp.StatusCode)
|
||||
}
|
||||
location := resp.Header.Get("Location")
|
||||
if location == "" {
|
||||
t.Fatal("authorize redirect missing Location header")
|
||||
}
|
||||
return extractAuthorizationCode(t, location)
|
||||
}
|
||||
|
||||
func exchangeSSOToken(t *testing.T, serverURL, code, redirectURI string) ssoTokenPayload {
|
||||
t.Helper()
|
||||
|
||||
resp, body := doSSOFormPost(t, serverURL+"/api/v1/sso/token", url.Values{
|
||||
"grant_type": {"authorization_code"},
|
||||
"code": {code},
|
||||
"client_id": {"test-client"},
|
||||
"client_secret": {"test-secret"},
|
||||
"redirect_uri": {redirectURI},
|
||||
}, "")
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("token exchange expected 200, got %d body=%s", resp.StatusCode, string(body))
|
||||
}
|
||||
|
||||
wrapped := decodeSSOWrappedResponse(t, body)
|
||||
if wrapped.Code != 0 {
|
||||
t.Fatalf("token exchange expected code=0, got %d body=%s", wrapped.Code, string(body))
|
||||
}
|
||||
|
||||
var payload ssoTokenPayload
|
||||
if err := json.Unmarshal(wrapped.Data, &payload); err != nil {
|
||||
t.Fatalf("decode token payload failed: %v body=%s", err, string(body))
|
||||
}
|
||||
if payload.AccessToken == "" {
|
||||
t.Fatalf("token exchange returned empty access token: %s", string(body))
|
||||
}
|
||||
return payload
|
||||
}
|
||||
|
||||
func TestSSOHandler_Authorize_CodeFlowRedirectsWithCodeAndState(t *testing.T) {
|
||||
server, cleanup := setupHandlerTestServer(t)
|
||||
defer cleanup()
|
||||
|
||||
// Register and login user
|
||||
registerUser(server.URL, "ssouser", "sso@test.com", "Pass123!")
|
||||
token := getToken(server.URL, "ssouser", "Pass123!")
|
||||
assert.NotEmpty(t, token)
|
||||
platformToken := getToken(server.URL, "ssouser", "Pass123!")
|
||||
if platformToken == "" {
|
||||
t.Fatal("expected login token for authorize flow")
|
||||
}
|
||||
|
||||
// Request authorization with code flow
|
||||
resp, _ := doGet(server.URL+"/api/v1/sso/authorize?client_id=test-client&redirect_uri=http://localhost/callback&response_type=code&state=xyz", token)
|
||||
resp := doSSOAuthorizeRequest(t, server.URL+"/api/v1/sso/authorize?client_id=test-client&redirect_uri=http://localhost/callback&response_type=code&scope=profile&state=xyz", platformToken)
|
||||
defer resp.Body.Close()
|
||||
|
||||
// SSO may return various status codes based on configuration
|
||||
assert.True(t, resp.StatusCode == http.StatusFound || resp.StatusCode == http.StatusBadRequest ||
|
||||
resp.StatusCode == http.StatusInternalServerError || resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusUnauthorized,
|
||||
"should handle authorize request, got %d", resp.StatusCode)
|
||||
if resp.StatusCode != http.StatusFound {
|
||||
t.Fatalf("authorize expected 302, got %d", resp.StatusCode)
|
||||
}
|
||||
location := resp.Header.Get("Location")
|
||||
if location == "" {
|
||||
t.Fatal("authorize redirect missing Location header")
|
||||
}
|
||||
if !strings.Contains(location, "code=") {
|
||||
t.Fatalf("authorize redirect missing code: %s", location)
|
||||
}
|
||||
if !strings.Contains(location, "state=xyz") {
|
||||
t.Fatalf("authorize redirect missing state: %s", location)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSSOHandler_Authorize_TokenFlow 验证隐式授权流程
|
||||
func TestSSOHandler_Authorize_TokenFlow(t *testing.T) {
|
||||
func TestSSOHandler_Authorize_ImplicitFlowRejected(t *testing.T) {
|
||||
server, cleanup := setupHandlerTestServer(t)
|
||||
defer cleanup()
|
||||
|
||||
registerUser(server.URL, "ssouser2", "sso2@test.com", "Pass123!")
|
||||
token := getToken(server.URL, "ssouser2", "Pass123!")
|
||||
assert.NotEmpty(t, token)
|
||||
platformToken := getToken(server.URL, "ssouser2", "Pass123!")
|
||||
if platformToken == "" {
|
||||
t.Fatal("expected login token for implicit rejection test")
|
||||
}
|
||||
|
||||
// Request authorization with token flow
|
||||
resp, _ := doGet(server.URL+"/api/v1/sso/authorize?client_id=test-client&redirect_uri=http://localhost/callback&response_type=token&state=abc", token)
|
||||
resp := doSSOAuthorizeRequest(t, server.URL+"/api/v1/sso/authorize?client_id=test-client&redirect_uri=http://localhost/callback&response_type=token", platformToken)
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.True(t, resp.StatusCode == http.StatusFound || resp.StatusCode == http.StatusBadRequest ||
|
||||
resp.StatusCode == http.StatusInternalServerError || resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusUnauthorized,
|
||||
"should handle token flow, got %d", resp.StatusCode)
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("implicit flow expected 400, got %d", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSSOHandler_Authorize_MissingParams 验证缺少参数
|
||||
func TestSSOHandler_Authorize_MissingParams(t *testing.T) {
|
||||
func TestSSOHandler_Token_ExchangesWithoutPlatformBearerAuth(t *testing.T) {
|
||||
server, cleanup := setupHandlerTestServer(t)
|
||||
defer cleanup()
|
||||
|
||||
registerUser(server.URL, "ssouser3", "sso3@test.com", "Pass123!")
|
||||
token := getToken(server.URL, "ssouser3", "Pass123!")
|
||||
|
||||
// Missing params - handler may enforce or not based on config
|
||||
resp1, _ := doGet(server.URL+"/api/v1/sso/authorize?redirect_uri=http://localhost&response_type=code", token)
|
||||
defer resp1.Body.Close()
|
||||
assert.True(t, resp1.StatusCode >= http.StatusBadRequest || resp1.StatusCode == http.StatusOK,
|
||||
"should handle missing client_id, got %d", resp1.StatusCode)
|
||||
|
||||
// Missing redirect_uri
|
||||
resp2, _ := doGet(server.URL+"/api/v1/sso/authorize?client_id=test&response_type=code", token)
|
||||
defer resp2.Body.Close()
|
||||
assert.True(t, resp2.StatusCode >= http.StatusBadRequest || resp2.StatusCode == http.StatusOK,
|
||||
"should handle missing redirect_uri, got %d", resp2.StatusCode)
|
||||
|
||||
// Missing response_type
|
||||
resp3, _ := doGet(server.URL+"/api/v1/sso/authorize?client_id=test&redirect_uri=http://localhost", token)
|
||||
defer resp3.Body.Close()
|
||||
assert.True(t, resp3.StatusCode >= http.StatusBadRequest || resp3.StatusCode == http.StatusOK,
|
||||
"should handle missing response_type, got %d", resp3.StatusCode)
|
||||
}
|
||||
|
||||
// TestSSOHandler_Authorize_InvalidResponseType 验证无效响应类型
|
||||
func TestSSOHandler_Authorize_InvalidResponseType(t *testing.T) {
|
||||
server, cleanup := setupHandlerTestServer(t)
|
||||
defer cleanup()
|
||||
|
||||
registerUser(server.URL, "ssouser4", "sso4@test.com", "Pass123!")
|
||||
token := getToken(server.URL, "ssouser4", "Pass123!")
|
||||
|
||||
resp, _ := doGet(server.URL+"/api/v1/sso/authorize?client_id=test&redirect_uri=http://localhost&response_type=invalid", token)
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.True(t, resp.StatusCode >= http.StatusBadRequest || resp.StatusCode == http.StatusOK,
|
||||
"should handle invalid response_type, got %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
// TestSSOHandler_Authorize_Unauthorized 验证未认证用户
|
||||
func TestSSOHandler_Authorize_Unauthorized(t *testing.T) {
|
||||
server, cleanup := setupHandlerTestServer(t)
|
||||
defer cleanup()
|
||||
|
||||
// No authentication token
|
||||
resp, _ := doGet(server.URL+"/api/v1/sso/authorize?client_id=test&redirect_uri=http://localhost&response_type=code", "")
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.True(t, resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusBadRequest,
|
||||
"should handle unauthorized request, got %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
// TestSSOHandler_Token_Success 验证获取 Token
|
||||
func TestSSOHandler_Token_Success(t *testing.T) {
|
||||
server, cleanup := setupHandlerTestServer(t)
|
||||
defer cleanup()
|
||||
|
||||
// Try to exchange code for token using doPost helper
|
||||
resp, _ := doPost(server.URL+"/api/v1/sso/token", "", map[string]interface{}{
|
||||
"grant_type": "authorization_code",
|
||||
"code": "invalid-code",
|
||||
"client_id": "test",
|
||||
"client_secret": "secret",
|
||||
"redirect_uri": "http://localhost",
|
||||
})
|
||||
defer resp.Body.Close()
|
||||
|
||||
// Handler may accept or reject based on SSO config
|
||||
assert.True(t, resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusBadRequest || resp.StatusCode == http.StatusOK,
|
||||
"should handle token request, got %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
// TestSSOHandler_Token_MissingParams 验证缺少 Token 参数
|
||||
func TestSSOHandler_Token_MissingParams(t *testing.T) {
|
||||
server, cleanup := setupHandlerTestServer(t)
|
||||
defer cleanup()
|
||||
|
||||
// Missing client_id
|
||||
resp1, _ := doPost(server.URL+"/api/v1/sso/token", "", map[string]interface{}{
|
||||
"grant_type": "authorization_code",
|
||||
"code": "test",
|
||||
"client_secret": "secret",
|
||||
})
|
||||
defer resp1.Body.Close()
|
||||
assert.True(t, resp1.StatusCode >= http.StatusBadRequest || resp1.StatusCode == http.StatusOK,
|
||||
"should handle missing client_id, got %d", resp1.StatusCode)
|
||||
|
||||
// Missing client_secret
|
||||
resp2, _ := doPost(server.URL+"/api/v1/sso/token", "", map[string]interface{}{
|
||||
"grant_type": "authorization_code",
|
||||
"code": "test",
|
||||
"client_id": "test",
|
||||
})
|
||||
defer resp2.Body.Close()
|
||||
assert.True(t, resp2.StatusCode >= http.StatusBadRequest || resp2.StatusCode == http.StatusOK,
|
||||
"should handle missing client_secret, got %d", resp2.StatusCode)
|
||||
|
||||
// Missing grant_type
|
||||
resp3, _ := doPost(server.URL+"/api/v1/sso/token", "", map[string]interface{}{
|
||||
"client_id": "test",
|
||||
"client_secret": "secret",
|
||||
"code": "test",
|
||||
})
|
||||
defer resp3.Body.Close()
|
||||
assert.True(t, resp3.StatusCode >= http.StatusBadRequest || resp3.StatusCode == http.StatusOK,
|
||||
"should handle missing grant_type, got %d", resp3.StatusCode)
|
||||
}
|
||||
|
||||
// TestSSOHandler_Token_InvalidGrantType 验证无效授权类型
|
||||
func TestSSOHandler_Token_InvalidGrantType(t *testing.T) {
|
||||
server, cleanup := setupHandlerTestServer(t)
|
||||
defer cleanup()
|
||||
|
||||
resp, _ := doPost(server.URL+"/api/v1/sso/token", "", map[string]interface{}{
|
||||
"grant_type": "invalid_grant",
|
||||
"client_id": "test",
|
||||
"client_secret": "secret",
|
||||
"code": "test",
|
||||
})
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.True(t, resp.StatusCode >= http.StatusBadRequest || resp.StatusCode == http.StatusOK,
|
||||
"should handle invalid grant_type, got %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
// TestSSOHandler_Introspect_Success 验证 Token 验证
|
||||
func TestSSOHandler_Introspect_Success(t *testing.T) {
|
||||
server, cleanup := setupHandlerTestServer(t)
|
||||
defer cleanup()
|
||||
|
||||
// Introspect invalid token
|
||||
resp, body := doPost(server.URL+"/api/v1/sso/introspect", "", map[string]interface{}{
|
||||
"token": "invalid-token",
|
||||
})
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.True(t, resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusBadRequest,
|
||||
"should return introspect response, got %d: %s", resp.StatusCode, body)
|
||||
}
|
||||
|
||||
// TestSSOHandler_Introspect_MissingToken 验证缺少 Token
|
||||
func TestSSOHandler_Introspect_MissingToken(t *testing.T) {
|
||||
server, cleanup := setupHandlerTestServer(t)
|
||||
defer cleanup()
|
||||
|
||||
resp, _ := doPost(server.URL+"/api/v1/sso/introspect", "", map[string]interface{}{
|
||||
"token": "",
|
||||
})
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.True(t, resp.StatusCode >= http.StatusBadRequest || resp.StatusCode == http.StatusOK,
|
||||
"should handle missing token, got %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
// TestSSOHandler_Revoke_Success 验证 Token 撤销
|
||||
func TestSSOHandler_Revoke_Success(t *testing.T) {
|
||||
server, cleanup := setupHandlerTestServer(t)
|
||||
defer cleanup()
|
||||
|
||||
resp, body := doPost(server.URL+"/api/v1/sso/revoke", "", map[string]interface{}{
|
||||
"token": "some-token",
|
||||
})
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.True(t, resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusBadRequest,
|
||||
"should handle revoke request, got %d: %s", resp.StatusCode, body)
|
||||
}
|
||||
|
||||
// TestSSOHandler_Revoke_MissingToken 验证缺少 Token
|
||||
func TestSSOHandler_Revoke_MissingToken(t *testing.T) {
|
||||
server, cleanup := setupHandlerTestServer(t)
|
||||
defer cleanup()
|
||||
|
||||
resp, _ := doPost(server.URL+"/api/v1/sso/revoke", "", map[string]interface{}{
|
||||
"token": "",
|
||||
})
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.True(t, resp.StatusCode >= http.StatusBadRequest || resp.StatusCode == http.StatusOK,
|
||||
"should handle missing token, got %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
// TestSSOHandler_UserInfo_Success 验证获取用户信息
|
||||
func TestSSOHandler_UserInfo_Success(t *testing.T) {
|
||||
server, cleanup := setupHandlerTestServer(t)
|
||||
defer cleanup()
|
||||
|
||||
registerUser(server.URL, "ssouser5", "sso5@test.com", "Pass123!")
|
||||
token := getToken(server.URL, "ssouser5", "Pass123!")
|
||||
assert.NotEmpty(t, token)
|
||||
|
||||
resp, body := doGet(server.URL+"/api/v1/sso/userinfo", token)
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.True(t, resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden,
|
||||
"should handle userinfo request, got %d: %s", resp.StatusCode, body)
|
||||
}
|
||||
|
||||
// TestSSOHandler_UserInfo_Unauthorized 验证未认证访问
|
||||
func TestSSOHandler_UserInfo_Unauthorized(t *testing.T) {
|
||||
server, cleanup := setupHandlerTestServer(t)
|
||||
defer cleanup()
|
||||
|
||||
resp, _ := doGet(server.URL+"/api/v1/sso/userinfo", "")
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.True(t, resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusBadRequest,
|
||||
"should handle unauthorized request, got %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
// TestSSOHandler_FullFlow_Authorization 验证完整授权流程
|
||||
func TestSSOHandler_FullFlow_Authorization(t *testing.T) {
|
||||
server, cleanup := setupHandlerTestServer(t)
|
||||
defer cleanup()
|
||||
|
||||
// Register and login
|
||||
registerUser(server.URL, "flowuser", "flow@test.com", "Pass123!")
|
||||
token := getToken(server.URL, "flowuser", "Pass123!")
|
||||
assert.NotEmpty(t, token)
|
||||
platformToken := getToken(server.URL, "flowuser", "Pass123!")
|
||||
if platformToken == "" {
|
||||
t.Fatal("expected login token for authorization")
|
||||
}
|
||||
|
||||
// Step 1: Authorize (get code or redirect)
|
||||
authResp, _ := doGet(server.URL+"/api/v1/sso/authorize?client_id=test&redirect_uri=http://localhost&response_type=code&scope=profile", token)
|
||||
defer authResp.Body.Close()
|
||||
code := issueSSOAuthCode(t, server.URL, platformToken)
|
||||
payload := exchangeSSOToken(t, server.URL, code, "http://localhost/callback")
|
||||
|
||||
// Step 2: Check response - SSO may return redirect or direct response based on config
|
||||
assert.True(t, authResp.StatusCode == http.StatusFound || authResp.StatusCode == http.StatusOK ||
|
||||
authResp.StatusCode == http.StatusBadRequest || authResp.StatusCode == http.StatusInternalServerError,
|
||||
"should handle authorization, got %d", authResp.StatusCode)
|
||||
|
||||
if authResp.StatusCode == http.StatusFound {
|
||||
location := authResp.Header.Get("Location")
|
||||
assert.Contains(t, location, "localhost")
|
||||
t.Logf("Redirected to: %s", location)
|
||||
if payload.TokenType != "Bearer" {
|
||||
t.Fatalf("unexpected token type: %q", payload.TokenType)
|
||||
}
|
||||
if payload.ExpiresIn <= 0 {
|
||||
t.Fatalf("unexpected expires_in: %d", payload.ExpiresIn)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSSOHandler_ClientCredentials_Validation 验证客户端凭证验证
|
||||
func TestSSOHandler_ClientCredentials_Validation(t *testing.T) {
|
||||
func TestSSOHandler_Token_RedirectURIMismatchRejected(t *testing.T) {
|
||||
server, cleanup := setupHandlerTestServer(t)
|
||||
defer cleanup()
|
||||
|
||||
// Try with invalid client credentials
|
||||
resp, _ := doPost(server.URL+"/api/v1/sso/token", "", map[string]interface{}{
|
||||
"grant_type": "authorization_code",
|
||||
"code": "test-code",
|
||||
"client_id": "invalid-client",
|
||||
"client_secret": "wrong-secret",
|
||||
"redirect_uri": "http://localhost",
|
||||
})
|
||||
defer resp.Body.Close()
|
||||
registerUser(server.URL, "mismatchuser", "mismatch@test.com", "Pass123!")
|
||||
platformToken := getToken(server.URL, "mismatchuser", "Pass123!")
|
||||
if platformToken == "" {
|
||||
t.Fatal("expected login token for authorization")
|
||||
}
|
||||
|
||||
// May accept or reject based on SSO configuration
|
||||
assert.True(t, resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusBadRequest || resp.StatusCode == http.StatusOK,
|
||||
"should handle client credentials, got %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
// TestSSOHandler_Scope_Handling 验证 Scope 处理
|
||||
func TestSSOHandler_Scope_Handling(t *testing.T) {
|
||||
server, cleanup := setupHandlerTestServer(t)
|
||||
defer cleanup()
|
||||
|
||||
registerUser(server.URL, "scopeuser", "scope@test.com", "Pass123!")
|
||||
token := getToken(server.URL, "scopeuser", "Pass123!")
|
||||
|
||||
// Request with scope
|
||||
resp, _ := doGet(server.URL+"/api/v1/sso/authorize?client_id=test&redirect_uri=http://localhost&response_type=code&scope=profile+email", token)
|
||||
defer resp.Body.Close()
|
||||
|
||||
// Should handle scope parameter
|
||||
assert.True(t, resp.StatusCode == http.StatusFound || resp.StatusCode == http.StatusBadRequest ||
|
||||
resp.StatusCode == http.StatusInternalServerError || resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusUnauthorized,
|
||||
"should handle scope parameter, got %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
// TestSSOHandler_State_Preservation 验证 State 参数保持
|
||||
func TestSSOHandler_State_Preservation(t *testing.T) {
|
||||
server, cleanup := setupHandlerTestServer(t)
|
||||
defer cleanup()
|
||||
|
||||
registerUser(server.URL, "stateuser", "state@test.com", "Pass123!")
|
||||
token := getToken(server.URL, "stateuser", "Pass123!")
|
||||
|
||||
// Request with state parameter
|
||||
resp, _ := doGet(server.URL+"/api/v1/sso/authorize?client_id=test&redirect_uri=http://localhost&response_type=code&state=my-state-value", token)
|
||||
defer resp.Body.Close()
|
||||
|
||||
// If redirected, state should be preserved in callback
|
||||
if resp.StatusCode == http.StatusFound {
|
||||
location := resp.Header.Get("Location")
|
||||
// State should be included in redirect URL
|
||||
t.Logf("Redirect location: %s", location)
|
||||
code := issueSSOAuthCode(t, server.URL, platformToken)
|
||||
resp, body := doSSOFormPost(t, server.URL+"/api/v1/sso/token", url.Values{
|
||||
"grant_type": {"authorization_code"},
|
||||
"code": {code},
|
||||
"client_id": {"test-client"},
|
||||
"client_secret": {"test-secret"},
|
||||
"redirect_uri": {"http://localhost/other"},
|
||||
}, "")
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("redirect mismatch expected 400, got %d body=%s", resp.StatusCode, string(body))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSOHandler_IntrospectAndRevokeUseClientCredentialsNotPlatformBearer(t *testing.T) {
|
||||
server, cleanup := setupHandlerTestServer(t)
|
||||
defer cleanup()
|
||||
|
||||
registerUser(server.URL, "introspectuser", "introspect@test.com", "Pass123!")
|
||||
platformToken := getToken(server.URL, "introspectuser", "Pass123!")
|
||||
if platformToken == "" {
|
||||
t.Fatal("expected login token for authorization")
|
||||
}
|
||||
|
||||
code := issueSSOAuthCode(t, server.URL, platformToken)
|
||||
tokenPayload := exchangeSSOToken(t, server.URL, code, "http://localhost/callback")
|
||||
|
||||
resp1, body1 := doSSOFormPost(t, server.URL+"/api/v1/sso/introspect", url.Values{
|
||||
"token": {tokenPayload.AccessToken},
|
||||
"client_id": {"test-client"},
|
||||
"client_secret": {"test-secret"},
|
||||
}, "")
|
||||
if resp1.StatusCode != http.StatusOK {
|
||||
t.Fatalf("introspect expected 200, got %d body=%s", resp1.StatusCode, string(body1))
|
||||
}
|
||||
wrapped1 := decodeSSOWrappedResponse(t, body1)
|
||||
var introspect ssoIntrospectPayload
|
||||
if err := json.Unmarshal(wrapped1.Data, &introspect); err != nil {
|
||||
t.Fatalf("decode introspect payload failed: %v body=%s", err, string(body1))
|
||||
}
|
||||
if !introspect.Active {
|
||||
t.Fatalf("expected active token in introspect response: %s", string(body1))
|
||||
}
|
||||
if introspect.Username != "introspectuser" {
|
||||
t.Fatalf("unexpected introspect username: %q", introspect.Username)
|
||||
}
|
||||
|
||||
resp2, body2 := doSSOFormPost(t, server.URL+"/api/v1/sso/revoke", url.Values{
|
||||
"token": {tokenPayload.AccessToken},
|
||||
"client_id": {"test-client"},
|
||||
"client_secret": {"test-secret"},
|
||||
}, "")
|
||||
if resp2.StatusCode != http.StatusOK {
|
||||
t.Fatalf("revoke expected 200, got %d body=%s", resp2.StatusCode, string(body2))
|
||||
}
|
||||
|
||||
resp3, body3 := doSSOFormPost(t, server.URL+"/api/v1/sso/introspect", url.Values{
|
||||
"token": {tokenPayload.AccessToken},
|
||||
"client_id": {"test-client"},
|
||||
"client_secret": {"test-secret"},
|
||||
}, "")
|
||||
if resp3.StatusCode != http.StatusOK {
|
||||
t.Fatalf("post-revoke introspect expected 200, got %d body=%s", resp3.StatusCode, string(body3))
|
||||
}
|
||||
wrapped3 := decodeSSOWrappedResponse(t, body3)
|
||||
var revoked ssoIntrospectPayload
|
||||
if err := json.Unmarshal(wrapped3.Data, &revoked); err != nil {
|
||||
t.Fatalf("decode revoked introspect payload failed: %v body=%s", err, string(body3))
|
||||
}
|
||||
if revoked.Active {
|
||||
t.Fatalf("expected revoked token to be inactive: %s", string(body3))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSOHandler_UserInfoUsesSSOAccessTokenSubject(t *testing.T) {
|
||||
server, cleanup := setupHandlerTestServer(t)
|
||||
defer cleanup()
|
||||
|
||||
registerUser(server.URL, "userinfo-user", "userinfo@test.com", "Pass123!")
|
||||
platformToken := getToken(server.URL, "userinfo-user", "Pass123!")
|
||||
if platformToken == "" {
|
||||
t.Fatal("expected login token for authorization")
|
||||
}
|
||||
|
||||
code := issueSSOAuthCode(t, server.URL, platformToken)
|
||||
tokenPayload := exchangeSSOToken(t, server.URL, code, "http://localhost/callback")
|
||||
|
||||
resp, body := doGet(server.URL+"/api/v1/sso/userinfo", tokenPayload.AccessToken)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("userinfo expected 200, got %d body=%s", resp.StatusCode, body)
|
||||
}
|
||||
wrapped := decodeSSOWrappedResponse(t, []byte(body))
|
||||
var payload ssoUserInfoPayload
|
||||
if err := json.Unmarshal(wrapped.Data, &payload); err != nil {
|
||||
t.Fatalf("decode userinfo payload failed: %v body=%s", err, body)
|
||||
}
|
||||
if payload.Username != "userinfo-user" {
|
||||
t.Fatalf("unexpected userinfo username: %q body=%s", payload.Username, body)
|
||||
}
|
||||
if payload.UserID == 0 {
|
||||
t.Fatalf("userinfo user_id should be non-zero: %s", body)
|
||||
}
|
||||
}
|
||||
|
||||
1
internal/api/handler/swagger_domain_aliases.go
Normal file
1
internal/api/handler/swagger_domain_aliases.go
Normal file
@@ -0,0 +1 @@
|
||||
package handler
|
||||
83
internal/api/handler/swagger_domain_types.go
Normal file
83
internal/api/handler/swagger_domain_types.go
Normal file
@@ -0,0 +1,83 @@
|
||||
package handler
|
||||
|
||||
import "time"
|
||||
|
||||
type SwaggerRole struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Code string `json:"code"`
|
||||
Description string `json:"description"`
|
||||
Status int `json:"status"`
|
||||
IsSystem bool `json:"is_system"`
|
||||
Sort int `json:"sort"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type SwaggerPermission struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Code string `json:"code"`
|
||||
Description string `json:"description"`
|
||||
Type int `json:"type"`
|
||||
ParentID *int64 `json:"parent_id,omitempty"`
|
||||
Path string `json:"path"`
|
||||
Method string `json:"method"`
|
||||
Icon string `json:"icon"`
|
||||
Sort int `json:"sort"`
|
||||
Status int `json:"status"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type SwaggerCustomField struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
FieldKey string `json:"field_key"`
|
||||
FieldType string `json:"field_type"`
|
||||
Required bool `json:"required"`
|
||||
SortOrder int `json:"sort_order"`
|
||||
Options string `json:"options,omitempty"`
|
||||
Placeholder string `json:"placeholder,omitempty"`
|
||||
HelpText string `json:"help_text,omitempty"`
|
||||
Active bool `json:"active"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type SwaggerDevice struct {
|
||||
ID int64 `json:"id"`
|
||||
UserID int64 `json:"user_id"`
|
||||
DeviceID string `json:"device_id"`
|
||||
DeviceName string `json:"device_name"`
|
||||
DeviceType int `json:"device_type"`
|
||||
DeviceOS string `json:"device_os"`
|
||||
DeviceBrowser string `json:"device_browser"`
|
||||
IP string `json:"ip"`
|
||||
Location string `json:"location"`
|
||||
Status int `json:"status"`
|
||||
LastActiveAt *time.Time `json:"last_active_at,omitempty"`
|
||||
IsTrusted bool `json:"is_trusted"`
|
||||
TrustedUntil *time.Time `json:"trusted_until,omitempty"`
|
||||
LastUsedAt *time.Time `json:"last_used_at,omitempty"`
|
||||
Current bool `json:"current"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type SwaggerTheme struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
IsDefault bool `json:"is_default"`
|
||||
PrimaryColor string `json:"primary_color"`
|
||||
SecondaryColor string `json:"secondary_color"`
|
||||
AccentColor string `json:"accent_color"`
|
||||
BackgroundColor string `json:"background_color"`
|
||||
TextColor string `json:"text_color"`
|
||||
SuccessColor string `json:"success_color"`
|
||||
WarningColor string `json:"warning_color"`
|
||||
ErrorColor string `json:"error_color"`
|
||||
InfoColor string `json:"info_color"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
138
internal/api/handler/swagger_request_types.go
Normal file
138
internal/api/handler/swagger_request_types.go
Normal file
@@ -0,0 +1,138 @@
|
||||
package handler
|
||||
|
||||
// TOTPVerifyRequest documents the password-login TOTP verification request.
|
||||
type TOTPVerifyRequest struct {
|
||||
UserID int64 `json:"user_id"`
|
||||
Code string `json:"code"`
|
||||
DeviceID string `json:"device_id,omitempty"`
|
||||
TempToken string `json:"temp_token"`
|
||||
}
|
||||
|
||||
// RefreshTokenRequest documents refresh token input.
|
||||
type RefreshTokenRequest struct {
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
}
|
||||
|
||||
// ResendActivationRequest documents resend activation input.
|
||||
type ResendActivationRequest struct {
|
||||
Email string `json:"email"`
|
||||
}
|
||||
|
||||
// SendEmailCodeRequest documents email code login input.
|
||||
type SendEmailCodeRequest struct {
|
||||
Email string `json:"email"`
|
||||
}
|
||||
|
||||
// LoginByEmailCodeRequest documents email-code login input.
|
||||
type LoginByEmailCodeRequest struct {
|
||||
Email string `json:"email"`
|
||||
Code string `json:"code"`
|
||||
DeviceID string `json:"device_id,omitempty"`
|
||||
DeviceName string `json:"device_name,omitempty"`
|
||||
DeviceBrowser string `json:"device_browser,omitempty"`
|
||||
DeviceOS string `json:"device_os,omitempty"`
|
||||
}
|
||||
|
||||
// BootstrapAdminRequest documents bootstrap admin input.
|
||||
type BootstrapAdminRequest struct {
|
||||
Username string `json:"username"`
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
// VerifyCaptchaRequest documents captcha verification input.
|
||||
type VerifyCaptchaRequest struct {
|
||||
CaptchaID string `json:"captcha_id"`
|
||||
Answer string `json:"answer"`
|
||||
}
|
||||
|
||||
// ForgotPasswordRequest documents email-based password reset initiation.
|
||||
type ForgotPasswordRequest struct {
|
||||
Email string `json:"email"`
|
||||
}
|
||||
|
||||
// ResetPasswordRequest documents token-based password reset input.
|
||||
type ResetPasswordRequest struct {
|
||||
Token string `json:"token"`
|
||||
NewPassword string `json:"new_password"`
|
||||
}
|
||||
|
||||
// EnableTOTPRequest documents enabling TOTP with a code.
|
||||
type EnableTOTPRequest struct {
|
||||
Code string `json:"code"`
|
||||
}
|
||||
|
||||
// DisableTOTPRequest documents disabling TOTP with a code.
|
||||
type DisableTOTPRequest struct {
|
||||
Code string `json:"code"`
|
||||
}
|
||||
|
||||
// VerifyTOTPRequest documents authenticated TOTP verification input.
|
||||
type VerifyTOTPRequest struct {
|
||||
Code string `json:"code"`
|
||||
DeviceID string `json:"device_id,omitempty"`
|
||||
}
|
||||
|
||||
// CreateUserRequest documents user creation input.
|
||||
type CreateUserRequest struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
Email string `json:"email,omitempty"`
|
||||
Phone string `json:"phone,omitempty"`
|
||||
Nickname string `json:"nickname,omitempty"`
|
||||
}
|
||||
|
||||
// UpdateUserRequest documents user profile updates.
|
||||
type UpdateUserRequest struct {
|
||||
Email *string `json:"email,omitempty"`
|
||||
Nickname *string `json:"nickname,omitempty"`
|
||||
}
|
||||
|
||||
// UpdatePasswordRequest documents password change input.
|
||||
type UpdatePasswordRequest struct {
|
||||
OldPassword string `json:"old_password"`
|
||||
NewPassword string `json:"new_password"`
|
||||
}
|
||||
|
||||
// UpdateStatusRequest documents status updates for users.
|
||||
type UpdateStatusRequest struct {
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
// AssignRolesRequest documents role assignment input.
|
||||
type AssignRolesRequest struct {
|
||||
RoleIDs []int64 `json:"role_ids"`
|
||||
}
|
||||
|
||||
// CreateAdminRequest documents admin creation input.
|
||||
type CreateAdminRequest struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
Email string `json:"email,omitempty"`
|
||||
Nickname string `json:"nickname,omitempty"`
|
||||
}
|
||||
|
||||
// SetUserFieldValuesRequest documents user custom-field updates.
|
||||
type SetUserFieldValuesRequest struct {
|
||||
Values map[string]string `json:"values"`
|
||||
}
|
||||
|
||||
// UpdateDeviceStatusRequest documents device status changes.
|
||||
type UpdateDeviceStatusRequest struct {
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
// UpdatePermissionStatusRequest documents permission status changes.
|
||||
type UpdatePermissionStatusRequest struct {
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
// UpdateRoleStatusRequest documents role status changes.
|
||||
type UpdateRoleStatusRequest struct {
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
// AssignPermissionsRequest documents role permission assignment.
|
||||
type AssignPermissionsRequest struct {
|
||||
PermissionIDs []int64 `json:"permission_ids"`
|
||||
}
|
||||
115
internal/api/handler/swagger_types.go
Normal file
115
internal/api/handler/swagger_types.go
Normal file
@@ -0,0 +1,115 @@
|
||||
package handler
|
||||
|
||||
// Response is the canonical API envelope used in Swagger annotations.
|
||||
type Response struct {
|
||||
Code int `json:"code"`
|
||||
Message string `json:"message"`
|
||||
Data interface{} `json:"data,omitempty"`
|
||||
}
|
||||
|
||||
// CaptchaResponse is the captcha generation payload.
|
||||
type CaptchaResponse struct {
|
||||
CaptchaID string `json:"captcha_id"`
|
||||
Image string `json:"image"`
|
||||
}
|
||||
|
||||
// VerifyResponse represents a boolean verification result.
|
||||
type VerifyResponse struct {
|
||||
Verified bool `json:"verified"`
|
||||
}
|
||||
|
||||
// ValidateTokenResponse represents password reset token validation output.
|
||||
type ValidateTokenResponse struct {
|
||||
Valid bool `json:"valid"`
|
||||
}
|
||||
|
||||
// TOTPStatusResponse represents whether TOTP is enabled.
|
||||
type TOTPStatusResponse struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
}
|
||||
|
||||
// TOTPSetupResponse contains setup material for enabling TOTP.
|
||||
type TOTPSetupResponse struct {
|
||||
Secret string `json:"secret"`
|
||||
QRCodeBase64 string `json:"qr_code_base64"`
|
||||
RecoveryCodes []string `json:"recovery_codes"`
|
||||
}
|
||||
|
||||
// VerifyTOTPResponse represents a successful TOTP verification.
|
||||
type VerifyTOTPResponse struct {
|
||||
Verified bool `json:"verified"`
|
||||
}
|
||||
|
||||
// DeviceListResponse represents paginated device results.
|
||||
type DeviceListResponse struct {
|
||||
Items interface{} `json:"items"`
|
||||
Total int64 `json:"total"`
|
||||
Page int `json:"page,omitempty"`
|
||||
PageSize int `json:"page_size,omitempty"`
|
||||
Cursor string `json:"cursor,omitempty"`
|
||||
NextCursor string `json:"next_cursor,omitempty"`
|
||||
HasMore bool `json:"has_more,omitempty"`
|
||||
}
|
||||
|
||||
// LoginLogListResponse represents paginated login log results.
|
||||
type LoginLogListResponse struct {
|
||||
List interface{} `json:"list,omitempty"`
|
||||
Items interface{} `json:"items,omitempty"`
|
||||
Total int64 `json:"total"`
|
||||
Page int `json:"page,omitempty"`
|
||||
PageSize int `json:"page_size,omitempty"`
|
||||
Cursor string `json:"cursor,omitempty"`
|
||||
NextCursor string `json:"next_cursor,omitempty"`
|
||||
HasMore bool `json:"has_more,omitempty"`
|
||||
}
|
||||
|
||||
// OperationLogListResponse represents paginated operation log results.
|
||||
type OperationLogListResponse struct {
|
||||
List interface{} `json:"list,omitempty"`
|
||||
Items interface{} `json:"items,omitempty"`
|
||||
Total int64 `json:"total"`
|
||||
Page int `json:"page,omitempty"`
|
||||
PageSize int `json:"page_size,omitempty"`
|
||||
Cursor string `json:"cursor,omitempty"`
|
||||
NextCursor string `json:"next_cursor,omitempty"`
|
||||
HasMore bool `json:"has_more,omitempty"`
|
||||
}
|
||||
|
||||
// RoleListResponse represents paginated role results.
|
||||
type RoleListResponse struct {
|
||||
Items interface{} `json:"items"`
|
||||
Total int64 `json:"total"`
|
||||
Page int `json:"page,omitempty"`
|
||||
PageSize int `json:"page_size,omitempty"`
|
||||
}
|
||||
|
||||
// UserListResponse represents list or cursor user results.
|
||||
type UserListResponse struct {
|
||||
Users interface{} `json:"users,omitempty"`
|
||||
Items interface{} `json:"items,omitempty"`
|
||||
Total int64 `json:"total,omitempty"`
|
||||
Offset int `json:"offset,omitempty"`
|
||||
Limit int `json:"limit,omitempty"`
|
||||
NextCursor string `json:"next_cursor,omitempty"`
|
||||
HasMore bool `json:"has_more,omitempty"`
|
||||
PageSize int `json:"page_size,omitempty"`
|
||||
}
|
||||
|
||||
// AvatarResponse represents the avatar upload result.
|
||||
type AvatarResponse struct {
|
||||
AvatarURL string `json:"avatar_url"`
|
||||
Thumbnail string `json:"thumbnail"`
|
||||
}
|
||||
|
||||
// CSRFTokenResponse documents the empty CSRF compatibility payload.
|
||||
type CSRFTokenResponse struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
|
||||
// OAuthProvidersResponse documents enabled OAuth providers.
|
||||
type OAuthProvidersResponse struct {
|
||||
Providers []string `json:"providers"`
|
||||
}
|
||||
|
||||
// CustomFieldValuesResponse documents arbitrary custom-field values.
|
||||
type CustomFieldValuesResponse map[string]string
|
||||
@@ -27,7 +27,7 @@ func NewThemeHandler(themeService *service.ThemeService) *ThemeHandler {
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param request body service.CreateThemeRequest true "主题信息"
|
||||
// @Success 201 {object} Response{data=domain.Theme} "主题创建成功"
|
||||
// @Success 201 {object} Response{data=SwaggerTheme} "主题创建成功"
|
||||
// @Failure 400 {object} Response "请求参数错误"
|
||||
// @Failure 401 {object} Response "未认证"
|
||||
// @Failure 500 {object} Response "服务器错误"
|
||||
@@ -61,7 +61,7 @@ func (h *ThemeHandler) CreateTheme(c *gin.Context) {
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "主题ID"
|
||||
// @Param request body service.UpdateThemeRequest true "更新信息"
|
||||
// @Success 200 {object} Response{data=domain.Theme} "主题更新成功"
|
||||
// @Success 200 {object} Response{data=SwaggerTheme} "主题更新成功"
|
||||
// @Failure 400 {object} Response "请求参数错误"
|
||||
// @Failure 401 {object} Response "未认证"
|
||||
// @Failure 500 {object} Response "服务器错误"
|
||||
@@ -129,7 +129,7 @@ func (h *ThemeHandler) DeleteTheme(c *gin.Context) {
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "主题ID"
|
||||
// @Success 200 {object} Response{data=domain.Theme} "主题详情"
|
||||
// @Success 200 {object} Response{data=SwaggerTheme} "主题详情"
|
||||
// @Failure 400 {object} Response "请求参数错误"
|
||||
// @Failure 401 {object} Response "未认证"
|
||||
// @Failure 500 {object} Response "服务器错误"
|
||||
@@ -160,7 +160,7 @@ func (h *ThemeHandler) GetTheme(c *gin.Context) {
|
||||
// @Tags 主题管理
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Success 200 {object} Response{data=[]domain.Theme} "主题列表"
|
||||
// @Success 200 {object} Response{data=[]SwaggerTheme} "主题列表"
|
||||
// @Failure 401 {object} Response "未认证"
|
||||
// @Failure 500 {object} Response "服务器错误"
|
||||
// @Router /api/v1/themes [get]
|
||||
@@ -184,10 +184,10 @@ func (h *ThemeHandler) ListThemes(c *gin.Context) {
|
||||
// @Tags 主题管理
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Success 200 {object} Response{data=[]domain.Theme} "主题列表"
|
||||
// @Success 200 {object} Response{data=[]SwaggerTheme} "主题列表"
|
||||
// @Failure 401 {object} Response "未认证"
|
||||
// @Failure 500 {object} Response "服务器错误"
|
||||
// @Router /api/v1/themes/all [get]
|
||||
// @Router /api/v1/themes [get]
|
||||
func (h *ThemeHandler) ListAllThemes(c *gin.Context) {
|
||||
themes, err := h.themeService.ListAllThemes(c.Request.Context())
|
||||
if err != nil {
|
||||
@@ -208,7 +208,7 @@ func (h *ThemeHandler) ListAllThemes(c *gin.Context) {
|
||||
// @Tags 主题管理
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Success 200 {object} Response{data=domain.Theme} "默认主题"
|
||||
// @Success 200 {object} Response{data=SwaggerTheme} "默认主题"
|
||||
// @Failure 401 {object} Response "未认证"
|
||||
// @Failure 500 {object} Response "服务器错误"
|
||||
// @Router /api/v1/themes/default [get]
|
||||
@@ -237,7 +237,7 @@ func (h *ThemeHandler) GetDefaultTheme(c *gin.Context) {
|
||||
// @Failure 400 {object} Response "请求参数错误"
|
||||
// @Failure 401 {object} Response "未认证"
|
||||
// @Failure 500 {object} Response "服务器错误"
|
||||
// @Router /api/v1/themes/{id}/default [put]
|
||||
// @Router /api/v1/themes/default/{id} [put]
|
||||
func (h *ThemeHandler) SetDefaultTheme(c *gin.Context) {
|
||||
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
@@ -261,9 +261,9 @@ func (h *ThemeHandler) SetDefaultTheme(c *gin.Context) {
|
||||
// @Description 获取当前系统正在使用的主题(公开接口)
|
||||
// @Tags 主题管理
|
||||
// @Produce json
|
||||
// @Success 200 {object} Response{data=domain.Theme} "当前生效主题"
|
||||
// @Success 200 {object} Response{data=SwaggerTheme} "当前生效主题"
|
||||
// @Failure 500 {object} Response "服务器错误"
|
||||
// @Router /api/v1/themes/active [get]
|
||||
// @Router /api/v1/theme/active [get]
|
||||
func (h *ThemeHandler) GetActiveTheme(c *gin.Context) {
|
||||
theme, err := h.themeService.GetActiveTheme(c.Request.Context())
|
||||
if err != nil {
|
||||
|
||||
@@ -24,7 +24,7 @@ func TestThemeHandler_ListThemes_Success(t *testing.T) {
|
||||
resp, body := doGet(server.URL+"/api/v1/themes", token)
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.True(t, resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusForbidden ||
|
||||
assert.True(t, resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusForbidden ||
|
||||
resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusInternalServerError,
|
||||
"should list themes, got %d: %s", resp.StatusCode, body)
|
||||
}
|
||||
@@ -42,7 +42,7 @@ func TestThemeHandler_ListAllThemes_Success(t *testing.T) {
|
||||
resp, body := doGet(server.URL+"/api/v1/themes/all", token)
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.True(t, resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusForbidden ||
|
||||
assert.True(t, resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusForbidden ||
|
||||
resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusInternalServerError || resp.StatusCode == http.StatusBadRequest,
|
||||
"should list all themes, got %d: %s", resp.StatusCode, body)
|
||||
}
|
||||
@@ -60,7 +60,7 @@ func TestThemeHandler_GetTheme_Success(t *testing.T) {
|
||||
resp, body := doGet(server.URL+"/api/v1/themes/1", token)
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.True(t, resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusNotFound ||
|
||||
assert.True(t, resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusNotFound ||
|
||||
resp.StatusCode == http.StatusForbidden || resp.StatusCode == http.StatusInternalServerError,
|
||||
"should get theme, got %d: %s", resp.StatusCode, body)
|
||||
}
|
||||
@@ -94,7 +94,7 @@ func TestThemeHandler_GetTheme_InvalidID(t *testing.T) {
|
||||
resp, _ := doGet(server.URL+"/api/v1/themes/invalid", token)
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.True(t, resp.StatusCode == http.StatusBadRequest || resp.StatusCode == http.StatusOK ||
|
||||
assert.True(t, resp.StatusCode == http.StatusBadRequest || resp.StatusCode == http.StatusOK ||
|
||||
resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusInternalServerError || resp.StatusCode == http.StatusForbidden,
|
||||
"should handle invalid ID, got %d", resp.StatusCode)
|
||||
}
|
||||
@@ -112,7 +112,7 @@ func TestThemeHandler_GetDefaultTheme_Success(t *testing.T) {
|
||||
resp, body := doGet(server.URL+"/api/v1/themes/default", token)
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.True(t, resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusNotFound ||
|
||||
assert.True(t, resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusNotFound ||
|
||||
resp.StatusCode == http.StatusForbidden || resp.StatusCode == http.StatusInternalServerError,
|
||||
"should get default theme, got %d: %s", resp.StatusCode, body)
|
||||
}
|
||||
@@ -126,7 +126,7 @@ func TestThemeHandler_GetActiveTheme_Success(t *testing.T) {
|
||||
resp, body := doGet(server.URL+"/api/v1/themes/active", "")
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.True(t, resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusNotFound ||
|
||||
assert.True(t, resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusNotFound ||
|
||||
resp.StatusCode == http.StatusInternalServerError || resp.StatusCode == http.StatusUnauthorized,
|
||||
"should get active theme, got %d: %s", resp.StatusCode, body)
|
||||
}
|
||||
@@ -142,9 +142,9 @@ func TestThemeHandler_CreateTheme_Success(t *testing.T) {
|
||||
}
|
||||
|
||||
resp, body := doPost(server.URL+"/api/v1/themes", token, map[string]interface{}{
|
||||
"name": "dark-theme",
|
||||
"name": "dark-theme",
|
||||
"display_name": "Dark Theme",
|
||||
"description": "A dark theme for the application",
|
||||
"description": "A dark theme for the application",
|
||||
"colors": map[string]string{
|
||||
"primary": "#1a1a1a",
|
||||
"secondary": "#2d2d2d",
|
||||
@@ -185,7 +185,7 @@ func TestThemeHandler_CreateTheme_NonAdmin(t *testing.T) {
|
||||
assert.NotEmpty(t, token)
|
||||
|
||||
resp, _ := doPost(server.URL+"/api/v1/themes", token, map[string]interface{}{
|
||||
"name": "test-theme",
|
||||
"name": "test-theme",
|
||||
"display_name": "Test Theme",
|
||||
})
|
||||
defer resp.Body.Close()
|
||||
@@ -248,7 +248,7 @@ func TestThemeHandler_UpdateTheme_InvalidID(t *testing.T) {
|
||||
})
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.True(t, resp.StatusCode == http.StatusBadRequest || resp.StatusCode == http.StatusOK ||
|
||||
assert.True(t, resp.StatusCode == http.StatusBadRequest || resp.StatusCode == http.StatusOK ||
|
||||
resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusInternalServerError,
|
||||
"should handle invalid ID, got %d", resp.StatusCode)
|
||||
}
|
||||
@@ -350,7 +350,7 @@ func TestThemeHandler_SetDefaultTheme_InvalidID(t *testing.T) {
|
||||
resp, _ := doPut(server.URL+"/api/v1/themes/invalid/default", token, nil)
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.True(t, resp.StatusCode == http.StatusBadRequest || resp.StatusCode == http.StatusOK ||
|
||||
assert.True(t, resp.StatusCode == http.StatusBadRequest || resp.StatusCode == http.StatusOK ||
|
||||
resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusInternalServerError,
|
||||
"should handle invalid ID, got %d", resp.StatusCode)
|
||||
}
|
||||
@@ -384,7 +384,7 @@ func TestThemeHandler_CRUD_FullFlow(t *testing.T) {
|
||||
// List themes
|
||||
resp1, _ := doGet(server.URL+"/api/v1/themes", token)
|
||||
defer resp1.Body.Close()
|
||||
assert.True(t, resp1.StatusCode == http.StatusOK || resp1.StatusCode == http.StatusForbidden ||
|
||||
assert.True(t, resp1.StatusCode == http.StatusOK || resp1.StatusCode == http.StatusForbidden ||
|
||||
resp1.StatusCode == http.StatusInternalServerError || resp1.StatusCode == http.StatusBadRequest,
|
||||
"should list themes, got %d", resp1.StatusCode)
|
||||
|
||||
|
||||
@@ -30,7 +30,7 @@ func NewTOTPHandler(authService *service.AuthService, totpService *service.TOTPS
|
||||
// @Security BearerAuth
|
||||
// @Success 200 {object} Response{data=TOTPStatusResponse} "TOTP状态"
|
||||
// @Failure 401 {object} Response "未认证"
|
||||
// @Router /api/v1/auth/totp/status [get]
|
||||
// @Router /api/v1/auth/2fa/status [get]
|
||||
func (h *TOTPHandler) GetTOTPStatus(c *gin.Context) {
|
||||
userID, ok := getUserIDFromContext(c)
|
||||
if !ok {
|
||||
@@ -57,7 +57,7 @@ func (h *TOTPHandler) GetTOTPStatus(c *gin.Context) {
|
||||
// @Success 200 {object} Response{data=TOTPSetupResponse} "TOTP设置信息"
|
||||
// @Failure 401 {object} Response "未认证"
|
||||
// @Failure 500 {object} Response "服务器错误"
|
||||
// @Router /api/v1/auth/totp/setup [post]
|
||||
// @Router /api/v1/auth/2fa/setup [get]
|
||||
func (h *TOTPHandler) SetupTOTP(c *gin.Context) {
|
||||
userID, ok := getUserIDFromContext(c)
|
||||
if !ok {
|
||||
@@ -94,7 +94,7 @@ func (h *TOTPHandler) SetupTOTP(c *gin.Context) {
|
||||
// @Failure 400 {object} Response "请求参数错误"
|
||||
// @Failure 401 {object} Response "未认证或验证码错误"
|
||||
// @Failure 500 {object} Response "服务器错误"
|
||||
// @Router /api/v1/auth/totp/enable [post]
|
||||
// @Router /api/v1/auth/2fa/enable [post]
|
||||
func (h *TOTPHandler) EnableTOTP(c *gin.Context) {
|
||||
userID, ok := getUserIDFromContext(c)
|
||||
if !ok {
|
||||
@@ -131,7 +131,7 @@ func (h *TOTPHandler) EnableTOTP(c *gin.Context) {
|
||||
// @Failure 400 {object} Response "请求参数错误"
|
||||
// @Failure 401 {object} Response "未认证或验证码错误"
|
||||
// @Failure 500 {object} Response "服务器错误"
|
||||
// @Router /api/v1/auth/totp/disable [post]
|
||||
// @Router /api/v1/auth/2fa/disable [post]
|
||||
func (h *TOTPHandler) DisableTOTP(c *gin.Context) {
|
||||
userID, ok := getUserIDFromContext(c)
|
||||
if !ok {
|
||||
@@ -168,7 +168,7 @@ func (h *TOTPHandler) DisableTOTP(c *gin.Context) {
|
||||
// @Failure 400 {object} Response "请求参数错误"
|
||||
// @Failure 401 {object} Response "未认证或验证码错误"
|
||||
// @Failure 500 {object} Response "服务器错误"
|
||||
// @Router /api/v1/auth/totp/verify [post]
|
||||
// @Router /api/v1/auth/2fa/verify [post]
|
||||
func (h *TOTPHandler) VerifyTOTP(c *gin.Context) {
|
||||
userID, ok := getUserIDFromContext(c)
|
||||
if !ok {
|
||||
|
||||
@@ -141,7 +141,7 @@ func TestTOTPHandler_EnableTOTP_InvalidCode(t *testing.T) {
|
||||
defer resp.Body.Close()
|
||||
|
||||
// Should reject invalid code (could be 400, 401, or 500 depending on implementation)
|
||||
assert.True(t, resp.StatusCode == http.StatusBadRequest ||
|
||||
assert.True(t, resp.StatusCode == http.StatusBadRequest ||
|
||||
resp.StatusCode == http.StatusUnauthorized ||
|
||||
resp.StatusCode == http.StatusInternalServerError,
|
||||
"should reject invalid code, got %d", resp.StatusCode)
|
||||
@@ -195,7 +195,7 @@ func TestTOTPHandler_EnableTOTP_AlreadyEnabled(t *testing.T) {
|
||||
defer resp2.Body.Close()
|
||||
|
||||
// Could succeed, fail with bad request, or internal error
|
||||
assert.True(t, resp2.StatusCode == http.StatusBadRequest ||
|
||||
assert.True(t, resp2.StatusCode == http.StatusBadRequest ||
|
||||
resp2.StatusCode == http.StatusOK ||
|
||||
resp2.StatusCode == http.StatusInternalServerError,
|
||||
"should return appropriate status, got %d", resp2.StatusCode)
|
||||
@@ -291,7 +291,7 @@ func TestTOTPHandler_VerifyTOTP_NotEnabled(t *testing.T) {
|
||||
defer resp.Body.Close()
|
||||
|
||||
// Should fail since 2FA not enabled (could be 400 or 500)
|
||||
assert.True(t, resp.StatusCode == http.StatusBadRequest ||
|
||||
assert.True(t, resp.StatusCode == http.StatusBadRequest ||
|
||||
resp.StatusCode == http.StatusUnauthorized ||
|
||||
resp.StatusCode == http.StatusInternalServerError,
|
||||
"should error when 2FA not enabled, got %d", resp.StatusCode)
|
||||
@@ -315,7 +315,7 @@ func TestTOTPHandler_VerifyTOTP_InvalidCode(t *testing.T) {
|
||||
defer resp.Body.Close()
|
||||
|
||||
// Should fail since 2FA not enabled or code invalid
|
||||
assert.True(t, resp.StatusCode == http.StatusBadRequest ||
|
||||
assert.True(t, resp.StatusCode == http.StatusBadRequest ||
|
||||
resp.StatusCode == http.StatusUnauthorized ||
|
||||
resp.StatusCode == http.StatusInternalServerError,
|
||||
"should reject, got %d", resp.StatusCode)
|
||||
@@ -354,7 +354,7 @@ func TestTOTPHandler_VerifyTOTP_WithDeviceID(t *testing.T) {
|
||||
defer resp.Body.Close()
|
||||
|
||||
// Should fail for various reasons but accept the request format
|
||||
assert.True(t, resp.StatusCode == http.StatusBadRequest ||
|
||||
assert.True(t, resp.StatusCode == http.StatusBadRequest ||
|
||||
resp.StatusCode == http.StatusUnauthorized ||
|
||||
resp.StatusCode == http.StatusInternalServerError,
|
||||
"should process request but fail validation, got %d", resp.StatusCode)
|
||||
@@ -394,7 +394,7 @@ func TestTOTPHandler_FullFlow_SetupEnableDisable(t *testing.T) {
|
||||
"code": "000000",
|
||||
})
|
||||
defer resp3.Body.Close()
|
||||
assert.True(t, resp3.StatusCode == http.StatusBadRequest ||
|
||||
assert.True(t, resp3.StatusCode == http.StatusBadRequest ||
|
||||
resp3.StatusCode == http.StatusUnauthorized ||
|
||||
resp3.StatusCode == http.StatusInternalServerError,
|
||||
"should fail with invalid code, got %d", resp3.StatusCode)
|
||||
|
||||
@@ -355,7 +355,7 @@ func (h *UserHandler) UpdateUserStatus(c *gin.Context) {
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "用户ID"
|
||||
// @Success 200 {object} Response{data=[]domain.Role} "角色列表"
|
||||
// @Success 200 {object} Response{data=[]SwaggerRole} "角色列表"
|
||||
// @Failure 403 {object} Response "无权限"
|
||||
// @Failure 404 {object} Response "用户不存在"
|
||||
// @Router /api/v1/users/{id}/roles [get]
|
||||
@@ -399,7 +399,7 @@ func (h *UserHandler) GetUserRoles(c *gin.Context) {
|
||||
// @Failure 400 {object} Response "请求参数错误"
|
||||
// @Failure 403 {object} Response "无权限"
|
||||
// @Failure 404 {object} Response "用户不存在"
|
||||
// @Router /api/v1/users/{id}/roles [post]
|
||||
// @Router /api/v1/users/{id}/roles [put]
|
||||
func (h *UserHandler) AssignRoles(c *gin.Context) {
|
||||
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
@@ -488,7 +488,7 @@ func (h *UserHandler) BatchDelete(c *gin.Context) {
|
||||
// @Security BearerAuth
|
||||
// @Success 200 {object} Response{data=[]UserResponse} "管理员列表"
|
||||
// @Failure 403 {object} Response "无权限"
|
||||
// @Router /api/v1/users/admins [get]
|
||||
// @Router /api/v1/admin/admins [get]
|
||||
func (h *UserHandler) ListAdmins(c *gin.Context) {
|
||||
admins, err := h.userService.ListAdmins(c.Request.Context())
|
||||
if err != nil {
|
||||
@@ -515,7 +515,7 @@ func (h *UserHandler) ListAdmins(c *gin.Context) {
|
||||
// @Success 201 {object} Response{data=UserResponse} "管理员创建成功"
|
||||
// @Failure 400 {object} Response "请求参数错误"
|
||||
// @Failure 403 {object} Response "无权限"
|
||||
// @Router /api/v1/users/admins [post]
|
||||
// @Router /api/v1/admin/admins [post]
|
||||
func (h *UserHandler) CreateAdmin(c *gin.Context) {
|
||||
var req struct {
|
||||
Username string `json:"username" binding:"required"`
|
||||
@@ -556,7 +556,7 @@ func (h *UserHandler) CreateAdmin(c *gin.Context) {
|
||||
// @Failure 400 {object} Response "无效的用户ID"
|
||||
// @Failure 403 {object} Response "无权限"
|
||||
// @Failure 409 {object} Response "无法删除(最后管理员或自删)"
|
||||
// @Router /api/v1/users/admins/{id} [delete]
|
||||
// @Router /api/v1/admin/admins/{id} [delete]
|
||||
func (h *UserHandler) DeleteAdmin(c *gin.Context) {
|
||||
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
|
||||
@@ -316,7 +316,7 @@ func TestUserHandler_UpdatePassword_Success(t *testing.T) {
|
||||
"new_password": "NewPass456!",
|
||||
})
|
||||
defer resp.Body.Close()
|
||||
|
||||
|
||||
// Accept both 200 (success) and 403 (if user doesn't have permission to update self)
|
||||
// The handler checks: currentUserID != id && !IsAdmin(c)
|
||||
// For self-update, currentUserID == id, so should be allowed
|
||||
@@ -589,7 +589,7 @@ func TestUserHandler_BatchDelete_Success(t *testing.T) {
|
||||
}
|
||||
|
||||
// Batch delete uses DELETE method with body
|
||||
req, _ := http.NewRequest("DELETE", server.URL+"/api/v1/users/batch",
|
||||
req, _ := http.NewRequest("DELETE", server.URL+"/api/v1/users/batch",
|
||||
bytes.NewReader([]byte(`{"ids": [2, 3, 4]}`)))
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
@@ -599,7 +599,7 @@ func TestUserHandler_BatchDelete_Success(t *testing.T) {
|
||||
t.Fatalf("request failed: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
|
||||
// Accept 200 or method not allowed
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
bodyBytes, _ := io.ReadAll(resp.Body)
|
||||
|
||||
@@ -381,15 +381,19 @@ func (r *Router) Setup() *gin.Engine {
|
||||
}
|
||||
}
|
||||
|
||||
// SSO 单点登录接口(需要认证)
|
||||
// SSO 单点登录接口
|
||||
if r.ssoHandler != nil {
|
||||
sso := protected.Group("/sso")
|
||||
ssoProtected := protected.Group("/sso")
|
||||
{
|
||||
sso.GET("/authorize", r.ssoHandler.Authorize)
|
||||
sso.POST("/token", r.ssoHandler.Token)
|
||||
sso.POST("/introspect", r.ssoHandler.Introspect)
|
||||
sso.POST("/revoke", r.ssoHandler.Revoke)
|
||||
sso.GET("/userinfo", r.ssoHandler.UserInfo)
|
||||
ssoProtected.GET("/authorize", r.ssoHandler.Authorize)
|
||||
}
|
||||
|
||||
ssoPublic := v1.Group("/sso")
|
||||
{
|
||||
ssoPublic.POST("/token", r.ssoHandler.Token)
|
||||
ssoPublic.POST("/introspect", r.ssoHandler.Introspect)
|
||||
ssoPublic.POST("/revoke", r.ssoHandler.Revoke)
|
||||
ssoPublic.GET("/userinfo", r.ssoHandler.UserInfo)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user