token.go 9.1 KB

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