token.go 14 KB

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