token.go 8.5 KB

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