token.go 8.7 KB

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