token.go 7.4 KB

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