token.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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. if err != nil {
  99. go cacheSetToken(&token)
  100. }
  101. return &token, err
  102. }
  103. func GetTokenByKey(key string) (*Token, error) {
  104. keyCol := "`key`"
  105. if common.UsingPostgreSQL {
  106. keyCol = `"key"`
  107. }
  108. var token Token
  109. err := DB.Where(keyCol+" = ?", key).First(&token).Error
  110. return &token, err
  111. }
  112. func (token *Token) Insert() error {
  113. var err error
  114. err = DB.Create(token).Error
  115. return err
  116. }
  117. // Update Make sure your token's fields is completed, because this will update non-zero values
  118. func (token *Token) Update() error {
  119. var err error
  120. err = DB.Model(token).Select("name", "status", "expired_time", "remain_quota", "unlimited_quota", "model_limits_enabled", "model_limits").Updates(token).Error
  121. return err
  122. }
  123. func (token *Token) SelectUpdate() error {
  124. // This can update zero values
  125. return DB.Model(token).Select("accessed_time", "status").Updates(token).Error
  126. }
  127. func (token *Token) Delete() error {
  128. var err error
  129. err = DB.Delete(token).Error
  130. return err
  131. }
  132. func (token *Token) IsModelLimitsEnabled() bool {
  133. return token.ModelLimitsEnabled
  134. }
  135. func (token *Token) GetModelLimits() []string {
  136. if token.ModelLimits == "" {
  137. return []string{}
  138. }
  139. return strings.Split(token.ModelLimits, ",")
  140. }
  141. func (token *Token) GetModelLimitsMap() map[string]bool {
  142. limits := token.GetModelLimits()
  143. limitsMap := make(map[string]bool)
  144. for _, limit := range limits {
  145. limitsMap[limit] = true
  146. }
  147. return limitsMap
  148. }
  149. func DisableModelLimits(tokenId int) error {
  150. token, err := GetTokenById(tokenId)
  151. if err != nil {
  152. return err
  153. }
  154. token.ModelLimitsEnabled = false
  155. token.ModelLimits = ""
  156. return token.Update()
  157. }
  158. func DeleteTokenById(id int, userId int) (err error) {
  159. // Why we need userId here? In case user want to delete other's token.
  160. if id == 0 || userId == 0 {
  161. return errors.New("id 或 userId 为空!")
  162. }
  163. token := Token{Id: id, UserId: userId}
  164. err = DB.Where(token).First(&token).Error
  165. if err != nil {
  166. return err
  167. }
  168. return token.Delete()
  169. }
  170. func IncreaseTokenQuota(id int, quota int) (err error) {
  171. if quota < 0 {
  172. return errors.New("quota 不能为负数!")
  173. }
  174. if common.BatchUpdateEnabled {
  175. addNewRecord(BatchUpdateTypeTokenQuota, id, quota)
  176. return nil
  177. }
  178. return increaseTokenQuota(id, quota)
  179. }
  180. func increaseTokenQuota(id int, quota int) (err error) {
  181. err = DB.Model(&Token{}).Where("id = ?", id).Updates(
  182. map[string]interface{}{
  183. "remain_quota": gorm.Expr("remain_quota + ?", quota),
  184. "used_quota": gorm.Expr("used_quota - ?", quota),
  185. "accessed_time": common.GetTimestamp(),
  186. },
  187. ).Error
  188. return err
  189. }
  190. func DecreaseTokenQuota(id int, quota int) (err error) {
  191. if quota < 0 {
  192. return errors.New("quota 不能为负数!")
  193. }
  194. if common.BatchUpdateEnabled {
  195. addNewRecord(BatchUpdateTypeTokenQuota, id, -quota)
  196. return nil
  197. }
  198. return decreaseTokenQuota(id, quota)
  199. }
  200. func decreaseTokenQuota(id int, quota int) (err error) {
  201. err = DB.Model(&Token{}).Where("id = ?", id).Updates(
  202. map[string]interface{}{
  203. "remain_quota": gorm.Expr("remain_quota - ?", quota),
  204. "used_quota": gorm.Expr("used_quota + ?", quota),
  205. "accessed_time": common.GetTimestamp(),
  206. },
  207. ).Error
  208. return err
  209. }
  210. func PreConsumeTokenQuota(tokenId int, quota int) (userQuota int, err error) {
  211. if quota < 0 {
  212. return 0, errors.New("quota 不能为负数!")
  213. }
  214. token, err := GetTokenById(tokenId)
  215. if err != nil {
  216. return 0, err
  217. }
  218. if !token.UnlimitedQuota && token.RemainQuota < quota {
  219. return 0, errors.New("令牌额度不足")
  220. }
  221. userQuota, err = GetUserQuota(token.UserId)
  222. if err != nil {
  223. return 0, err
  224. }
  225. if userQuota < quota {
  226. return 0, errors.New(fmt.Sprintf("用户额度不足,剩余额度为 %d", userQuota))
  227. }
  228. if !token.UnlimitedQuota {
  229. err = DecreaseTokenQuota(tokenId, quota)
  230. if err != nil {
  231. return 0, err
  232. }
  233. }
  234. err = DecreaseUserQuota(token.UserId, quota)
  235. return userQuota - quota, err
  236. }
  237. func PostConsumeTokenQuota(tokenId int, userQuota int, quota int, preConsumedQuota int, sendEmail bool) (err error) {
  238. token, err := GetTokenById(tokenId)
  239. if quota > 0 {
  240. err = DecreaseUserQuota(token.UserId, quota)
  241. } else {
  242. err = IncreaseUserQuota(token.UserId, -quota)
  243. }
  244. if err != nil {
  245. return err
  246. }
  247. if !token.UnlimitedQuota {
  248. if quota > 0 {
  249. err = DecreaseTokenQuota(tokenId, quota)
  250. } else {
  251. err = IncreaseTokenQuota(tokenId, -quota)
  252. }
  253. if err != nil {
  254. return err
  255. }
  256. }
  257. if sendEmail {
  258. if (quota + preConsumedQuota) != 0 {
  259. quotaTooLow := userQuota >= common.QuotaRemindThreshold && userQuota-(quota+preConsumedQuota) < common.QuotaRemindThreshold
  260. noMoreQuota := userQuota-(quota+preConsumedQuota) <= 0
  261. if quotaTooLow || noMoreQuota {
  262. go func() {
  263. email, err := GetUserEmail(token.UserId)
  264. if err != nil {
  265. common.SysError("failed to fetch user email: " + err.Error())
  266. }
  267. prompt := "您的额度即将用尽"
  268. if noMoreQuota {
  269. prompt = "您的额度已用尽"
  270. }
  271. if email != "" {
  272. topUpLink := fmt.Sprintf("%s/topup", common.ServerAddress)
  273. err = common.SendEmail(prompt, email,
  274. fmt.Sprintf("%s,当前剩余额度为 %d,为了不影响您的使用,请及时充值。<br/>充值链接:<a href='%s'>%s</a>", prompt, userQuota, topUpLink, topUpLink))
  275. if err != nil {
  276. common.SysError("failed to send email" + err.Error())
  277. }
  278. common.SysLog("user quota is low, consumed quota: " + strconv.Itoa(quota) + ", user quota: " + strconv.Itoa(userQuota))
  279. }
  280. }()
  281. }
  282. }
  283. }
  284. return nil
  285. }