2
0

token.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. package model
  2. import (
  3. "errors"
  4. "fmt"
  5. "github.com/bytedance/gopkg/util/gopool"
  6. "gorm.io/gorm"
  7. "one-api/common"
  8. relaycommon "one-api/relay/common"
  9. "one-api/setting"
  10. "strconv"
  11. "strings"
  12. )
  13. type Token struct {
  14. Id int `json:"id"`
  15. UserId int `json:"user_id" gorm:"index"`
  16. Key string `json:"key" gorm:"type:char(48);uniqueIndex"`
  17. Status int `json:"status" gorm:"default:1"`
  18. Name string `json:"name" gorm:"index" `
  19. CreatedTime int64 `json:"created_time" gorm:"bigint"`
  20. AccessedTime int64 `json:"accessed_time" gorm:"bigint"`
  21. ExpiredTime int64 `json:"expired_time" gorm:"bigint;default:-1"` // -1 means never expired
  22. RemainQuota int `json:"remain_quota" gorm:"default:0"`
  23. UnlimitedQuota bool `json:"unlimited_quota" gorm:"default:false"`
  24. ModelLimitsEnabled bool `json:"model_limits_enabled" gorm:"default:false"`
  25. ModelLimits string `json:"model_limits" gorm:"type:varchar(1024);default:''"`
  26. AllowIps *string `json:"allow_ips" gorm:"default:''"`
  27. UsedQuota int `json:"used_quota" gorm:"default:0"` // used quota
  28. Group string `json:"group" gorm:"default:''"`
  29. DeletedAt gorm.DeletedAt `gorm:"index"`
  30. }
  31. func (token *Token) Clean() {
  32. token.Key = ""
  33. }
  34. func (token *Token) GetIpLimitsMap() map[string]any {
  35. // delete empty spaces
  36. //split with \n
  37. ipLimitsMap := make(map[string]any)
  38. if token.AllowIps == nil {
  39. return ipLimitsMap
  40. }
  41. cleanIps := strings.ReplaceAll(*token.AllowIps, " ", "")
  42. if cleanIps == "" {
  43. return ipLimitsMap
  44. }
  45. ips := strings.Split(cleanIps, "\n")
  46. for _, ip := range ips {
  47. ip = strings.TrimSpace(ip)
  48. ip = strings.ReplaceAll(ip, ",", "")
  49. if common.IsIP(ip) {
  50. ipLimitsMap[ip] = true
  51. }
  52. }
  53. return ipLimitsMap
  54. }
  55. func GetAllUserTokens(userId int, startIdx int, num int) ([]*Token, error) {
  56. var tokens []*Token
  57. var err error
  58. err = DB.Where("user_id = ?", userId).Order("id desc").Limit(num).Offset(startIdx).Find(&tokens).Error
  59. return tokens, err
  60. }
  61. func SearchUserTokens(userId int, keyword string, token string) (tokens []*Token, err error) {
  62. if token != "" {
  63. token = strings.Trim(token, "sk-")
  64. }
  65. err = DB.Where("user_id = ?", userId).Where("name LIKE ?", "%"+keyword+"%").Where(keyCol+" LIKE ?", "%"+token+"%").Find(&tokens).Error
  66. return tokens, err
  67. }
  68. func ValidateUserToken(key string) (token *Token, err error) {
  69. if key == "" {
  70. return nil, errors.New("未提供令牌")
  71. }
  72. token, err = GetTokenByKey(key, false)
  73. if err == nil {
  74. if token.Status == common.TokenStatusExhausted {
  75. keyPrefix := key[:3]
  76. keySuffix := key[len(key)-3:]
  77. return token, errors.New("该令牌额度已用尽 TokenStatusExhausted[sk-" + keyPrefix + "***" + keySuffix + "]")
  78. } else if token.Status == common.TokenStatusExpired {
  79. return token, errors.New("该令牌已过期")
  80. }
  81. if token.Status != common.TokenStatusEnabled {
  82. return token, errors.New("该令牌状态不可用")
  83. }
  84. if token.ExpiredTime != -1 && token.ExpiredTime < common.GetTimestamp() {
  85. if !common.RedisEnabled {
  86. token.Status = common.TokenStatusExpired
  87. err := token.SelectUpdate()
  88. if err != nil {
  89. common.SysError("failed to update token status" + err.Error())
  90. }
  91. }
  92. return token, errors.New("该令牌已过期")
  93. }
  94. if !token.UnlimitedQuota && token.RemainQuota <= 0 {
  95. if !common.RedisEnabled {
  96. // in this case, we can make sure the token is exhausted
  97. token.Status = common.TokenStatusExhausted
  98. err := token.SelectUpdate()
  99. if err != nil {
  100. common.SysError("failed to update token status" + err.Error())
  101. }
  102. }
  103. keyPrefix := key[:3]
  104. keySuffix := key[len(key)-3:]
  105. return token, errors.New(fmt.Sprintf("[sk-%s***%s] 该令牌额度已用尽 !token.UnlimitedQuota && token.RemainQuota = %d", keyPrefix, keySuffix, token.RemainQuota))
  106. }
  107. return token, nil
  108. }
  109. return nil, errors.New("无效的令牌")
  110. }
  111. func GetTokenByIds(id int, userId int) (*Token, error) {
  112. if id == 0 || userId == 0 {
  113. return nil, errors.New("id 或 userId 为空!")
  114. }
  115. token := Token{Id: id, UserId: userId}
  116. var err error = nil
  117. err = DB.First(&token, "id = ? and user_id = ?", id, userId).Error
  118. return &token, err
  119. }
  120. func GetTokenById(id int) (*Token, error) {
  121. if id == 0 {
  122. return nil, errors.New("id 为空!")
  123. }
  124. token := Token{Id: id}
  125. var err error = nil
  126. err = DB.First(&token, "id = ?", id).Error
  127. if shouldUpdateRedis(true, err) {
  128. gopool.Go(func() {
  129. if err := cacheSetToken(token); err != nil {
  130. common.SysError("failed to update user status cache: " + err.Error())
  131. }
  132. })
  133. }
  134. return &token, err
  135. }
  136. func GetTokenByKey(key string, fromDB bool) (token *Token, err error) {
  137. defer func() {
  138. // Update Redis cache asynchronously on successful DB read
  139. if shouldUpdateRedis(fromDB, err) && token != nil {
  140. gopool.Go(func() {
  141. if err := cacheSetToken(*token); err != nil {
  142. common.SysError("failed to update user status cache: " + err.Error())
  143. }
  144. })
  145. }
  146. }()
  147. if !fromDB && common.RedisEnabled {
  148. // Try Redis first
  149. token, err := cacheGetTokenByKey(key)
  150. if err == nil {
  151. return token, nil
  152. }
  153. // Don't return error - fall through to DB
  154. }
  155. fromDB = true
  156. err = DB.Where(keyCol+" = ?", key).First(&token).Error
  157. return token, err
  158. }
  159. func (token *Token) Insert() error {
  160. var err error
  161. err = DB.Create(token).Error
  162. return err
  163. }
  164. // Update Make sure your token's fields is completed, because this will update non-zero values
  165. func (token *Token) Update() (err error) {
  166. defer func() {
  167. if shouldUpdateRedis(true, err) {
  168. gopool.Go(func() {
  169. err := cacheSetToken(*token)
  170. if err != nil {
  171. common.SysError("failed to update token cache: " + err.Error())
  172. }
  173. })
  174. }
  175. }()
  176. err = DB.Model(token).Select("name", "status", "expired_time", "remain_quota", "unlimited_quota",
  177. "model_limits_enabled", "model_limits", "allow_ips", "group").Updates(token).Error
  178. return err
  179. }
  180. func (token *Token) SelectUpdate() (err error) {
  181. defer func() {
  182. if shouldUpdateRedis(true, err) {
  183. gopool.Go(func() {
  184. err := cacheSetToken(*token)
  185. if err != nil {
  186. common.SysError("failed to update token cache: " + err.Error())
  187. }
  188. })
  189. }
  190. }()
  191. // This can update zero values
  192. return DB.Model(token).Select("accessed_time", "status").Updates(token).Error
  193. }
  194. func (token *Token) Delete() (err error) {
  195. defer func() {
  196. if shouldUpdateRedis(true, err) {
  197. gopool.Go(func() {
  198. err := cacheDeleteToken(token.Key)
  199. if err != nil {
  200. common.SysError("failed to delete token cache: " + err.Error())
  201. }
  202. })
  203. }
  204. }()
  205. err = DB.Delete(token).Error
  206. return err
  207. }
  208. func (token *Token) IsModelLimitsEnabled() bool {
  209. return token.ModelLimitsEnabled
  210. }
  211. func (token *Token) GetModelLimits() []string {
  212. if token.ModelLimits == "" {
  213. return []string{}
  214. }
  215. return strings.Split(token.ModelLimits, ",")
  216. }
  217. func (token *Token) GetModelLimitsMap() map[string]bool {
  218. limits := token.GetModelLimits()
  219. limitsMap := make(map[string]bool)
  220. for _, limit := range limits {
  221. limitsMap[limit] = true
  222. }
  223. return limitsMap
  224. }
  225. func DisableModelLimits(tokenId int) error {
  226. token, err := GetTokenById(tokenId)
  227. if err != nil {
  228. return err
  229. }
  230. token.ModelLimitsEnabled = false
  231. token.ModelLimits = ""
  232. return token.Update()
  233. }
  234. func DeleteTokenById(id int, userId int) (err error) {
  235. // Why we need userId here? In case user want to delete other's token.
  236. if id == 0 || userId == 0 {
  237. return errors.New("id 或 userId 为空!")
  238. }
  239. token := Token{Id: id, UserId: userId}
  240. err = DB.Where(token).First(&token).Error
  241. if err != nil {
  242. return err
  243. }
  244. return token.Delete()
  245. }
  246. func IncreaseTokenQuota(id int, key string, quota int) (err error) {
  247. if quota < 0 {
  248. return errors.New("quota 不能为负数!")
  249. }
  250. if common.RedisEnabled {
  251. gopool.Go(func() {
  252. err := cacheIncrTokenQuota(key, int64(quota))
  253. if err != nil {
  254. common.SysError("failed to increase token quota: " + err.Error())
  255. }
  256. })
  257. }
  258. if common.BatchUpdateEnabled {
  259. addNewRecord(BatchUpdateTypeTokenQuota, id, quota)
  260. return nil
  261. }
  262. return increaseTokenQuota(id, quota)
  263. }
  264. func increaseTokenQuota(id int, quota int) (err error) {
  265. err = DB.Model(&Token{}).Where("id = ?", id).Updates(
  266. map[string]interface{}{
  267. "remain_quota": gorm.Expr("remain_quota + ?", quota),
  268. "used_quota": gorm.Expr("used_quota - ?", quota),
  269. "accessed_time": common.GetTimestamp(),
  270. },
  271. ).Error
  272. return err
  273. }
  274. func DecreaseTokenQuota(id int, key string, quota int) (err error) {
  275. if quota < 0 {
  276. return errors.New("quota 不能为负数!")
  277. }
  278. if common.RedisEnabled {
  279. gopool.Go(func() {
  280. err := cacheDecrTokenQuota(key, int64(quota))
  281. if err != nil {
  282. common.SysError("failed to decrease token quota: " + err.Error())
  283. }
  284. })
  285. }
  286. if common.BatchUpdateEnabled {
  287. addNewRecord(BatchUpdateTypeTokenQuota, id, -quota)
  288. return nil
  289. }
  290. return decreaseTokenQuota(id, quota)
  291. }
  292. func decreaseTokenQuota(id int, quota int) (err error) {
  293. err = DB.Model(&Token{}).Where("id = ?", id).Updates(
  294. map[string]interface{}{
  295. "remain_quota": gorm.Expr("remain_quota - ?", quota),
  296. "used_quota": gorm.Expr("used_quota + ?", quota),
  297. "accessed_time": common.GetTimestamp(),
  298. },
  299. ).Error
  300. return err
  301. }
  302. func PreConsumeTokenQuota(relayInfo *relaycommon.RelayInfo, quota int) error {
  303. if quota < 0 {
  304. return errors.New("quota 不能为负数!")
  305. }
  306. if relayInfo.IsPlayground {
  307. return nil
  308. }
  309. //if relayInfo.TokenUnlimited {
  310. // return nil
  311. //}
  312. token, err := GetTokenById(relayInfo.TokenId)
  313. if err != nil {
  314. return err
  315. }
  316. if !relayInfo.TokenUnlimited && token.RemainQuota < quota {
  317. return errors.New("令牌额度不足")
  318. }
  319. err = DecreaseTokenQuota(relayInfo.TokenId, relayInfo.TokenKey, quota)
  320. if err != nil {
  321. return err
  322. }
  323. return nil
  324. }
  325. func PostConsumeQuota(relayInfo *relaycommon.RelayInfo, userQuota int, quota int, preConsumedQuota int, sendEmail bool) (err error) {
  326. if quota > 0 {
  327. err = DecreaseUserQuota(relayInfo.UserId, quota)
  328. } else {
  329. err = IncreaseUserQuota(relayInfo.UserId, -quota)
  330. }
  331. if err != nil {
  332. return err
  333. }
  334. if !relayInfo.IsPlayground {
  335. if quota > 0 {
  336. err = DecreaseTokenQuota(relayInfo.TokenId, relayInfo.TokenKey, quota)
  337. } else {
  338. err = IncreaseTokenQuota(relayInfo.TokenId, relayInfo.TokenKey, -quota)
  339. }
  340. if err != nil {
  341. return err
  342. }
  343. }
  344. if sendEmail {
  345. if (quota + preConsumedQuota) != 0 {
  346. quotaTooLow := userQuota >= common.QuotaRemindThreshold && userQuota-(quota+preConsumedQuota) < common.QuotaRemindThreshold
  347. noMoreQuota := userQuota-(quota+preConsumedQuota) <= 0
  348. if quotaTooLow || noMoreQuota {
  349. go func() {
  350. email, err := GetUserEmail(relayInfo.UserId)
  351. if err != nil {
  352. common.SysError("failed to fetch user email: " + err.Error())
  353. }
  354. prompt := "您的额度即将用尽"
  355. if noMoreQuota {
  356. prompt = "您的额度已用尽"
  357. }
  358. if email != "" {
  359. topUpLink := fmt.Sprintf("%s/topup", setting.ServerAddress)
  360. err = common.SendEmail(prompt, email,
  361. fmt.Sprintf("%s,当前剩余额度为 %d,为了不影响您的使用,请及时充值。<br/>充值链接:<a href='%s'>%s</a>", prompt, userQuota, topUpLink, topUpLink))
  362. if err != nil {
  363. common.SysError("failed to send email" + err.Error())
  364. }
  365. common.SysLog("user quota is low, consumed quota: " + strconv.Itoa(quota) + ", user quota: " + strconv.Itoa(userQuota))
  366. }
  367. }()
  368. }
  369. }
  370. }
  371. return nil
  372. }