token.go 9.1 KB

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