token.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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/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. 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. key, err := common.GenerateKey()
  159. if err != nil {
  160. c.JSON(http.StatusOK, gin.H{
  161. "success": false,
  162. "message": "生成令牌失败",
  163. })
  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. c.JSON(http.StatusOK, gin.H{
  218. "success": false,
  219. "message": "令牌名称过长",
  220. })
  221. return
  222. }
  223. if !token.UnlimitedQuota {
  224. if token.RemainQuota < 0 {
  225. c.JSON(http.StatusOK, gin.H{
  226. "success": false,
  227. "message": "额度值不能为负数",
  228. })
  229. return
  230. }
  231. maxQuotaValue := int((1000000000 * common.QuotaPerUnit))
  232. if token.RemainQuota > maxQuotaValue {
  233. c.JSON(http.StatusOK, gin.H{
  234. "success": false,
  235. "message": fmt.Sprintf("额度值超出有效范围,最大值为 %d", maxQuotaValue),
  236. })
  237. return
  238. }
  239. }
  240. cleanToken, err := model.GetTokenByIds(token.Id, userId)
  241. if err != nil {
  242. common.ApiError(c, err)
  243. return
  244. }
  245. if token.Status == common.TokenStatusEnabled {
  246. if cleanToken.Status == common.TokenStatusExpired && cleanToken.ExpiredTime <= common.GetTimestamp() && cleanToken.ExpiredTime != -1 {
  247. c.JSON(http.StatusOK, gin.H{
  248. "success": false,
  249. "message": "令牌已过期,无法启用,请先修改令牌过期时间,或者设置为永不过期",
  250. })
  251. return
  252. }
  253. if cleanToken.Status == common.TokenStatusExhausted && cleanToken.RemainQuota <= 0 && !cleanToken.UnlimitedQuota {
  254. c.JSON(http.StatusOK, gin.H{
  255. "success": false,
  256. "message": "令牌可用额度已用尽,无法启用,请先修改令牌剩余额度,或者设置为无限额度",
  257. })
  258. return
  259. }
  260. }
  261. if statusOnly != "" {
  262. cleanToken.Status = token.Status
  263. } else {
  264. // If you add more fields, please also update token.Update()
  265. cleanToken.Name = token.Name
  266. cleanToken.ExpiredTime = token.ExpiredTime
  267. cleanToken.RemainQuota = token.RemainQuota
  268. cleanToken.UnlimitedQuota = token.UnlimitedQuota
  269. cleanToken.ModelLimitsEnabled = token.ModelLimitsEnabled
  270. cleanToken.ModelLimits = token.ModelLimits
  271. cleanToken.AllowIps = token.AllowIps
  272. cleanToken.Group = token.Group
  273. cleanToken.CrossGroupRetry = token.CrossGroupRetry
  274. }
  275. err = cleanToken.Update()
  276. if err != nil {
  277. common.ApiError(c, err)
  278. return
  279. }
  280. c.JSON(http.StatusOK, gin.H{
  281. "success": true,
  282. "message": "",
  283. "data": cleanToken,
  284. })
  285. }
  286. type TokenBatch struct {
  287. Ids []int `json:"ids"`
  288. }
  289. func DeleteTokenBatch(c *gin.Context) {
  290. tokenBatch := TokenBatch{}
  291. if err := c.ShouldBindJSON(&tokenBatch); err != nil || len(tokenBatch.Ids) == 0 {
  292. c.JSON(http.StatusOK, gin.H{
  293. "success": false,
  294. "message": "参数错误",
  295. })
  296. return
  297. }
  298. userId := c.GetInt("id")
  299. count, err := model.BatchDeleteTokens(tokenBatch.Ids, userId)
  300. if err != nil {
  301. common.ApiError(c, err)
  302. return
  303. }
  304. c.JSON(http.StatusOK, gin.H{
  305. "success": true,
  306. "message": "",
  307. "data": count,
  308. })
  309. }