token.go 6.7 KB

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