소스 검색

feat: `/api/token/usage`

lollipopkit🏳️‍⚧️ 8 달 전
부모
커밋
530af5e358
2개의 변경된 파일54개의 추가작업 그리고 2개의 파일을 삭제
  1. 53 1
      controller/token.go
  2. 1 1
      router/api-router.go

+ 53 - 1
controller/token.go

@@ -1,11 +1,13 @@
 package controller
 
 import (
-	"github.com/gin-gonic/gin"
 	"net/http"
 	"one-api/common"
 	"one-api/model"
 	"strconv"
+	"strings"
+
+	"github.com/gin-gonic/gin"
 )
 
 func GetAllTokens(c *gin.Context) {
@@ -106,6 +108,56 @@ func GetTokenStatus(c *gin.Context) {
 	})
 }
 
+func GetTokenUsage(c *gin.Context) {
+	authHeader := c.GetHeader("Authorization")
+	if authHeader == "" {
+		c.JSON(http.StatusUnauthorized, gin.H{
+			"success": false,
+			"message": "No Authorization header",
+		})
+		return
+	}
+
+	parts := strings.Split(authHeader, " ")
+	if len(parts) != 2 || strings.ToLower(parts[0]) != "bearer" {
+		c.JSON(http.StatusUnauthorized, gin.H{
+			"success": false,
+			"message": "Invalid Bearer token",
+		})
+		return
+	}
+	tokenKey := parts[1]
+
+	token, err := model.GetTokenByKey(tokenKey, true)
+	if err != nil {
+		c.JSON(http.StatusOK, gin.H{
+			"success": false,
+			"message": err.Error(),
+		})
+		return
+	}
+
+	expiredAt := token.ExpiredTime
+	if expiredAt == -1 {
+		expiredAt = 0
+	}
+
+	c.JSON(http.StatusOK, gin.H{
+		"code": true,
+		"message": "ok",
+		"data": gin.H{
+			"object":          "token_usage",
+			"id":              token.Id,
+			"name":            token.Name,
+			"total_granted":   token.RemainQuota + token.UsedQuota,
+			"total_used":      token.UsedQuota,
+			"total_available": token.RemainQuota,
+			"unlimited_quota": token.UnlimitedQuota,
+			"expires_at":      expiredAt,
+		},
+	})
+}
+
 func AddToken(c *gin.Context) {
 	token := model.Token{}
 	err := c.ShouldBindJSON(&token)

+ 1 - 1
router/api-router.go

@@ -111,6 +111,7 @@ func SetApiRouter(router *gin.Engine) {
 		{
 			tokenRoute.GET("/", controller.GetAllTokens)
 			tokenRoute.GET("/search", controller.SearchTokens)
+			tokenRoute.GET("/usage", controller.GetTokenUsage)
 			tokenRoute.GET("/:id", controller.GetToken)
 			tokenRoute.POST("/", controller.AddToken)
 			tokenRoute.PUT("/", controller.UpdateToken)
@@ -142,7 +143,6 @@ func SetApiRouter(router *gin.Engine) {
 		logRoute.Use(middleware.CORS())
 		{
 			logRoute.GET("/token", controller.GetLogByKey)
-
 		}
 		groupRoute := apiRouter.Group("/group")
 		groupRoute.Use(middleware.AdminAuth())