token.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. package model
  2. import (
  3. "errors"
  4. "fmt"
  5. "strings"
  6. "github.com/QuantumNous/new-api/common"
  7. "github.com/QuantumNous/new-api/setting/operation_setting"
  8. "github.com/bytedance/gopkg/util/gopool"
  9. "gorm.io/gorm"
  10. )
  11. type Token struct {
  12. Id int `json:"id"`
  13. UserId int `json:"user_id" gorm:"index"`
  14. Key string `json:"key" gorm:"type:char(48);uniqueIndex"`
  15. Status int `json:"status" gorm:"default:1"`
  16. Name string `json:"name" gorm:"index" `
  17. CreatedTime int64 `json:"created_time" gorm:"bigint"`
  18. AccessedTime int64 `json:"accessed_time" gorm:"bigint"`
  19. ExpiredTime int64 `json:"expired_time" gorm:"bigint;default:-1"` // -1 means never expired
  20. RemainQuota int `json:"remain_quota" gorm:"default:0"`
  21. UnlimitedQuota bool `json:"unlimited_quota"`
  22. ModelLimitsEnabled bool `json:"model_limits_enabled"`
  23. ModelLimits string `json:"model_limits" gorm:"type:varchar(1024);default:''"`
  24. AllowIps *string `json:"allow_ips" gorm:"default:''"`
  25. UsedQuota int `json:"used_quota" gorm:"default:0"` // used quota
  26. Group string `json:"group" gorm:"default:''"`
  27. CrossGroupRetry bool `json:"cross_group_retry"` // 跨分组重试,仅auto分组有效
  28. DeletedAt gorm.DeletedAt `gorm:"index"`
  29. }
  30. func (token *Token) Clean() {
  31. token.Key = ""
  32. }
  33. func (token *Token) GetIpLimits() []string {
  34. // delete empty spaces
  35. //split with \n
  36. ipLimits := make([]string, 0)
  37. if token.AllowIps == nil {
  38. return ipLimits
  39. }
  40. cleanIps := strings.ReplaceAll(*token.AllowIps, " ", "")
  41. if cleanIps == "" {
  42. return ipLimits
  43. }
  44. ips := strings.Split(cleanIps, "\n")
  45. for _, ip := range ips {
  46. ip = strings.TrimSpace(ip)
  47. ip = strings.ReplaceAll(ip, ",", "")
  48. if ip != "" {
  49. ipLimits = append(ipLimits, ip)
  50. }
  51. }
  52. return ipLimits
  53. }
  54. func GetAllUserTokens(userId int, startIdx int, num int) ([]*Token, error) {
  55. var tokens []*Token
  56. var err error
  57. err = DB.Where("user_id = ?", userId).Order("id desc").Limit(num).Offset(startIdx).Find(&tokens).Error
  58. return tokens, err
  59. }
  60. // sanitizeLikePattern 校验并清洗用户输入的 LIKE 搜索模式。
  61. // 规则:
  62. // 1. 转义 _ 和 \(不允许 _ 作通配符)
  63. // 2. 连续的 % 合并为单个 %
  64. // 3. 最多允许 2 个 %
  65. // 4. 含 % 时(模糊搜索),去掉 % 后关键词长度必须 >= 2
  66. // 5. 不含 % 时按精确匹配
  67. func sanitizeLikePattern(input string) (string, error) {
  68. // 1. 转义 \ 和 _
  69. input = strings.ReplaceAll(input, `\`, `\\`)
  70. input = strings.ReplaceAll(input, `_`, `\_`)
  71. // 2. 连续的 % 直接拒绝
  72. if strings.Contains(input, "%%") {
  73. return "", errors.New("搜索模式中不允许包含连续的 % 通配符")
  74. }
  75. // 3. 统计 % 数量,不得超过 2
  76. count := strings.Count(input, "%")
  77. if count > 2 {
  78. return "", errors.New("搜索模式中最多允许包含 2 个 % 通配符")
  79. }
  80. // 4. 含 % 时,去掉 % 后关键词长度必须 >= 2
  81. if count > 0 {
  82. stripped := strings.ReplaceAll(input, "%", "")
  83. if len(stripped) < 2 {
  84. return "", errors.New("使用模糊搜索时,关键词长度至少为 2 个字符")
  85. }
  86. return input, nil
  87. }
  88. // 5. 无 % 时,精确全匹配
  89. return input, nil
  90. }
  91. const searchHardLimit = 100
  92. func SearchUserTokens(userId int, keyword string, token string, offset int, limit int) (tokens []*Token, total int64, err error) {
  93. // model 层强制截断
  94. if limit <= 0 || limit > searchHardLimit {
  95. limit = searchHardLimit
  96. }
  97. if offset < 0 {
  98. offset = 0
  99. }
  100. if token != "" {
  101. token = strings.Trim(token, "sk-")
  102. }
  103. // 超量用户(令牌数超过上限)只允许精确搜索,禁止模糊搜索
  104. maxTokens := operation_setting.GetMaxUserTokens()
  105. hasFuzzy := strings.Contains(keyword, "%") || strings.Contains(token, "%")
  106. if hasFuzzy {
  107. count, err := CountUserTokens(userId)
  108. if err != nil {
  109. common.SysLog("failed to count user tokens: " + err.Error())
  110. return nil, 0, errors.New("获取令牌数量失败")
  111. }
  112. if int(count) > maxTokens {
  113. return nil, 0, errors.New("令牌数量超过上限,仅允许精确搜索,请勿使用 % 通配符")
  114. }
  115. }
  116. baseQuery := DB.Model(&Token{}).Where("user_id = ?", userId)
  117. // 非空才加 LIKE 条件,空则跳过(不过滤该字段)
  118. if keyword != "" {
  119. keywordPattern, err := sanitizeLikePattern(keyword)
  120. if err != nil {
  121. return nil, 0, err
  122. }
  123. baseQuery = baseQuery.Where("name LIKE ? ESCAPE '\\'", keywordPattern)
  124. }
  125. if token != "" {
  126. tokenPattern, err := sanitizeLikePattern(token)
  127. if err != nil {
  128. return nil, 0, err
  129. }
  130. baseQuery = baseQuery.Where(commonKeyCol+" LIKE ? ESCAPE '\\'", tokenPattern)
  131. }
  132. // 先查匹配总数(用于分页,受 maxTokens 上限保护,避免全表 COUNT)
  133. err = baseQuery.Limit(maxTokens).Count(&total).Error
  134. if err != nil {
  135. common.SysError("failed to count search tokens: " + err.Error())
  136. return nil, 0, errors.New("搜索令牌失败")
  137. }
  138. // 再分页查数据
  139. err = baseQuery.Order("id desc").Offset(offset).Limit(limit).Find(&tokens).Error
  140. if err != nil {
  141. common.SysError("failed to search tokens: " + err.Error())
  142. return nil, 0, errors.New("搜索令牌失败")
  143. }
  144. return tokens, total, nil
  145. }
  146. func ValidateUserToken(key string) (token *Token, err error) {
  147. if key == "" {
  148. return nil, errors.New("未提供令牌")
  149. }
  150. token, err = GetTokenByKey(key, false)
  151. if err == nil {
  152. if token.Status == common.TokenStatusExhausted {
  153. keyPrefix := key[:3]
  154. keySuffix := key[len(key)-3:]
  155. return token, errors.New("该令牌额度已用尽 TokenStatusExhausted[sk-" + keyPrefix + "***" + keySuffix + "]")
  156. } else if token.Status == common.TokenStatusExpired {
  157. return token, errors.New("该令牌已过期")
  158. }
  159. if token.Status != common.TokenStatusEnabled {
  160. return token, errors.New("该令牌状态不可用")
  161. }
  162. if token.ExpiredTime != -1 && token.ExpiredTime < common.GetTimestamp() {
  163. if !common.RedisEnabled {
  164. token.Status = common.TokenStatusExpired
  165. err := token.SelectUpdate()
  166. if err != nil {
  167. common.SysLog("failed to update token status" + err.Error())
  168. }
  169. }
  170. return token, errors.New("该令牌已过期")
  171. }
  172. if !token.UnlimitedQuota && token.RemainQuota <= 0 {
  173. if !common.RedisEnabled {
  174. // in this case, we can make sure the token is exhausted
  175. token.Status = common.TokenStatusExhausted
  176. err := token.SelectUpdate()
  177. if err != nil {
  178. common.SysLog("failed to update token status" + err.Error())
  179. }
  180. }
  181. keyPrefix := key[:3]
  182. keySuffix := key[len(key)-3:]
  183. return token, errors.New(fmt.Sprintf("[sk-%s***%s] 该令牌额度已用尽 !token.UnlimitedQuota && token.RemainQuota = %d", keyPrefix, keySuffix, token.RemainQuota))
  184. }
  185. return token, nil
  186. }
  187. common.SysLog("ValidateUserToken: failed to get token: " + err.Error())
  188. if errors.Is(err, gorm.ErrRecordNotFound) {
  189. return nil, errors.New("无效的令牌")
  190. } else {
  191. return nil, errors.New("无效的令牌,数据库查询出错,请联系管理员")
  192. }
  193. }
  194. func GetTokenByIds(id int, userId int) (*Token, error) {
  195. if id == 0 || userId == 0 {
  196. return nil, errors.New("id 或 userId 为空!")
  197. }
  198. token := Token{Id: id, UserId: userId}
  199. var err error = nil
  200. err = DB.First(&token, "id = ? and user_id = ?", id, userId).Error
  201. return &token, err
  202. }
  203. func GetTokenById(id int) (*Token, error) {
  204. if id == 0 {
  205. return nil, errors.New("id 为空!")
  206. }
  207. token := Token{Id: id}
  208. var err error = nil
  209. err = DB.First(&token, "id = ?", id).Error
  210. if shouldUpdateRedis(true, err) {
  211. gopool.Go(func() {
  212. if err := cacheSetToken(token); err != nil {
  213. common.SysLog("failed to update user status cache: " + err.Error())
  214. }
  215. })
  216. }
  217. return &token, err
  218. }
  219. func GetTokenByKey(key string, fromDB bool) (token *Token, err error) {
  220. defer func() {
  221. // Update Redis cache asynchronously on successful DB read
  222. if shouldUpdateRedis(fromDB, err) && token != nil {
  223. gopool.Go(func() {
  224. if err := cacheSetToken(*token); err != nil {
  225. common.SysLog("failed to update user status cache: " + err.Error())
  226. }
  227. })
  228. }
  229. }()
  230. if !fromDB && common.RedisEnabled {
  231. // Try Redis first
  232. token, err := cacheGetTokenByKey(key)
  233. if err == nil {
  234. return token, nil
  235. }
  236. // Don't return error - fall through to DB
  237. }
  238. fromDB = true
  239. err = DB.Where(commonKeyCol+" = ?", key).First(&token).Error
  240. return token, err
  241. }
  242. func (token *Token) Insert() error {
  243. var err error
  244. err = DB.Create(token).Error
  245. return err
  246. }
  247. // Update Make sure your token's fields is completed, because this will update non-zero values
  248. func (token *Token) Update() (err error) {
  249. defer func() {
  250. if shouldUpdateRedis(true, err) {
  251. gopool.Go(func() {
  252. err := cacheSetToken(*token)
  253. if err != nil {
  254. common.SysLog("failed to update token cache: " + err.Error())
  255. }
  256. })
  257. }
  258. }()
  259. err = DB.Model(token).Select("name", "status", "expired_time", "remain_quota", "unlimited_quota",
  260. "model_limits_enabled", "model_limits", "allow_ips", "group", "cross_group_retry").Updates(token).Error
  261. return err
  262. }
  263. func (token *Token) SelectUpdate() (err error) {
  264. defer func() {
  265. if shouldUpdateRedis(true, err) {
  266. gopool.Go(func() {
  267. err := cacheSetToken(*token)
  268. if err != nil {
  269. common.SysLog("failed to update token cache: " + err.Error())
  270. }
  271. })
  272. }
  273. }()
  274. // This can update zero values
  275. return DB.Model(token).Select("accessed_time", "status").Updates(token).Error
  276. }
  277. func (token *Token) Delete() (err error) {
  278. defer func() {
  279. if shouldUpdateRedis(true, err) {
  280. gopool.Go(func() {
  281. err := cacheDeleteToken(token.Key)
  282. if err != nil {
  283. common.SysLog("failed to delete token cache: " + err.Error())
  284. }
  285. })
  286. }
  287. }()
  288. err = DB.Delete(token).Error
  289. return err
  290. }
  291. func (token *Token) IsModelLimitsEnabled() bool {
  292. return token.ModelLimitsEnabled
  293. }
  294. func (token *Token) GetModelLimits() []string {
  295. if token.ModelLimits == "" {
  296. return []string{}
  297. }
  298. return strings.Split(token.ModelLimits, ",")
  299. }
  300. func (token *Token) GetModelLimitsMap() map[string]bool {
  301. limits := token.GetModelLimits()
  302. limitsMap := make(map[string]bool)
  303. for _, limit := range limits {
  304. limitsMap[limit] = true
  305. }
  306. return limitsMap
  307. }
  308. func DisableModelLimits(tokenId int) error {
  309. token, err := GetTokenById(tokenId)
  310. if err != nil {
  311. return err
  312. }
  313. token.ModelLimitsEnabled = false
  314. token.ModelLimits = ""
  315. return token.Update()
  316. }
  317. func DeleteTokenById(id int, userId int) (err error) {
  318. // Why we need userId here? In case user want to delete other's token.
  319. if id == 0 || userId == 0 {
  320. return errors.New("id 或 userId 为空!")
  321. }
  322. token := Token{Id: id, UserId: userId}
  323. err = DB.Where(token).First(&token).Error
  324. if err != nil {
  325. return err
  326. }
  327. return token.Delete()
  328. }
  329. func IncreaseTokenQuota(id int, key string, quota int) (err error) {
  330. if quota < 0 {
  331. return errors.New("quota 不能为负数!")
  332. }
  333. if common.RedisEnabled {
  334. gopool.Go(func() {
  335. err := cacheIncrTokenQuota(key, int64(quota))
  336. if err != nil {
  337. common.SysLog("failed to increase token quota: " + err.Error())
  338. }
  339. })
  340. }
  341. if common.BatchUpdateEnabled {
  342. addNewRecord(BatchUpdateTypeTokenQuota, id, quota)
  343. return nil
  344. }
  345. return increaseTokenQuota(id, quota)
  346. }
  347. func increaseTokenQuota(id int, quota int) (err error) {
  348. err = DB.Model(&Token{}).Where("id = ?", id).Updates(
  349. map[string]interface{}{
  350. "remain_quota": gorm.Expr("remain_quota + ?", quota),
  351. "used_quota": gorm.Expr("used_quota - ?", quota),
  352. "accessed_time": common.GetTimestamp(),
  353. },
  354. ).Error
  355. return err
  356. }
  357. func DecreaseTokenQuota(id int, key string, quota int) (err error) {
  358. if quota < 0 {
  359. return errors.New("quota 不能为负数!")
  360. }
  361. if common.RedisEnabled {
  362. gopool.Go(func() {
  363. err := cacheDecrTokenQuota(key, int64(quota))
  364. if err != nil {
  365. common.SysLog("failed to decrease token quota: " + err.Error())
  366. }
  367. })
  368. }
  369. if common.BatchUpdateEnabled {
  370. addNewRecord(BatchUpdateTypeTokenQuota, id, -quota)
  371. return nil
  372. }
  373. return decreaseTokenQuota(id, quota)
  374. }
  375. func decreaseTokenQuota(id int, quota int) (err error) {
  376. err = DB.Model(&Token{}).Where("id = ?", id).Updates(
  377. map[string]interface{}{
  378. "remain_quota": gorm.Expr("remain_quota - ?", quota),
  379. "used_quota": gorm.Expr("used_quota + ?", quota),
  380. "accessed_time": common.GetTimestamp(),
  381. },
  382. ).Error
  383. return err
  384. }
  385. // CountUserTokens returns total number of tokens for the given user, used for pagination
  386. func CountUserTokens(userId int) (int64, error) {
  387. var total int64
  388. err := DB.Model(&Token{}).Where("user_id = ?", userId).Count(&total).Error
  389. return total, err
  390. }
  391. // BatchDeleteTokens 删除指定用户的一组令牌,返回成功删除数量
  392. func BatchDeleteTokens(ids []int, userId int) (int, error) {
  393. if len(ids) == 0 {
  394. return 0, errors.New("ids 不能为空!")
  395. }
  396. tx := DB.Begin()
  397. var tokens []Token
  398. if err := tx.Where("user_id = ? AND id IN (?)", userId, ids).Find(&tokens).Error; err != nil {
  399. tx.Rollback()
  400. return 0, err
  401. }
  402. if err := tx.Where("user_id = ? AND id IN (?)", userId, ids).Delete(&Token{}).Error; err != nil {
  403. tx.Rollback()
  404. return 0, err
  405. }
  406. if err := tx.Commit().Error; err != nil {
  407. return 0, err
  408. }
  409. if common.RedisEnabled {
  410. gopool.Go(func() {
  411. for _, t := range tokens {
  412. _ = cacheDeleteToken(t.Key)
  413. }
  414. })
  415. }
  416. return len(tokens), nil
  417. }