token.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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/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. c.JSON(http.StatusOK, gin.H{
  101. "success": false,
  102. "message": err.Error(),
  103. })
  104. return
  105. }
  106. expiredAt := token.ExpiredTime
  107. if expiredAt == -1 {
  108. expiredAt = 0
  109. }
  110. c.JSON(http.StatusOK, gin.H{
  111. "code": true,
  112. "message": "ok",
  113. "data": gin.H{
  114. "object": "token_usage",
  115. "name": token.Name,
  116. "total_granted": token.RemainQuota + token.UsedQuota,
  117. "total_used": token.UsedQuota,
  118. "total_available": token.RemainQuota,
  119. "unlimited_quota": token.UnlimitedQuota,
  120. "model_limits": token.GetModelLimitsMap(),
  121. "model_limits_enabled": token.ModelLimitsEnabled,
  122. "expires_at": expiredAt,
  123. },
  124. })
  125. }
  126. func AddToken(c *gin.Context) {
  127. token := model.Token{}
  128. err := c.ShouldBindJSON(&token)
  129. if err != nil {
  130. common.ApiError(c, err)
  131. return
  132. }
  133. if len(token.Name) > 50 {
  134. c.JSON(http.StatusOK, gin.H{
  135. "success": false,
  136. "message": "令牌名称过长",
  137. })
  138. return
  139. }
  140. // 非无限额度时,检查额度值是否超出有效范围
  141. if !token.UnlimitedQuota {
  142. if token.RemainQuota < 0 {
  143. c.JSON(http.StatusOK, gin.H{
  144. "success": false,
  145. "message": "额度值不能为负数",
  146. })
  147. return
  148. }
  149. maxQuotaValue := int((1000000000 * common.QuotaPerUnit))
  150. if token.RemainQuota > maxQuotaValue {
  151. c.JSON(http.StatusOK, gin.H{
  152. "success": false,
  153. "message": fmt.Sprintf("额度值超出有效范围,最大值为 %d", maxQuotaValue),
  154. })
  155. return
  156. }
  157. }
  158. // 检查用户令牌数量是否已达上限
  159. maxTokens := operation_setting.GetMaxUserTokens()
  160. count, err := model.CountUserTokens(c.GetInt("id"))
  161. if err != nil {
  162. common.ApiError(c, err)
  163. return
  164. }
  165. if int(count) >= maxTokens {
  166. c.JSON(http.StatusOK, gin.H{
  167. "success": false,
  168. "message": fmt.Sprintf("已达到最大令牌数量限制 (%d)", maxTokens),
  169. })
  170. return
  171. }
  172. key, err := common.GenerateKey()
  173. if err != nil {
  174. c.JSON(http.StatusOK, gin.H{
  175. "success": false,
  176. "message": "生成令牌失败",
  177. })
  178. common.SysLog("failed to generate token key: " + err.Error())
  179. return
  180. }
  181. cleanToken := model.Token{
  182. UserId: c.GetInt("id"),
  183. Name: token.Name,
  184. Key: key,
  185. CreatedTime: common.GetTimestamp(),
  186. AccessedTime: common.GetTimestamp(),
  187. ExpiredTime: token.ExpiredTime,
  188. RemainQuota: token.RemainQuota,
  189. UnlimitedQuota: token.UnlimitedQuota,
  190. ModelLimitsEnabled: token.ModelLimitsEnabled,
  191. ModelLimits: token.ModelLimits,
  192. AllowIps: token.AllowIps,
  193. Group: token.Group,
  194. CrossGroupRetry: token.CrossGroupRetry,
  195. }
  196. err = cleanToken.Insert()
  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 DeleteToken(c *gin.Context) {
  208. id, _ := strconv.Atoi(c.Param("id"))
  209. userId := c.GetInt("id")
  210. err := model.DeleteTokenById(id, userId)
  211. if err != nil {
  212. common.ApiError(c, err)
  213. return
  214. }
  215. c.JSON(http.StatusOK, gin.H{
  216. "success": true,
  217. "message": "",
  218. })
  219. return
  220. }
  221. func UpdateToken(c *gin.Context) {
  222. userId := c.GetInt("id")
  223. statusOnly := c.Query("status_only")
  224. token := model.Token{}
  225. err := c.ShouldBindJSON(&token)
  226. if err != nil {
  227. common.ApiError(c, err)
  228. return
  229. }
  230. if len(token.Name) > 50 {
  231. c.JSON(http.StatusOK, gin.H{
  232. "success": false,
  233. "message": "令牌名称过长",
  234. })
  235. return
  236. }
  237. if !token.UnlimitedQuota {
  238. if token.RemainQuota < 0 {
  239. c.JSON(http.StatusOK, gin.H{
  240. "success": false,
  241. "message": "额度值不能为负数",
  242. })
  243. return
  244. }
  245. maxQuotaValue := int((1000000000 * common.QuotaPerUnit))
  246. if token.RemainQuota > maxQuotaValue {
  247. c.JSON(http.StatusOK, gin.H{
  248. "success": false,
  249. "message": fmt.Sprintf("额度值超出有效范围,最大值为 %d", maxQuotaValue),
  250. })
  251. return
  252. }
  253. }
  254. cleanToken, err := model.GetTokenByIds(token.Id, userId)
  255. if err != nil {
  256. common.ApiError(c, err)
  257. return
  258. }
  259. if token.Status == common.TokenStatusEnabled {
  260. if cleanToken.Status == common.TokenStatusExpired && cleanToken.ExpiredTime <= common.GetTimestamp() && cleanToken.ExpiredTime != -1 {
  261. c.JSON(http.StatusOK, gin.H{
  262. "success": false,
  263. "message": "令牌已过期,无法启用,请先修改令牌过期时间,或者设置为永不过期",
  264. })
  265. return
  266. }
  267. if cleanToken.Status == common.TokenStatusExhausted && cleanToken.RemainQuota <= 0 && !cleanToken.UnlimitedQuota {
  268. c.JSON(http.StatusOK, gin.H{
  269. "success": false,
  270. "message": "令牌可用额度已用尽,无法启用,请先修改令牌剩余额度,或者设置为无限额度",
  271. })
  272. return
  273. }
  274. }
  275. if statusOnly != "" {
  276. cleanToken.Status = token.Status
  277. } else {
  278. // If you add more fields, please also update token.Update()
  279. cleanToken.Name = token.Name
  280. cleanToken.ExpiredTime = token.ExpiredTime
  281. cleanToken.RemainQuota = token.RemainQuota
  282. cleanToken.UnlimitedQuota = token.UnlimitedQuota
  283. cleanToken.ModelLimitsEnabled = token.ModelLimitsEnabled
  284. cleanToken.ModelLimits = token.ModelLimits
  285. cleanToken.AllowIps = token.AllowIps
  286. cleanToken.Group = token.Group
  287. cleanToken.CrossGroupRetry = token.CrossGroupRetry
  288. }
  289. err = cleanToken.Update()
  290. if err != nil {
  291. common.ApiError(c, err)
  292. return
  293. }
  294. c.JSON(http.StatusOK, gin.H{
  295. "success": true,
  296. "message": "",
  297. "data": cleanToken,
  298. })
  299. }
  300. type TokenBatch struct {
  301. Ids []int `json:"ids"`
  302. }
  303. func DeleteTokenBatch(c *gin.Context) {
  304. tokenBatch := TokenBatch{}
  305. if err := c.ShouldBindJSON(&tokenBatch); err != nil || len(tokenBatch.Ids) == 0 {
  306. c.JSON(http.StatusOK, gin.H{
  307. "success": false,
  308. "message": "参数错误",
  309. })
  310. return
  311. }
  312. userId := c.GetInt("id")
  313. count, err := model.BatchDeleteTokens(tokenBatch.Ids, userId)
  314. if err != nil {
  315. common.ApiError(c, err)
  316. return
  317. }
  318. c.JSON(http.StatusOK, gin.H{
  319. "success": true,
  320. "message": "",
  321. "data": count,
  322. })
  323. }