token.go 9.6 KB

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