token.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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/model"
  8. "github.com/gin-gonic/gin"
  9. )
  10. func GetAllTokens(c *gin.Context) {
  11. userId := c.GetInt("id")
  12. pageInfo := common.GetPageQuery(c)
  13. tokens, err := model.GetAllUserTokens(userId, pageInfo.GetStartIdx(), pageInfo.GetPageSize())
  14. if err != nil {
  15. common.ApiError(c, err)
  16. return
  17. }
  18. total, _ := model.CountUserTokens(userId)
  19. pageInfo.SetTotal(int(total))
  20. pageInfo.SetItems(tokens)
  21. common.ApiSuccess(c, pageInfo)
  22. return
  23. }
  24. func SearchTokens(c *gin.Context) {
  25. userId := c.GetInt("id")
  26. keyword := c.Query("keyword")
  27. token := c.Query("token")
  28. tokens, err := model.SearchUserTokens(userId, keyword, token)
  29. if err != nil {
  30. common.ApiError(c, err)
  31. return
  32. }
  33. c.JSON(http.StatusOK, gin.H{
  34. "success": true,
  35. "message": "",
  36. "data": tokens,
  37. })
  38. return
  39. }
  40. func GetToken(c *gin.Context) {
  41. id, err := strconv.Atoi(c.Param("id"))
  42. userId := c.GetInt("id")
  43. if err != nil {
  44. common.ApiError(c, err)
  45. return
  46. }
  47. token, err := model.GetTokenByIds(id, userId)
  48. if err != nil {
  49. common.ApiError(c, err)
  50. return
  51. }
  52. c.JSON(http.StatusOK, gin.H{
  53. "success": true,
  54. "message": "",
  55. "data": token,
  56. })
  57. return
  58. }
  59. func GetTokenStatus(c *gin.Context) {
  60. tokenId := c.GetInt("token_id")
  61. userId := c.GetInt("id")
  62. token, err := model.GetTokenByIds(tokenId, userId)
  63. if err != nil {
  64. common.ApiError(c, err)
  65. return
  66. }
  67. expiredAt := token.ExpiredTime
  68. if expiredAt == -1 {
  69. expiredAt = 0
  70. }
  71. c.JSON(http.StatusOK, gin.H{
  72. "object": "credit_summary",
  73. "total_granted": token.RemainQuota,
  74. "total_used": 0, // not supported currently
  75. "total_available": token.RemainQuota,
  76. "expires_at": expiredAt * 1000,
  77. })
  78. }
  79. func GetTokenUsage(c *gin.Context) {
  80. authHeader := c.GetHeader("Authorization")
  81. if authHeader == "" {
  82. c.JSON(http.StatusUnauthorized, gin.H{
  83. "success": false,
  84. "message": "No Authorization header",
  85. })
  86. return
  87. }
  88. parts := strings.Split(authHeader, " ")
  89. if len(parts) != 2 || strings.ToLower(parts[0]) != "bearer" {
  90. c.JSON(http.StatusUnauthorized, gin.H{
  91. "success": false,
  92. "message": "Invalid Bearer token",
  93. })
  94. return
  95. }
  96. tokenKey := parts[1]
  97. token, err := model.GetTokenByKey(strings.TrimPrefix(tokenKey, "sk-"), false)
  98. if err != nil {
  99. c.JSON(http.StatusOK, gin.H{
  100. "success": false,
  101. "message": err.Error(),
  102. })
  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. c.JSON(http.StatusOK, gin.H{
  134. "success": false,
  135. "message": "令牌名称过长",
  136. })
  137. return
  138. }
  139. key, err := common.GenerateKey()
  140. if err != nil {
  141. c.JSON(http.StatusOK, gin.H{
  142. "success": false,
  143. "message": "生成令牌失败",
  144. })
  145. common.SysLog("failed to generate token key: " + err.Error())
  146. return
  147. }
  148. cleanToken := model.Token{
  149. UserId: c.GetInt("id"),
  150. Name: token.Name,
  151. Key: key,
  152. CreatedTime: common.GetTimestamp(),
  153. AccessedTime: common.GetTimestamp(),
  154. ExpiredTime: token.ExpiredTime,
  155. RemainQuota: token.RemainQuota,
  156. UnlimitedQuota: token.UnlimitedQuota,
  157. ModelLimitsEnabled: token.ModelLimitsEnabled,
  158. ModelLimits: token.ModelLimits,
  159. AllowIps: token.AllowIps,
  160. Group: token.Group,
  161. CrossGroupRetry: token.CrossGroupRetry,
  162. }
  163. err = cleanToken.Insert()
  164. if err != nil {
  165. common.ApiError(c, err)
  166. return
  167. }
  168. c.JSON(http.StatusOK, gin.H{
  169. "success": true,
  170. "message": "",
  171. })
  172. return
  173. }
  174. func DeleteToken(c *gin.Context) {
  175. id, _ := strconv.Atoi(c.Param("id"))
  176. userId := c.GetInt("id")
  177. err := model.DeleteTokenById(id, userId)
  178. if err != nil {
  179. common.ApiError(c, err)
  180. return
  181. }
  182. c.JSON(http.StatusOK, gin.H{
  183. "success": true,
  184. "message": "",
  185. })
  186. return
  187. }
  188. func UpdateToken(c *gin.Context) {
  189. userId := c.GetInt("id")
  190. statusOnly := c.Query("status_only")
  191. token := model.Token{}
  192. err := c.ShouldBindJSON(&token)
  193. if err != nil {
  194. common.ApiError(c, err)
  195. return
  196. }
  197. if len(token.Name) > 50 {
  198. c.JSON(http.StatusOK, gin.H{
  199. "success": false,
  200. "message": "令牌名称过长",
  201. })
  202. return
  203. }
  204. cleanToken, err := model.GetTokenByIds(token.Id, userId)
  205. if err != nil {
  206. common.ApiError(c, err)
  207. return
  208. }
  209. if token.Status == common.TokenStatusEnabled {
  210. if cleanToken.Status == common.TokenStatusExpired && cleanToken.ExpiredTime <= common.GetTimestamp() && cleanToken.ExpiredTime != -1 {
  211. c.JSON(http.StatusOK, gin.H{
  212. "success": false,
  213. "message": "令牌已过期,无法启用,请先修改令牌过期时间,或者设置为永不过期",
  214. })
  215. return
  216. }
  217. if cleanToken.Status == common.TokenStatusExhausted && cleanToken.RemainQuota <= 0 && !cleanToken.UnlimitedQuota {
  218. c.JSON(http.StatusOK, gin.H{
  219. "success": false,
  220. "message": "令牌可用额度已用尽,无法启用,请先修改令牌剩余额度,或者设置为无限额度",
  221. })
  222. return
  223. }
  224. }
  225. if statusOnly != "" {
  226. cleanToken.Status = token.Status
  227. } else {
  228. // If you add more fields, please also update token.Update()
  229. cleanToken.Name = token.Name
  230. cleanToken.ExpiredTime = token.ExpiredTime
  231. cleanToken.RemainQuota = token.RemainQuota
  232. cleanToken.UnlimitedQuota = token.UnlimitedQuota
  233. cleanToken.ModelLimitsEnabled = token.ModelLimitsEnabled
  234. cleanToken.ModelLimits = token.ModelLimits
  235. cleanToken.AllowIps = token.AllowIps
  236. cleanToken.Group = token.Group
  237. cleanToken.CrossGroupRetry = token.CrossGroupRetry
  238. }
  239. err = cleanToken.Update()
  240. if err != nil {
  241. common.ApiError(c, err)
  242. return
  243. }
  244. c.JSON(http.StatusOK, gin.H{
  245. "success": true,
  246. "message": "",
  247. "data": cleanToken,
  248. })
  249. return
  250. }
  251. type TokenBatch struct {
  252. Ids []int `json:"ids"`
  253. }
  254. func DeleteTokenBatch(c *gin.Context) {
  255. tokenBatch := TokenBatch{}
  256. if err := c.ShouldBindJSON(&tokenBatch); err != nil || len(tokenBatch.Ids) == 0 {
  257. c.JSON(http.StatusOK, gin.H{
  258. "success": false,
  259. "message": "参数错误",
  260. })
  261. return
  262. }
  263. userId := c.GetInt("id")
  264. count, err := model.BatchDeleteTokens(tokenBatch.Ids, userId)
  265. if err != nil {
  266. common.ApiError(c, err)
  267. return
  268. }
  269. c.JSON(http.StatusOK, gin.H{
  270. "success": true,
  271. "message": "",
  272. "data": count,
  273. })
  274. }