token.go 9.7 KB

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