token.go 7.7 KB

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