token.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. package model
  2. import (
  3. "errors"
  4. "fmt"
  5. "strings"
  6. "github.com/QuantumNous/new-api/common"
  7. "github.com/bytedance/gopkg/util/gopool"
  8. "gorm.io/gorm"
  9. )
  10. type Token struct {
  11. Id int `json:"id"`
  12. UserId int `json:"user_id" gorm:"index"`
  13. Key string `json:"key" gorm:"type:char(48);uniqueIndex"`
  14. Status int `json:"status" gorm:"default:1"`
  15. Name string `json:"name" gorm:"index" `
  16. CreatedTime int64 `json:"created_time" gorm:"bigint"`
  17. AccessedTime int64 `json:"accessed_time" gorm:"bigint"`
  18. ExpiredTime int64 `json:"expired_time" gorm:"bigint;default:-1"` // -1 means never expired
  19. RemainQuota int `json:"remain_quota" gorm:"default:0"`
  20. UnlimitedQuota bool `json:"unlimited_quota"`
  21. ModelLimitsEnabled bool `json:"model_limits_enabled"`
  22. ModelLimits string `json:"model_limits" gorm:"type:varchar(1024);default:''"`
  23. AllowIps *string `json:"allow_ips" gorm:"default:''"`
  24. UsedQuota int `json:"used_quota" gorm:"default:0"` // used quota
  25. Group string `json:"group" gorm:"default:''"`
  26. CrossGroupRetry bool `json:"cross_group_retry" gorm:"default:false"` // 跨分组重试,仅auto分组有效
  27. DeletedAt gorm.DeletedAt `gorm:"index"`
  28. }
  29. func (token *Token) Clean() {
  30. token.Key = ""
  31. }
  32. func (token *Token) GetIpLimits() []string {
  33. // delete empty spaces
  34. //split with \n
  35. ipLimits := make([]string, 0)
  36. if token.AllowIps == nil {
  37. return ipLimits
  38. }
  39. cleanIps := strings.ReplaceAll(*token.AllowIps, " ", "")
  40. if cleanIps == "" {
  41. return ipLimits
  42. }
  43. ips := strings.Split(cleanIps, "\n")
  44. for _, ip := range ips {
  45. ip = strings.TrimSpace(ip)
  46. ip = strings.ReplaceAll(ip, ",", "")
  47. if ip != "" {
  48. ipLimits = append(ipLimits, ip)
  49. }
  50. }
  51. return ipLimits
  52. }
  53. func GetAllUserTokens(userId int, startIdx int, num int) ([]*Token, error) {
  54. var tokens []*Token
  55. var err error
  56. err = DB.Where("user_id = ?", userId).Order("id desc").Limit(num).Offset(startIdx).Find(&tokens).Error
  57. return tokens, err
  58. }
  59. func SearchUserTokens(userId int, keyword string, token string) (tokens []*Token, err error) {
  60. if token != "" {
  61. token = strings.Trim(token, "sk-")
  62. }
  63. err = DB.Where("user_id = ?", userId).Where("name LIKE ?", "%"+keyword+"%").Where(commonKeyCol+" LIKE ?", "%"+token+"%").Find(&tokens).Error
  64. return tokens, err
  65. }
  66. func ValidateUserToken(key string) (token *Token, err error) {
  67. if key == "" {
  68. return nil, errors.New("未提供令牌")
  69. }
  70. token, err = GetTokenByKey(key, false)
  71. if err == nil {
  72. if token.Status == common.TokenStatusExhausted {
  73. keyPrefix := key[:3]
  74. keySuffix := key[len(key)-3:]
  75. return token, errors.New("该令牌额度已用尽 TokenStatusExhausted[sk-" + keyPrefix + "***" + keySuffix + "]")
  76. } else if token.Status == common.TokenStatusExpired {
  77. return token, errors.New("该令牌已过期")
  78. }
  79. if token.Status != common.TokenStatusEnabled {
  80. return token, errors.New("该令牌状态不可用")
  81. }
  82. if token.ExpiredTime != -1 && token.ExpiredTime < common.GetTimestamp() {
  83. if !common.RedisEnabled {
  84. token.Status = common.TokenStatusExpired
  85. err := token.SelectUpdate()
  86. if err != nil {
  87. common.SysLog("failed to update token status" + err.Error())
  88. }
  89. }
  90. return token, errors.New("该令牌已过期")
  91. }
  92. if !token.UnlimitedQuota && token.RemainQuota <= 0 {
  93. if !common.RedisEnabled {
  94. // in this case, we can make sure the token is exhausted
  95. token.Status = common.TokenStatusExhausted
  96. err := token.SelectUpdate()
  97. if err != nil {
  98. common.SysLog("failed to update token status" + err.Error())
  99. }
  100. }
  101. keyPrefix := key[:3]
  102. keySuffix := key[len(key)-3:]
  103. return token, errors.New(fmt.Sprintf("[sk-%s***%s] 该令牌额度已用尽 !token.UnlimitedQuota && token.RemainQuota = %d", keyPrefix, keySuffix, token.RemainQuota))
  104. }
  105. return token, nil
  106. }
  107. common.SysLog("ValidateUserToken: failed to get token: " + err.Error())
  108. if errors.Is(err, gorm.ErrRecordNotFound) {
  109. return nil, errors.New("无效的令牌")
  110. } else {
  111. return nil, errors.New("无效的令牌,数据库查询出错,请联系管理员")
  112. }
  113. }
  114. func GetTokenByIds(id int, userId int) (*Token, error) {
  115. if id == 0 || userId == 0 {
  116. return nil, errors.New("id 或 userId 为空!")
  117. }
  118. token := Token{Id: id, UserId: userId}
  119. var err error = nil
  120. err = DB.First(&token, "id = ? and user_id = ?", id, userId).Error
  121. return &token, err
  122. }
  123. func GetTokenById(id int) (*Token, error) {
  124. if id == 0 {
  125. return nil, errors.New("id 为空!")
  126. }
  127. token := Token{Id: id}
  128. var err error = nil
  129. err = DB.First(&token, "id = ?", id).Error
  130. if shouldUpdateRedis(true, err) {
  131. gopool.Go(func() {
  132. if err := cacheSetToken(token); err != nil {
  133. common.SysLog("failed to update user status cache: " + err.Error())
  134. }
  135. })
  136. }
  137. return &token, err
  138. }
  139. func GetTokenByKey(key string, fromDB bool) (token *Token, err error) {
  140. defer func() {
  141. // Update Redis cache asynchronously on successful DB read
  142. if shouldUpdateRedis(fromDB, err) && token != nil {
  143. gopool.Go(func() {
  144. if err := cacheSetToken(*token); err != nil {
  145. common.SysLog("failed to update user status cache: " + err.Error())
  146. }
  147. })
  148. }
  149. }()
  150. if !fromDB && common.RedisEnabled {
  151. // Try Redis first
  152. token, err := cacheGetTokenByKey(key)
  153. if err == nil {
  154. return token, nil
  155. }
  156. // Don't return error - fall through to DB
  157. }
  158. fromDB = true
  159. err = DB.Where(commonKeyCol+" = ?", key).First(&token).Error
  160. return token, err
  161. }
  162. func (token *Token) Insert() error {
  163. var err error
  164. err = DB.Create(token).Error
  165. return err
  166. }
  167. // Update Make sure your token's fields is completed, because this will update non-zero values
  168. func (token *Token) Update() (err error) {
  169. defer func() {
  170. if shouldUpdateRedis(true, err) {
  171. gopool.Go(func() {
  172. err := cacheSetToken(*token)
  173. if err != nil {
  174. common.SysLog("failed to update token cache: " + err.Error())
  175. }
  176. })
  177. }
  178. }()
  179. err = DB.Model(token).Select("name", "status", "expired_time", "remain_quota", "unlimited_quota",
  180. "model_limits_enabled", "model_limits", "allow_ips", "group", "cross_group_retry").Updates(token).Error
  181. return err
  182. }
  183. func (token *Token) SelectUpdate() (err error) {
  184. defer func() {
  185. if shouldUpdateRedis(true, err) {
  186. gopool.Go(func() {
  187. err := cacheSetToken(*token)
  188. if err != nil {
  189. common.SysLog("failed to update token cache: " + err.Error())
  190. }
  191. })
  192. }
  193. }()
  194. // This can update zero values
  195. return DB.Model(token).Select("accessed_time", "status").Updates(token).Error
  196. }
  197. func (token *Token) Delete() (err error) {
  198. defer func() {
  199. if shouldUpdateRedis(true, err) {
  200. gopool.Go(func() {
  201. err := cacheDeleteToken(token.Key)
  202. if err != nil {
  203. common.SysLog("failed to delete token cache: " + err.Error())
  204. }
  205. })
  206. }
  207. }()
  208. err = DB.Delete(token).Error
  209. return err
  210. }
  211. func (token *Token) IsModelLimitsEnabled() bool {
  212. return token.ModelLimitsEnabled
  213. }
  214. func (token *Token) GetModelLimits() []string {
  215. if token.ModelLimits == "" {
  216. return []string{}
  217. }
  218. return strings.Split(token.ModelLimits, ",")
  219. }
  220. func (token *Token) GetModelLimitsMap() map[string]bool {
  221. limits := token.GetModelLimits()
  222. limitsMap := make(map[string]bool)
  223. for _, limit := range limits {
  224. limitsMap[limit] = true
  225. }
  226. return limitsMap
  227. }
  228. func DisableModelLimits(tokenId int) error {
  229. token, err := GetTokenById(tokenId)
  230. if err != nil {
  231. return err
  232. }
  233. token.ModelLimitsEnabled = false
  234. token.ModelLimits = ""
  235. return token.Update()
  236. }
  237. func DeleteTokenById(id int, userId int) (err error) {
  238. // Why we need userId here? In case user want to delete other's token.
  239. if id == 0 || userId == 0 {
  240. return errors.New("id 或 userId 为空!")
  241. }
  242. token := Token{Id: id, UserId: userId}
  243. err = DB.Where(token).First(&token).Error
  244. if err != nil {
  245. return err
  246. }
  247. return token.Delete()
  248. }
  249. func IncreaseTokenQuota(id int, key string, quota int) (err error) {
  250. if quota < 0 {
  251. return errors.New("quota 不能为负数!")
  252. }
  253. if common.RedisEnabled {
  254. gopool.Go(func() {
  255. err := cacheIncrTokenQuota(key, int64(quota))
  256. if err != nil {
  257. common.SysLog("failed to increase token quota: " + err.Error())
  258. }
  259. })
  260. }
  261. if common.BatchUpdateEnabled {
  262. addNewRecord(BatchUpdateTypeTokenQuota, id, quota)
  263. return nil
  264. }
  265. return increaseTokenQuota(id, quota)
  266. }
  267. func increaseTokenQuota(id int, quota int) (err error) {
  268. err = DB.Model(&Token{}).Where("id = ?", id).Updates(
  269. map[string]interface{}{
  270. "remain_quota": gorm.Expr("remain_quota + ?", quota),
  271. "used_quota": gorm.Expr("used_quota - ?", quota),
  272. "accessed_time": common.GetTimestamp(),
  273. },
  274. ).Error
  275. return err
  276. }
  277. func DecreaseTokenQuota(id int, key string, quota int) (err error) {
  278. if quota < 0 {
  279. return errors.New("quota 不能为负数!")
  280. }
  281. if common.RedisEnabled {
  282. gopool.Go(func() {
  283. err := cacheDecrTokenQuota(key, int64(quota))
  284. if err != nil {
  285. common.SysLog("failed to decrease token quota: " + err.Error())
  286. }
  287. })
  288. }
  289. if common.BatchUpdateEnabled {
  290. addNewRecord(BatchUpdateTypeTokenQuota, id, -quota)
  291. return nil
  292. }
  293. return decreaseTokenQuota(id, quota)
  294. }
  295. func decreaseTokenQuota(id int, quota int) (err error) {
  296. err = DB.Model(&Token{}).Where("id = ?", id).Updates(
  297. map[string]interface{}{
  298. "remain_quota": gorm.Expr("remain_quota - ?", quota),
  299. "used_quota": gorm.Expr("used_quota + ?", quota),
  300. "accessed_time": common.GetTimestamp(),
  301. },
  302. ).Error
  303. return err
  304. }
  305. // CountUserTokens returns total number of tokens for the given user, used for pagination
  306. func CountUserTokens(userId int) (int64, error) {
  307. var total int64
  308. err := DB.Model(&Token{}).Where("user_id = ?", userId).Count(&total).Error
  309. return total, err
  310. }
  311. // BatchDeleteTokens 删除指定用户的一组令牌,返回成功删除数量
  312. func BatchDeleteTokens(ids []int, userId int) (int, error) {
  313. if len(ids) == 0 {
  314. return 0, errors.New("ids 不能为空!")
  315. }
  316. tx := DB.Begin()
  317. var tokens []Token
  318. if err := tx.Where("user_id = ? AND id IN (?)", userId, ids).Find(&tokens).Error; err != nil {
  319. tx.Rollback()
  320. return 0, err
  321. }
  322. if err := tx.Where("user_id = ? AND id IN (?)", userId, ids).Delete(&Token{}).Error; err != nil {
  323. tx.Rollback()
  324. return 0, err
  325. }
  326. if err := tx.Commit().Error; err != nil {
  327. return 0, err
  328. }
  329. if common.RedisEnabled {
  330. gopool.Go(func() {
  331. for _, t := range tokens {
  332. _ = cacheDeleteToken(t.Key)
  333. }
  334. })
  335. }
  336. return len(tokens), nil
  337. }