token.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. package model
  2. import (
  3. "errors"
  4. "fmt"
  5. "gorm.io/gorm"
  6. "one-api/common"
  7. "strconv"
  8. "strings"
  9. )
  10. type Token struct {
  11. Id int `json:"id"`
  12. UserId int `json:"user_id"`
  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" gorm:"default:false"`
  21. ModelLimitsEnabled bool `json:"model_limits_enabled" gorm:"default:false"`
  22. ModelLimits string `json:"model_limits" gorm:"type:varchar(1024);default:''"`
  23. UsedQuota int `json:"used_quota" gorm:"default:0"` // used quota
  24. DeletedAt gorm.DeletedAt `gorm:"index"`
  25. }
  26. func GetAllUserTokens(userId int, startIdx int, num int) ([]*Token, error) {
  27. var tokens []*Token
  28. var err error
  29. err = DB.Where("user_id = ?", userId).Order("id desc").Limit(num).Offset(startIdx).Find(&tokens).Error
  30. return tokens, err
  31. }
  32. func SearchUserTokens(userId int, keyword string, token string) (tokens []*Token, err error) {
  33. if token != "" {
  34. token = strings.Trim(token, "sk-")
  35. }
  36. err = DB.Where("user_id = ?", userId).Where("name LIKE ?", "%"+keyword+"%").Where("`key` LIKE ?", "%"+token+"%").Find(&tokens).Error
  37. return tokens, err
  38. }
  39. func ValidateUserToken(key string) (token *Token, err error) {
  40. if key == "" {
  41. return nil, errors.New("未提供令牌")
  42. }
  43. token, err = CacheGetTokenByKey(key)
  44. if err == nil {
  45. if token.Status == common.TokenStatusExhausted {
  46. keyPrefix := key[:3]
  47. keySuffix := key[len(key)-3:]
  48. return nil, errors.New("该令牌额度已用尽 TokenStatusExhausted[sk-" + keyPrefix + "***" + keySuffix + "]")
  49. } else if token.Status == common.TokenStatusExpired {
  50. return nil, errors.New("该令牌已过期")
  51. }
  52. if token.Status != common.TokenStatusEnabled {
  53. return nil, errors.New("该令牌状态不可用")
  54. }
  55. if token.ExpiredTime != -1 && token.ExpiredTime < common.GetTimestamp() {
  56. if !common.RedisEnabled {
  57. token.Status = common.TokenStatusExpired
  58. err := token.SelectUpdate()
  59. if err != nil {
  60. common.SysError("failed to update token status" + err.Error())
  61. }
  62. }
  63. return nil, errors.New("该令牌已过期")
  64. }
  65. if !token.UnlimitedQuota && token.RemainQuota <= 0 {
  66. if !common.RedisEnabled {
  67. // in this case, we can make sure the token is exhausted
  68. token.Status = common.TokenStatusExhausted
  69. err := token.SelectUpdate()
  70. if err != nil {
  71. common.SysError("failed to update token status" + err.Error())
  72. }
  73. }
  74. keyPrefix := key[:3]
  75. keySuffix := key[len(key)-3:]
  76. return nil, errors.New(fmt.Sprintf("[sk-%s***%s] 该令牌额度已用尽 !token.UnlimitedQuota && token.RemainQuota = %d", keyPrefix, keySuffix, token.RemainQuota))
  77. }
  78. return token, nil
  79. }
  80. return nil, errors.New("无效的令牌")
  81. }
  82. func GetTokenByIds(id int, userId int) (*Token, error) {
  83. if id == 0 || userId == 0 {
  84. return nil, errors.New("id 或 userId 为空!")
  85. }
  86. token := Token{Id: id, UserId: userId}
  87. var err error = nil
  88. err = DB.First(&token, "id = ? and user_id = ?", id, userId).Error
  89. return &token, err
  90. }
  91. func GetTokenById(id int) (*Token, error) {
  92. if id == 0 {
  93. return nil, errors.New("id 为空!")
  94. }
  95. token := Token{Id: id}
  96. var err error = nil
  97. err = DB.First(&token, "id = ?", id).Error
  98. return &token, err
  99. }
  100. func GetTokenByKey(key string) (*Token, error) {
  101. keyCol := "`key`"
  102. if common.UsingPostgreSQL {
  103. keyCol = `"key"`
  104. }
  105. var token Token
  106. err := DB.Where(keyCol+" = ?", key).First(&token).Error
  107. return &token, err
  108. }
  109. func (token *Token) Insert() error {
  110. var err error
  111. err = DB.Create(token).Error
  112. return err
  113. }
  114. // Update Make sure your token's fields is completed, because this will update non-zero values
  115. func (token *Token) Update() error {
  116. var err error
  117. err = DB.Model(token).Select("name", "status", "expired_time", "remain_quota", "unlimited_quota", "model_limits_enabled", "model_limits").Updates(token).Error
  118. return err
  119. }
  120. func (token *Token) SelectUpdate() error {
  121. // This can update zero values
  122. return DB.Model(token).Select("accessed_time", "status").Updates(token).Error
  123. }
  124. func (token *Token) Delete() error {
  125. var err error
  126. err = DB.Delete(token).Error
  127. return err
  128. }
  129. func (token *Token) IsModelLimitsEnabled() bool {
  130. return token.ModelLimitsEnabled
  131. }
  132. func (token *Token) GetModelLimits() []string {
  133. if token.ModelLimits == "" {
  134. return []string{}
  135. }
  136. return strings.Split(token.ModelLimits, ",")
  137. }
  138. func (token *Token) GetModelLimitsMap() map[string]bool {
  139. limits := token.GetModelLimits()
  140. limitsMap := make(map[string]bool)
  141. for _, limit := range limits {
  142. limitsMap[limit] = true
  143. }
  144. return limitsMap
  145. }
  146. func DisableModelLimits(tokenId int) error {
  147. token, err := GetTokenById(tokenId)
  148. if err != nil {
  149. return err
  150. }
  151. token.ModelLimitsEnabled = false
  152. token.ModelLimits = ""
  153. return token.Update()
  154. }
  155. func DeleteTokenById(id int, userId int) (err error) {
  156. // Why we need userId here? In case user want to delete other's token.
  157. if id == 0 || userId == 0 {
  158. return errors.New("id 或 userId 为空!")
  159. }
  160. token := Token{Id: id, UserId: userId}
  161. err = DB.Where(token).First(&token).Error
  162. if err != nil {
  163. return err
  164. }
  165. return token.Delete()
  166. }
  167. func IncreaseTokenQuota(id int, quota int) (err error) {
  168. if quota < 0 {
  169. return errors.New("quota 不能为负数!")
  170. }
  171. if common.BatchUpdateEnabled {
  172. addNewRecord(BatchUpdateTypeTokenQuota, id, quota)
  173. return nil
  174. }
  175. return increaseTokenQuota(id, quota)
  176. }
  177. func increaseTokenQuota(id int, quota int) (err error) {
  178. err = DB.Model(&Token{}).Where("id = ?", id).Updates(
  179. map[string]interface{}{
  180. "remain_quota": gorm.Expr("remain_quota + ?", quota),
  181. "used_quota": gorm.Expr("used_quota - ?", quota),
  182. "accessed_time": common.GetTimestamp(),
  183. },
  184. ).Error
  185. return err
  186. }
  187. func DecreaseTokenQuota(id int, quota int) (err error) {
  188. if quota < 0 {
  189. return errors.New("quota 不能为负数!")
  190. }
  191. if common.BatchUpdateEnabled {
  192. addNewRecord(BatchUpdateTypeTokenQuota, id, -quota)
  193. return nil
  194. }
  195. return decreaseTokenQuota(id, quota)
  196. }
  197. func decreaseTokenQuota(id int, quota int) (err error) {
  198. err = DB.Model(&Token{}).Where("id = ?", id).Updates(
  199. map[string]interface{}{
  200. "remain_quota": gorm.Expr("remain_quota - ?", quota),
  201. "used_quota": gorm.Expr("used_quota + ?", quota),
  202. "accessed_time": common.GetTimestamp(),
  203. },
  204. ).Error
  205. return err
  206. }
  207. func PreConsumeTokenQuota(tokenId int, quota int) (userQuota int, err error) {
  208. if quota < 0 {
  209. return 0, errors.New("quota 不能为负数!")
  210. }
  211. token, err := GetTokenById(tokenId)
  212. if err != nil {
  213. return 0, err
  214. }
  215. if !token.UnlimitedQuota && token.RemainQuota < quota {
  216. return 0, errors.New("令牌额度不足")
  217. }
  218. userQuota, err = GetUserQuota(token.UserId)
  219. if err != nil {
  220. return 0, err
  221. }
  222. if userQuota < quota {
  223. return 0, errors.New(fmt.Sprintf("用户额度不足,剩余额度为 %d", userQuota))
  224. }
  225. if !token.UnlimitedQuota {
  226. err = DecreaseTokenQuota(tokenId, quota)
  227. if err != nil {
  228. return 0, err
  229. }
  230. }
  231. err = DecreaseUserQuota(token.UserId, quota)
  232. return userQuota - quota, err
  233. }
  234. func PostConsumeTokenQuota(tokenId int, userQuota int, quota int, preConsumedQuota int, sendEmail bool) (err error) {
  235. token, err := GetTokenById(tokenId)
  236. if quota > 0 {
  237. err = DecreaseUserQuota(token.UserId, quota)
  238. } else {
  239. err = IncreaseUserQuota(token.UserId, -quota)
  240. }
  241. if err != nil {
  242. return err
  243. }
  244. if !token.UnlimitedQuota {
  245. if quota > 0 {
  246. err = DecreaseTokenQuota(tokenId, quota)
  247. } else {
  248. err = IncreaseTokenQuota(tokenId, -quota)
  249. }
  250. if err != nil {
  251. return err
  252. }
  253. }
  254. if sendEmail {
  255. if (quota + preConsumedQuota) != 0 {
  256. quotaTooLow := userQuota >= common.QuotaRemindThreshold && userQuota-(quota+preConsumedQuota) < common.QuotaRemindThreshold
  257. noMoreQuota := userQuota-(quota+preConsumedQuota) <= 0
  258. if quotaTooLow || noMoreQuota {
  259. go func() {
  260. email, err := GetUserEmail(token.UserId)
  261. if err != nil {
  262. common.SysError("failed to fetch user email: " + err.Error())
  263. }
  264. prompt := "您的额度即将用尽"
  265. if noMoreQuota {
  266. prompt = "您的额度已用尽"
  267. }
  268. if email != "" {
  269. topUpLink := fmt.Sprintf("%s/topup", common.ServerAddress)
  270. err = common.SendEmail(prompt, email,
  271. fmt.Sprintf("%s,当前剩余额度为 %d,为了不影响您的使用,请及时充值。<br/>充值链接:<a href='%s'>%s</a>", prompt, userQuota, topUpLink, topUpLink))
  272. if err != nil {
  273. common.SysError("failed to send email" + err.Error())
  274. }
  275. common.SysLog("user quota is low, consumed quota: " + strconv.Itoa(quota) + ", user quota: " + strconv.Itoa(userQuota))
  276. }
  277. }()
  278. }
  279. }
  280. }
  281. return nil
  282. }