token.go 6.6 KB

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