token.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. package controller
  2. import (
  3. "net/http"
  4. "one-api/common"
  5. "one-api/model"
  6. "strconv"
  7. "strings"
  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(tokenKey, true)
  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. "id": token.Id,
  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. "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) > 30 {
  132. c.JSON(http.StatusOK, gin.H{
  133. "success": false,
  134. "message": "令牌名称过长",
  135. })
  136. return
  137. }
  138. key, err := common.GenerateKey()
  139. if err != nil {
  140. c.JSON(http.StatusOK, gin.H{
  141. "success": false,
  142. "message": "生成令牌失败",
  143. })
  144. common.SysLog("failed to generate token key: " + err.Error())
  145. return
  146. }
  147. cleanToken := model.Token{
  148. UserId: c.GetInt("id"),
  149. Name: token.Name,
  150. Key: key,
  151. CreatedTime: common.GetTimestamp(),
  152. AccessedTime: common.GetTimestamp(),
  153. ExpiredTime: token.ExpiredTime,
  154. RemainQuota: token.RemainQuota,
  155. UnlimitedQuota: token.UnlimitedQuota,
  156. ModelLimitsEnabled: token.ModelLimitsEnabled,
  157. ModelLimits: token.ModelLimits,
  158. AllowIps: token.AllowIps,
  159. Group: token.Group,
  160. }
  161. err = cleanToken.Insert()
  162. if err != nil {
  163. common.ApiError(c, err)
  164. return
  165. }
  166. c.JSON(http.StatusOK, gin.H{
  167. "success": true,
  168. "message": "",
  169. })
  170. return
  171. }
  172. func DeleteToken(c *gin.Context) {
  173. id, _ := strconv.Atoi(c.Param("id"))
  174. userId := c.GetInt("id")
  175. err := model.DeleteTokenById(id, userId)
  176. if err != nil {
  177. common.ApiError(c, err)
  178. return
  179. }
  180. c.JSON(http.StatusOK, gin.H{
  181. "success": true,
  182. "message": "",
  183. })
  184. return
  185. }
  186. func UpdateToken(c *gin.Context) {
  187. userId := c.GetInt("id")
  188. statusOnly := c.Query("status_only")
  189. token := model.Token{}
  190. err := c.ShouldBindJSON(&token)
  191. if err != nil {
  192. common.ApiError(c, err)
  193. return
  194. }
  195. if len(token.Name) > 30 {
  196. c.JSON(http.StatusOK, gin.H{
  197. "success": false,
  198. "message": "令牌名称过长",
  199. })
  200. return
  201. }
  202. cleanToken, err := model.GetTokenByIds(token.Id, userId)
  203. if err != nil {
  204. common.ApiError(c, err)
  205. return
  206. }
  207. if token.Status == common.TokenStatusEnabled {
  208. if cleanToken.Status == common.TokenStatusExpired && cleanToken.ExpiredTime <= common.GetTimestamp() && cleanToken.ExpiredTime != -1 {
  209. c.JSON(http.StatusOK, gin.H{
  210. "success": false,
  211. "message": "令牌已过期,无法启用,请先修改令牌过期时间,或者设置为永不过期",
  212. })
  213. return
  214. }
  215. if cleanToken.Status == common.TokenStatusExhausted && cleanToken.RemainQuota <= 0 && !cleanToken.UnlimitedQuota {
  216. c.JSON(http.StatusOK, gin.H{
  217. "success": false,
  218. "message": "令牌可用额度已用尽,无法启用,请先修改令牌剩余额度,或者设置为无限额度",
  219. })
  220. return
  221. }
  222. }
  223. if statusOnly != "" {
  224. cleanToken.Status = token.Status
  225. } else {
  226. // If you add more fields, please also update token.Update()
  227. cleanToken.Name = token.Name
  228. cleanToken.ExpiredTime = token.ExpiredTime
  229. cleanToken.RemainQuota = token.RemainQuota
  230. cleanToken.UnlimitedQuota = token.UnlimitedQuota
  231. cleanToken.ModelLimitsEnabled = token.ModelLimitsEnabled
  232. cleanToken.ModelLimits = token.ModelLimits
  233. cleanToken.AllowIps = token.AllowIps
  234. cleanToken.Group = token.Group
  235. }
  236. err = cleanToken.Update()
  237. if err != nil {
  238. common.ApiError(c, err)
  239. return
  240. }
  241. c.JSON(http.StatusOK, gin.H{
  242. "success": true,
  243. "message": "",
  244. "data": cleanToken,
  245. })
  246. return
  247. }
  248. type TokenBatch struct {
  249. Ids []int `json:"ids"`
  250. }
  251. func DeleteTokenBatch(c *gin.Context) {
  252. tokenBatch := TokenBatch{}
  253. if err := c.ShouldBindJSON(&tokenBatch); err != nil || len(tokenBatch.Ids) == 0 {
  254. c.JSON(http.StatusOK, gin.H{
  255. "success": false,
  256. "message": "参数错误",
  257. })
  258. return
  259. }
  260. userId := c.GetInt("id")
  261. count, err := model.BatchDeleteTokens(tokenBatch.Ids, userId)
  262. if err != nil {
  263. common.ApiError(c, err)
  264. return
  265. }
  266. c.JSON(http.StatusOK, gin.H{
  267. "success": true,
  268. "message": "",
  269. "data": count,
  270. })
  271. }