token.go 13 KB

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