token.go 8.8 KB

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