token.go 9.9 KB

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