token.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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/gin-gonic/gin"
  10. )
  11. func GetAllTokens(c *gin.Context) {
  12. userId := c.GetInt("id")
  13. pageInfo := common.GetPageQuery(c)
  14. tokens, err := model.GetAllUserTokens(userId, pageInfo.GetStartIdx(), pageInfo.GetPageSize())
  15. if err != nil {
  16. common.ApiError(c, err)
  17. return
  18. }
  19. total, _ := model.CountUserTokens(userId)
  20. pageInfo.SetTotal(int(total))
  21. pageInfo.SetItems(tokens)
  22. common.ApiSuccess(c, pageInfo)
  23. return
  24. }
  25. func SearchTokens(c *gin.Context) {
  26. userId := c.GetInt("id")
  27. keyword := c.Query("keyword")
  28. token := c.Query("token")
  29. tokens, err := model.SearchUserTokens(userId, keyword, token)
  30. if err != nil {
  31. common.ApiError(c, err)
  32. return
  33. }
  34. c.JSON(http.StatusOK, gin.H{
  35. "success": true,
  36. "message": "",
  37. "data": tokens,
  38. })
  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. key, err := common.GenerateKey()
  148. if err != nil {
  149. common.ApiErrorI18n(c, i18n.MsgTokenGenerateFailed)
  150. common.SysLog("failed to generate token key: " + err.Error())
  151. return
  152. }
  153. cleanToken := model.Token{
  154. UserId: c.GetInt("id"),
  155. Name: token.Name,
  156. Key: key,
  157. CreatedTime: common.GetTimestamp(),
  158. AccessedTime: common.GetTimestamp(),
  159. ExpiredTime: token.ExpiredTime,
  160. RemainQuota: token.RemainQuota,
  161. UnlimitedQuota: token.UnlimitedQuota,
  162. ModelLimitsEnabled: token.ModelLimitsEnabled,
  163. ModelLimits: token.ModelLimits,
  164. AllowIps: token.AllowIps,
  165. Group: token.Group,
  166. CrossGroupRetry: token.CrossGroupRetry,
  167. }
  168. err = cleanToken.Insert()
  169. if err != nil {
  170. common.ApiError(c, err)
  171. return
  172. }
  173. c.JSON(http.StatusOK, gin.H{
  174. "success": true,
  175. "message": "",
  176. })
  177. return
  178. }
  179. func DeleteToken(c *gin.Context) {
  180. id, _ := strconv.Atoi(c.Param("id"))
  181. userId := c.GetInt("id")
  182. err := model.DeleteTokenById(id, userId)
  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 UpdateToken(c *gin.Context) {
  194. userId := c.GetInt("id")
  195. statusOnly := c.Query("status_only")
  196. token := model.Token{}
  197. err := c.ShouldBindJSON(&token)
  198. if err != nil {
  199. common.ApiError(c, err)
  200. return
  201. }
  202. if len(token.Name) > 50 {
  203. common.ApiErrorI18n(c, i18n.MsgTokenNameTooLong)
  204. return
  205. }
  206. if !token.UnlimitedQuota {
  207. if token.RemainQuota < 0 {
  208. common.ApiErrorI18n(c, i18n.MsgTokenQuotaNegative)
  209. return
  210. }
  211. maxQuotaValue := int((1000000000 * common.QuotaPerUnit))
  212. if token.RemainQuota > maxQuotaValue {
  213. common.ApiErrorI18n(c, i18n.MsgTokenQuotaExceedMax, map[string]any{"Max": maxQuotaValue})
  214. return
  215. }
  216. }
  217. cleanToken, err := model.GetTokenByIds(token.Id, userId)
  218. if err != nil {
  219. common.ApiError(c, err)
  220. return
  221. }
  222. if token.Status == common.TokenStatusEnabled {
  223. if cleanToken.Status == common.TokenStatusExpired && cleanToken.ExpiredTime <= common.GetTimestamp() && cleanToken.ExpiredTime != -1 {
  224. common.ApiErrorI18n(c, i18n.MsgTokenExpiredCannotEnable)
  225. return
  226. }
  227. if cleanToken.Status == common.TokenStatusExhausted && cleanToken.RemainQuota <= 0 && !cleanToken.UnlimitedQuota {
  228. common.ApiErrorI18n(c, i18n.MsgTokenExhaustedCannotEable)
  229. return
  230. }
  231. }
  232. if statusOnly != "" {
  233. cleanToken.Status = token.Status
  234. } else {
  235. // If you add more fields, please also update token.Update()
  236. cleanToken.Name = token.Name
  237. cleanToken.ExpiredTime = token.ExpiredTime
  238. cleanToken.RemainQuota = token.RemainQuota
  239. cleanToken.UnlimitedQuota = token.UnlimitedQuota
  240. cleanToken.ModelLimitsEnabled = token.ModelLimitsEnabled
  241. cleanToken.ModelLimits = token.ModelLimits
  242. cleanToken.AllowIps = token.AllowIps
  243. cleanToken.Group = token.Group
  244. cleanToken.CrossGroupRetry = token.CrossGroupRetry
  245. }
  246. err = cleanToken.Update()
  247. if err != nil {
  248. common.ApiError(c, err)
  249. return
  250. }
  251. c.JSON(http.StatusOK, gin.H{
  252. "success": true,
  253. "message": "",
  254. "data": cleanToken,
  255. })
  256. }
  257. type TokenBatch struct {
  258. Ids []int `json:"ids"`
  259. }
  260. func DeleteTokenBatch(c *gin.Context) {
  261. tokenBatch := TokenBatch{}
  262. if err := c.ShouldBindJSON(&tokenBatch); err != nil || len(tokenBatch.Ids) == 0 {
  263. common.ApiErrorI18n(c, i18n.MsgInvalidParams)
  264. return
  265. }
  266. userId := c.GetInt("id")
  267. count, err := model.BatchDeleteTokens(tokenBatch.Ids, userId)
  268. if err != nil {
  269. common.ApiError(c, err)
  270. return
  271. }
  272. c.JSON(http.StatusOK, gin.H{
  273. "success": true,
  274. "message": "",
  275. "data": count,
  276. })
  277. }