Files
soul-yongping/soul-api/internal/handler/admin.go

91 lines
2.8 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package handler
import (
"net/http"
"soul-api/internal/auth"
"soul-api/internal/config"
"github.com/gin-gonic/gin"
)
// AdminCheck GET /api/admin 鉴权检查(与 next-project 一致:校验 admin_session cookie已登录返回 success 或概览占位)
func AdminCheck(c *gin.Context) {
cfg := config.Get()
if cfg == nil {
c.JSON(http.StatusOK, gin.H{"success": true})
return
}
token := auth.GetAdminTokenFromRequest(c.Request)
if !auth.VerifyAdminToken(token, cfg.AdminSessionSecret) {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"success": false, "error": "未授权访问,请先登录"})
return
}
// 与 next 一致:返回 success可选带概览占位供前端扩展
c.JSON(http.StatusOK, gin.H{
"success": true,
"content": gin.H{
"totalChapters": 0, "totalWords": 0, "publishedChapters": 0, "draftChapters": 0,
"lastUpdate": nil,
},
"payment": gin.H{
"totalRevenue": 0, "todayRevenue": 0, "totalOrders": 0, "todayOrders": 0, "averagePrice": 0,
},
"referral": gin.H{
"totalReferrers": 0, "activeReferrers": 0, "totalCommission": 0, "paidCommission": 0, "pendingCommission": 0,
},
"users": gin.H{
"totalUsers": 0, "purchasedUsers": 0, "activeUsers": 0, "todayNewUsers": 0,
},
})
}
// AdminLogin POST /api/admin 登录(与 next-project 一致:校验 ADMIN_USERNAME/PASSWORD写 admin_session cookie
func AdminLogin(c *gin.Context) {
cfg := config.Get()
if cfg == nil {
c.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": "配置未加载"})
return
}
var body struct {
Username string `json:"username" binding:"required"`
Password string `json:"password" binding:"required"`
}
if err := c.ShouldBindJSON(&body); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"success": false, "error": "参数错误"})
return
}
username := trimSpace(body.Username)
password := body.Password
if username != cfg.AdminUsername || password != cfg.AdminPassword {
c.JSON(http.StatusUnauthorized, gin.H{"success": false, "error": "用户名或密码错误"})
return
}
token := auth.CreateAdminToken(cfg.AdminSessionSecret)
c.SetCookie(auth.AdminCookieName(), token, auth.MaxAgeSec(), "/", "", false, true)
c.JSON(http.StatusOK, gin.H{
"success": true,
"user": gin.H{
"id": "admin", "username": cfg.AdminUsername, "role": "admin", "name": "卡若",
},
})
}
// AdminLogout POST /api/admin/logout 清除 admin_session cookie
func AdminLogout(c *gin.Context) {
c.SetCookie(auth.AdminCookieName(), "", -1, "/", "", false, true)
c.JSON(http.StatusOK, gin.H{"success": true})
}
func trimSpace(s string) string {
start := 0
for start < len(s) && (s[start] == ' ' || s[start] == '\t') {
start++
}
end := len(s)
for end > start && (s[end-1] == ' ' || s[end-1] == '\t') {
end--
}
return s[start:end]
}