token.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. package controller
  2. import (
  3. "fmt"
  4. "net/http"
  5. "strconv"
  6. "strings"
  7. "github.com/QuantumNous/new-api/common"
  8. "github.com/QuantumNous/new-api/i18n"
  9. "github.com/QuantumNous/new-api/model"
  10. "github.com/QuantumNous/new-api/setting/operation_setting"
  11. "github.com/gin-gonic/gin"
  12. )
  13. func GetAllTokens(c *gin.Context) {
  14. userId := c.GetInt("id")
  15. pageInfo := common.GetPageQuery(c)
  16. tokens, err := model.GetAllUserTokens(userId, pageInfo.GetStartIdx(), pageInfo.GetPageSize())
  17. if err != nil {
  18. common.ApiError(c, err)
  19. return
  20. }
  21. total, _ := model.CountUserTokens(userId)
  22. pageInfo.SetTotal(int(total))
  23. pageInfo.SetItems(tokens)
  24. common.ApiSuccess(c, pageInfo)
  25. return
  26. }
  27. func SearchTokens(c *gin.Context) {
  28. userId := c.GetInt("id")
  29. keyword := c.Query("keyword")
  30. token := c.Query("token")
  31. pageInfo := common.GetPageQuery(c)
  32. tokens, total, err := model.SearchUserTokens(userId, keyword, token, pageInfo.GetStartIdx(), pageInfo.GetPageSize())
  33. if err != nil {
  34. common.ApiError(c, err)
  35. return
  36. }
  37. pageInfo.SetTotal(int(total))
  38. pageInfo.SetItems(tokens)
  39. common.ApiSuccess(c, pageInfo)
  40. return
  41. }
  42. func GetToken(c *gin.Context) {
  43. id, err := strconv.Atoi(c.Param("id"))
  44. userId := c.GetInt("id")
  45. if err != nil {
  46. common.ApiError(c, err)
  47. return
  48. }
  49. token, err := model.GetTokenByIds(id, userId)
  50. if err != nil {
  51. common.ApiError(c, err)
  52. return
  53. }
  54. c.JSON(http.StatusOK, gin.H{
  55. "success": true,
  56. "message": "",
  57. "data": token,
  58. })
  59. return
  60. }
  61. func GetTokenStatus(c *gin.Context) {
  62. tokenId := c.GetInt("token_id")
  63. userId := c.GetInt("id")
  64. token, err := model.GetTokenByIds(tokenId, userId)
  65. if err != nil {
  66. common.ApiError(c, err)
  67. return
  68. }
  69. expiredAt := token.ExpiredTime
  70. if expiredAt == -1 {
  71. expiredAt = 0
  72. }
  73. c.JSON(http.StatusOK, gin.H{
  74. "object": "credit_summary",
  75. "total_granted": token.RemainQuota,
  76. "total_used": 0, // not supported currently
  77. "total_available": token.RemainQuota,
  78. "expires_at": expiredAt * 1000,
  79. })
  80. }
  81. func GetTokenUsage(c *gin.Context) {
  82. authHeader := c.GetHeader("Authorization")
  83. if authHeader == "" {
  84. c.JSON(http.StatusUnauthorized, gin.H{
  85. "success": false,
  86. "message": "No Authorization header",
  87. })
  88. return
  89. }
  90. parts := strings.Split(authHeader, " ")
  91. if len(parts) != 2 || strings.ToLower(parts[0]) != "bearer" {
  92. c.JSON(http.StatusUnauthorized, gin.H{
  93. "success": false,
  94. "message": "Invalid Bearer token",
  95. })
  96. return
  97. }
  98. tokenKey := parts[1]
  99. token, err := model.GetTokenByKey(strings.TrimPrefix(tokenKey, "sk-"), false)
  100. if err != nil {
  101. common.SysError("failed to get token by key: " + err.Error())
  102. common.ApiErrorI18n(c, i18n.MsgTokenGetInfoFailed)
  103. return
  104. }
  105. expiredAt := token.ExpiredTime
  106. if expiredAt == -1 {
  107. expiredAt = 0
  108. }
  109. c.JSON(http.StatusOK, gin.H{
  110. "code": true,
  111. "message": "ok",
  112. "data": gin.H{
  113. "object": "token_usage",
  114. "name": token.Name,
  115. "total_granted": token.RemainQuota + token.UsedQuota,
  116. "total_used": token.UsedQuota,
  117. "total_available": token.RemainQuota,
  118. "unlimited_quota": token.UnlimitedQuota,
  119. "model_limits": token.GetModelLimitsMap(),
  120. "model_limits_enabled": token.ModelLimitsEnabled,
  121. "expires_at": expiredAt,
  122. },
  123. })
  124. }
  125. func AddToken(c *gin.Context) {
  126. token := model.Token{}
  127. err := c.ShouldBindJSON(&token)
  128. if err != nil {
  129. common.ApiError(c, err)
  130. return
  131. }
  132. if len(token.Name) > 50 {
  133. common.ApiErrorI18n(c, i18n.MsgTokenNameTooLong)
  134. return
  135. }
  136. // 非无限额度时,检查额度值是否超出有效范围
  137. if !token.UnlimitedQuota {
  138. if token.RemainQuota < 0 {
  139. common.ApiErrorI18n(c, i18n.MsgTokenQuotaNegative)
  140. return
  141. }
  142. maxQuotaValue := int((1000000000 * common.QuotaPerUnit))
  143. if token.RemainQuota > maxQuotaValue {
  144. common.ApiErrorI18n(c, i18n.MsgTokenQuotaExceedMax, map[string]any{"Max": maxQuotaValue})
  145. return
  146. }
  147. }
  148. // 检查用户令牌数量是否已达上限
  149. maxTokens := operation_setting.GetMaxUserTokens()
  150. count, err := model.CountUserTokens(c.GetInt("id"))
  151. if err != nil {
  152. common.ApiError(c, err)
  153. return
  154. }
  155. if int(count) >= maxTokens {
  156. c.JSON(http.StatusOK, gin.H{
  157. "success": false,
  158. "message": fmt.Sprintf("已达到最大令牌数量限制 (%d)", maxTokens),
  159. })
  160. return
  161. }
  162. key, err := common.GenerateKey()
  163. if err != nil {
  164. common.ApiErrorI18n(c, i18n.MsgTokenGenerateFailed)
  165. common.SysLog("failed to generate token key: " + err.Error())
  166. return
  167. }
  168. cleanToken := model.Token{
  169. UserId: c.GetInt("id"),
  170. Name: token.Name,
  171. Key: key,
  172. CreatedTime: common.GetTimestamp(),
  173. AccessedTime: common.GetTimestamp(),
  174. ExpiredTime: token.ExpiredTime,
  175. RemainQuota: token.RemainQuota,
  176. UnlimitedQuota: token.UnlimitedQuota,
  177. ModelLimitsEnabled: token.ModelLimitsEnabled,
  178. ModelLimits: token.ModelLimits,
  179. AllowIps: token.AllowIps,
  180. Group: token.Group,
  181. CrossGroupRetry: token.CrossGroupRetry,
  182. }
  183. err = cleanToken.Insert()
  184. if err != nil {
  185. common.ApiError(c, err)
  186. return
  187. }
  188. c.JSON(http.StatusOK, gin.H{
  189. "success": true,
  190. "message": "",
  191. })
  192. return
  193. }
  194. func DeleteToken(c *gin.Context) {
  195. id, _ := strconv.Atoi(c.Param("id"))
  196. userId := c.GetInt("id")
  197. err := model.DeleteTokenById(id, userId)
  198. if err != nil {
  199. common.ApiError(c, err)
  200. return
  201. }
  202. c.JSON(http.StatusOK, gin.H{
  203. "success": true,
  204. "message": "",
  205. })
  206. return
  207. }
  208. func UpdateToken(c *gin.Context) {
  209. userId := c.GetInt("id")
  210. statusOnly := c.Query("status_only")
  211. token := model.Token{}
  212. err := c.ShouldBindJSON(&token)
  213. if err != nil {
  214. common.ApiError(c, err)
  215. return
  216. }
  217. if len(token.Name) > 50 {
  218. common.ApiErrorI18n(c, i18n.MsgTokenNameTooLong)
  219. return
  220. }
  221. if !token.UnlimitedQuota {
  222. if token.RemainQuota < 0 {
  223. common.ApiErrorI18n(c, i18n.MsgTokenQuotaNegative)
  224. return
  225. }
  226. maxQuotaValue := int((1000000000 * common.QuotaPerUnit))
  227. if token.RemainQuota > maxQuotaValue {
  228. common.ApiErrorI18n(c, i18n.MsgTokenQuotaExceedMax, map[string]any{"Max": maxQuotaValue})
  229. return
  230. }
  231. }
  232. cleanToken, err := model.GetTokenByIds(token.Id, userId)
  233. if err != nil {
  234. common.ApiError(c, err)
  235. return
  236. }
  237. if token.Status == common.TokenStatusEnabled {
  238. if cleanToken.Status == common.TokenStatusExpired && cleanToken.ExpiredTime <= common.GetTimestamp() && cleanToken.ExpiredTime != -1 {
  239. common.ApiErrorI18n(c, i18n.MsgTokenExpiredCannotEnable)
  240. return
  241. }
  242. if cleanToken.Status == common.TokenStatusExhausted && cleanToken.RemainQuota <= 0 && !cleanToken.UnlimitedQuota {
  243. common.ApiErrorI18n(c, i18n.MsgTokenExhaustedCannotEable)
  244. return
  245. }
  246. }
  247. if statusOnly != "" {
  248. cleanToken.Status = token.Status
  249. } else {
  250. // If you add more fields, please also update token.Update()
  251. cleanToken.Name = token.Name
  252. cleanToken.ExpiredTime = token.ExpiredTime
  253. cleanToken.RemainQuota = token.RemainQuota
  254. cleanToken.UnlimitedQuota = token.UnlimitedQuota
  255. cleanToken.ModelLimitsEnabled = token.ModelLimitsEnabled
  256. cleanToken.ModelLimits = token.ModelLimits
  257. cleanToken.AllowIps = token.AllowIps
  258. cleanToken.Group = token.Group
  259. cleanToken.CrossGroupRetry = token.CrossGroupRetry
  260. }
  261. err = cleanToken.Update()
  262. if err != nil {
  263. common.ApiError(c, err)
  264. return
  265. }
  266. c.JSON(http.StatusOK, gin.H{
  267. "success": true,
  268. "message": "",
  269. "data": cleanToken,
  270. })
  271. }
  272. type TokenBatch struct {
  273. Ids []int `json:"ids"`
  274. }
  275. func DeleteTokenBatch(c *gin.Context) {
  276. tokenBatch := TokenBatch{}
  277. if err := c.ShouldBindJSON(&tokenBatch); err != nil || len(tokenBatch.Ids) == 0 {
  278. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  279. return
  280. }
  281. userId := c.GetInt("id")
  282. count, err := model.BatchDeleteTokens(tokenBatch.Ids, userId)
  283. if err != nil {
  284. common.ApiError(c, err)
  285. return
  286. }
  287. c.JSON(http.StatusOK, gin.H{
  288. "success": true,
  289. "message": "",
  290. "data": count,
  291. })
  292. }