user.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734
  1. package model
  2. import (
  3. "errors"
  4. "fmt"
  5. "one-api/common"
  6. "strconv"
  7. "strings"
  8. "github.com/bytedance/gopkg/util/gopool"
  9. "gorm.io/gorm"
  10. )
  11. // User if you add sensitive fields, don't forget to clean them in setupLogin function.
  12. // Otherwise, the sensitive information will be saved on local storage in plain text!
  13. type User struct {
  14. Id int `json:"id"`
  15. Username string `json:"username" gorm:"unique;index" validate:"max=12"`
  16. Password string `json:"password" gorm:"not null;" validate:"min=8,max=20"`
  17. DisplayName string `json:"display_name" gorm:"index" validate:"max=20"`
  18. Role int `json:"role" gorm:"type:int;default:1"` // admin, common
  19. Status int `json:"status" gorm:"type:int;default:1"` // enabled, disabled
  20. Email string `json:"email" gorm:"index" validate:"max=50"`
  21. GitHubId string `json:"github_id" gorm:"column:github_id;index"`
  22. WeChatId string `json:"wechat_id" gorm:"column:wechat_id;index"`
  23. TelegramId string `json:"telegram_id" gorm:"column:telegram_id;index"`
  24. VerificationCode string `json:"verification_code" gorm:"-:all"` // this field is only for Email verification, don't save it to database!
  25. AccessToken *string `json:"access_token" gorm:"type:char(32);column:access_token;uniqueIndex"` // this token is for system management
  26. Quota int `json:"quota" gorm:"type:int;default:0"`
  27. UsedQuota int `json:"used_quota" gorm:"type:int;default:0;column:used_quota"` // used quota
  28. RequestCount int `json:"request_count" gorm:"type:int;default:0;"` // request number
  29. Group string `json:"group" gorm:"type:varchar(64);default:'default'"`
  30. AffCode string `json:"aff_code" gorm:"type:varchar(32);column:aff_code;uniqueIndex"`
  31. AffCount int `json:"aff_count" gorm:"type:int;default:0;column:aff_count"`
  32. AffQuota int `json:"aff_quota" gorm:"type:int;default:0;column:aff_quota"` // 邀请剩余额度
  33. AffHistoryQuota int `json:"aff_history_quota" gorm:"type:int;default:0;column:aff_history"` // 邀请历史额度
  34. InviterId int `json:"inviter_id" gorm:"type:int;column:inviter_id;index"`
  35. DeletedAt gorm.DeletedAt `gorm:"index"`
  36. LinuxDOId string `json:"linux_do_id" gorm:"column:linux_do_id;index"`
  37. }
  38. func (user *User) GetAccessToken() string {
  39. if user.AccessToken == nil {
  40. return ""
  41. }
  42. return *user.AccessToken
  43. }
  44. func (user *User) SetAccessToken(token string) {
  45. user.AccessToken = &token
  46. }
  47. // CheckUserExistOrDeleted check if user exist or deleted, if not exist, return false, nil, if deleted or exist, return true, nil
  48. func CheckUserExistOrDeleted(username string, email string) (bool, error) {
  49. var user User
  50. // err := DB.Unscoped().First(&user, "username = ? or email = ?", username, email).Error
  51. // check email if empty
  52. var err error
  53. if email == "" {
  54. err = DB.Unscoped().First(&user, "username = ?", username).Error
  55. } else {
  56. err = DB.Unscoped().First(&user, "username = ? or email = ?", username, email).Error
  57. }
  58. if err != nil {
  59. if errors.Is(err, gorm.ErrRecordNotFound) {
  60. // not exist, return false, nil
  61. return false, nil
  62. }
  63. // other error, return false, err
  64. return false, err
  65. }
  66. // exist, return true, nil
  67. return true, nil
  68. }
  69. func GetMaxUserId() int {
  70. var user User
  71. DB.Last(&user)
  72. return user.Id
  73. }
  74. func GetAllUsers(startIdx int, num int) (users []*User, total int64, err error) {
  75. // Start transaction
  76. tx := DB.Begin()
  77. if tx.Error != nil {
  78. return nil, 0, tx.Error
  79. }
  80. defer func() {
  81. if r := recover(); r != nil {
  82. tx.Rollback()
  83. }
  84. }()
  85. // Get total count within transaction
  86. err = tx.Unscoped().Model(&User{}).Count(&total).Error
  87. if err != nil {
  88. tx.Rollback()
  89. return nil, 0, err
  90. }
  91. // Get paginated users within same transaction
  92. err = tx.Unscoped().Order("id desc").Limit(num).Offset(startIdx).Omit("password").Find(&users).Error
  93. if err != nil {
  94. tx.Rollback()
  95. return nil, 0, err
  96. }
  97. // Commit transaction
  98. if err = tx.Commit().Error; err != nil {
  99. return nil, 0, err
  100. }
  101. return users, total, nil
  102. }
  103. func SearchUsers(keyword string, group string, startIdx int, num int) ([]*User, int64, error) {
  104. var users []*User
  105. var total int64
  106. var err error
  107. // 开始事务
  108. tx := DB.Begin()
  109. if tx.Error != nil {
  110. return nil, 0, tx.Error
  111. }
  112. defer func() {
  113. if r := recover(); r != nil {
  114. tx.Rollback()
  115. }
  116. }()
  117. // 构建基础查询
  118. query := tx.Unscoped().Model(&User{})
  119. // 构建搜索条件
  120. likeCondition := "username LIKE ? OR email LIKE ? OR display_name LIKE ?"
  121. // 尝试将关键字转换为整数ID
  122. keywordInt, err := strconv.Atoi(keyword)
  123. if err == nil {
  124. // 如果是数字,同时搜索ID和其他字段
  125. likeCondition = "id = ? OR " + likeCondition
  126. if group != "" {
  127. query = query.Where("("+likeCondition+") AND "+groupCol+" = ?",
  128. keywordInt, "%"+keyword+"%", "%"+keyword+"%", "%"+keyword+"%", group)
  129. } else {
  130. query = query.Where(likeCondition,
  131. keywordInt, "%"+keyword+"%", "%"+keyword+"%", "%"+keyword+"%")
  132. }
  133. } else {
  134. // 非数字关键字,只搜索字符串字段
  135. if group != "" {
  136. query = query.Where("("+likeCondition+") AND "+groupCol+" = ?",
  137. "%"+keyword+"%", "%"+keyword+"%", "%"+keyword+"%", group)
  138. } else {
  139. query = query.Where(likeCondition,
  140. "%"+keyword+"%", "%"+keyword+"%", "%"+keyword+"%")
  141. }
  142. }
  143. // 获取总数
  144. err = query.Count(&total).Error
  145. if err != nil {
  146. tx.Rollback()
  147. return nil, 0, err
  148. }
  149. // 获取分页数据
  150. err = query.Omit("password").Order("id desc").Limit(num).Offset(startIdx).Find(&users).Error
  151. if err != nil {
  152. tx.Rollback()
  153. return nil, 0, err
  154. }
  155. // 提交事务
  156. if err = tx.Commit().Error; err != nil {
  157. return nil, 0, err
  158. }
  159. return users, total, nil
  160. }
  161. func GetUserById(id int, selectAll bool) (*User, error) {
  162. if id == 0 {
  163. return nil, errors.New("id 为空!")
  164. }
  165. user := User{Id: id}
  166. var err error = nil
  167. if selectAll {
  168. err = DB.First(&user, "id = ?", id).Error
  169. } else {
  170. err = DB.Omit("password").First(&user, "id = ?", id).Error
  171. }
  172. return &user, err
  173. }
  174. func GetUserIdByAffCode(affCode string) (int, error) {
  175. if affCode == "" {
  176. return 0, errors.New("affCode 为空!")
  177. }
  178. var user User
  179. err := DB.Select("id").First(&user, "aff_code = ?", affCode).Error
  180. return user.Id, err
  181. }
  182. func DeleteUserById(id int) (err error) {
  183. if id == 0 {
  184. return errors.New("id 为空!")
  185. }
  186. user := User{Id: id}
  187. return user.Delete()
  188. }
  189. func HardDeleteUserById(id int) error {
  190. if id == 0 {
  191. return errors.New("id 为空!")
  192. }
  193. err := DB.Unscoped().Delete(&User{}, "id = ?", id).Error
  194. return err
  195. }
  196. func inviteUser(inviterId int) (err error) {
  197. user, err := GetUserById(inviterId, true)
  198. if err != nil {
  199. return err
  200. }
  201. user.AffCount++
  202. user.AffQuota += common.QuotaForInviter
  203. user.AffHistoryQuota += common.QuotaForInviter
  204. return DB.Save(user).Error
  205. }
  206. func (user *User) TransferAffQuotaToQuota(quota int) error {
  207. // 检查quota是否小于最小额度
  208. if float64(quota) < common.QuotaPerUnit {
  209. return fmt.Errorf("转移额度最小为%s!", common.LogQuota(int(common.QuotaPerUnit)))
  210. }
  211. // 开始数据库事务
  212. tx := DB.Begin()
  213. if tx.Error != nil {
  214. return tx.Error
  215. }
  216. defer tx.Rollback() // 确保在函数退出时事务能回滚
  217. // 加锁查询用户以确保数据一致性
  218. err := tx.Set("gorm:query_option", "FOR UPDATE").First(&user, user.Id).Error
  219. if err != nil {
  220. return err
  221. }
  222. // 再次检查用户的AffQuota是否足够
  223. if user.AffQuota < quota {
  224. return errors.New("邀请额度不足!")
  225. }
  226. // 更新用户额度
  227. user.AffQuota -= quota
  228. user.Quota += quota
  229. // 保存用户状态
  230. if err := tx.Save(user).Error; err != nil {
  231. return err
  232. }
  233. // 提交事务
  234. return tx.Commit().Error
  235. }
  236. func (user *User) Insert(inviterId int) error {
  237. var err error
  238. if user.Password != "" {
  239. user.Password, err = common.Password2Hash(user.Password)
  240. if err != nil {
  241. return err
  242. }
  243. }
  244. user.Quota = common.QuotaForNewUser
  245. //user.SetAccessToken(common.GetUUID())
  246. user.AffCode = common.GetRandomString(4)
  247. result := DB.Create(user)
  248. if result.Error != nil {
  249. return result.Error
  250. }
  251. if common.QuotaForNewUser > 0 {
  252. RecordLog(user.Id, LogTypeSystem, fmt.Sprintf("新用户注册赠送 %s", common.LogQuota(common.QuotaForNewUser)))
  253. }
  254. if inviterId != 0 {
  255. if common.QuotaForInvitee > 0 {
  256. _ = IncreaseUserQuota(user.Id, common.QuotaForInvitee)
  257. RecordLog(user.Id, LogTypeSystem, fmt.Sprintf("使用邀请码赠送 %s", common.LogQuota(common.QuotaForInvitee)))
  258. }
  259. if common.QuotaForInviter > 0 {
  260. //_ = IncreaseUserQuota(inviterId, common.QuotaForInviter)
  261. RecordLog(inviterId, LogTypeSystem, fmt.Sprintf("邀请用户赠送 %s", common.LogQuota(common.QuotaForInviter)))
  262. _ = inviteUser(inviterId)
  263. }
  264. }
  265. return nil
  266. }
  267. func (user *User) Update(updatePassword bool) error {
  268. var err error
  269. if updatePassword {
  270. user.Password, err = common.Password2Hash(user.Password)
  271. if err != nil {
  272. return err
  273. }
  274. }
  275. newUser := *user
  276. DB.First(&user, user.Id)
  277. if err = DB.Model(user).Updates(newUser).Error; err != nil {
  278. return err
  279. }
  280. // 更新缓存
  281. return updateUserCache(user.Id, user.Username, user.Group, user.Quota, user.Status)
  282. }
  283. func (user *User) Edit(updatePassword bool) error {
  284. var err error
  285. if updatePassword {
  286. user.Password, err = common.Password2Hash(user.Password)
  287. if err != nil {
  288. return err
  289. }
  290. }
  291. newUser := *user
  292. updates := map[string]interface{}{
  293. "username": newUser.Username,
  294. "display_name": newUser.DisplayName,
  295. "group": newUser.Group,
  296. "quota": newUser.Quota,
  297. }
  298. if updatePassword {
  299. updates["password"] = newUser.Password
  300. }
  301. DB.First(&user, user.Id)
  302. if err = DB.Model(user).Updates(updates).Error; err != nil {
  303. return err
  304. }
  305. // 更新缓存
  306. return updateUserCache(user.Id, user.Username, user.Group, user.Quota, user.Status)
  307. }
  308. func (user *User) Delete() error {
  309. if user.Id == 0 {
  310. return errors.New("id 为空!")
  311. }
  312. if err := DB.Delete(user).Error; err != nil {
  313. return err
  314. }
  315. // 清除缓存
  316. return invalidateUserCache(user.Id)
  317. }
  318. func (user *User) HardDelete() error {
  319. if user.Id == 0 {
  320. return errors.New("id 为空!")
  321. }
  322. err := DB.Unscoped().Delete(user).Error
  323. return err
  324. }
  325. // ValidateAndFill check password & user status
  326. func (user *User) ValidateAndFill() (err error) {
  327. // When querying with struct, GORM will only query with non-zero fields,
  328. // that means if your field’s value is 0, '', false or other zero values,
  329. // it won’t be used to build query conditions
  330. password := user.Password
  331. username := strings.TrimSpace(user.Username)
  332. if username == "" || password == "" {
  333. return errors.New("用户名或密码为空")
  334. }
  335. // find buy username or email
  336. DB.Where("username = ? OR email = ?", username, username).First(user)
  337. okay := common.ValidatePasswordAndHash(password, user.Password)
  338. if !okay || user.Status != common.UserStatusEnabled {
  339. return errors.New("用户名或密码错误,或用户已被封禁")
  340. }
  341. return nil
  342. }
  343. func (user *User) FillUserById() error {
  344. if user.Id == 0 {
  345. return errors.New("id 为空!")
  346. }
  347. DB.Where(User{Id: user.Id}).First(user)
  348. return nil
  349. }
  350. func (user *User) FillUserByEmail() error {
  351. if user.Email == "" {
  352. return errors.New("email 为空!")
  353. }
  354. DB.Where(User{Email: user.Email}).First(user)
  355. return nil
  356. }
  357. func (user *User) FillUserByGitHubId() error {
  358. if user.GitHubId == "" {
  359. return errors.New("GitHub id 为空!")
  360. }
  361. DB.Where(User{GitHubId: user.GitHubId}).First(user)
  362. return nil
  363. }
  364. func (user *User) FillUserByWeChatId() error {
  365. if user.WeChatId == "" {
  366. return errors.New("WeChat id 为空!")
  367. }
  368. DB.Where(User{WeChatId: user.WeChatId}).First(user)
  369. return nil
  370. }
  371. func (user *User) FillUserByTelegramId() error {
  372. if user.TelegramId == "" {
  373. return errors.New("Telegram id 为空!")
  374. }
  375. err := DB.Where(User{TelegramId: user.TelegramId}).First(user).Error
  376. if errors.Is(err, gorm.ErrRecordNotFound) {
  377. return errors.New("该 Telegram 账户未绑定")
  378. }
  379. return nil
  380. }
  381. func IsEmailAlreadyTaken(email string) bool {
  382. return DB.Unscoped().Where("email = ?", email).Find(&User{}).RowsAffected == 1
  383. }
  384. func IsWeChatIdAlreadyTaken(wechatId string) bool {
  385. return DB.Unscoped().Where("wechat_id = ?", wechatId).Find(&User{}).RowsAffected == 1
  386. }
  387. func IsGitHubIdAlreadyTaken(githubId string) bool {
  388. return DB.Unscoped().Where("github_id = ?", githubId).Find(&User{}).RowsAffected == 1
  389. }
  390. func IsTelegramIdAlreadyTaken(telegramId string) bool {
  391. return DB.Unscoped().Where("telegram_id = ?", telegramId).Find(&User{}).RowsAffected == 1
  392. }
  393. func ResetUserPasswordByEmail(email string, password string) error {
  394. if email == "" || password == "" {
  395. return errors.New("邮箱地址或密码为空!")
  396. }
  397. hashedPassword, err := common.Password2Hash(password)
  398. if err != nil {
  399. return err
  400. }
  401. err = DB.Model(&User{}).Where("email = ?", email).Update("password", hashedPassword).Error
  402. return err
  403. }
  404. func IsAdmin(userId int) bool {
  405. if userId == 0 {
  406. return false
  407. }
  408. var user User
  409. err := DB.Where("id = ?", userId).Select("role").Find(&user).Error
  410. if err != nil {
  411. common.SysError("no such user " + err.Error())
  412. return false
  413. }
  414. return user.Role >= common.RoleAdminUser
  415. }
  416. // IsUserEnabled checks user status from Redis first, falls back to DB if needed
  417. func IsUserEnabled(id int, fromDB bool) (status bool, err error) {
  418. defer func() {
  419. // Update Redis cache asynchronously on successful DB read
  420. if shouldUpdateRedis(fromDB, err) {
  421. gopool.Go(func() {
  422. if err := updateUserStatusCache(id, status); err != nil {
  423. common.SysError("failed to update user status cache: " + err.Error())
  424. }
  425. })
  426. }
  427. }()
  428. if !fromDB && common.RedisEnabled {
  429. // Try Redis first
  430. status, err := getUserStatusCache(id)
  431. if err == nil {
  432. return status == common.UserStatusEnabled, nil
  433. }
  434. // Don't return error - fall through to DB
  435. }
  436. fromDB = true
  437. var user User
  438. err = DB.Where("id = ?", id).Select("status").Find(&user).Error
  439. if err != nil {
  440. return false, err
  441. }
  442. return user.Status == common.UserStatusEnabled, nil
  443. }
  444. func ValidateAccessToken(token string) (user *User) {
  445. if token == "" {
  446. return nil
  447. }
  448. token = strings.Replace(token, "Bearer ", "", 1)
  449. user = &User{}
  450. if DB.Where("access_token = ?", token).First(user).RowsAffected == 1 {
  451. return user
  452. }
  453. return nil
  454. }
  455. // GetUserQuota gets quota from Redis first, falls back to DB if needed
  456. func GetUserQuota(id int, fromDB bool) (quota int, err error) {
  457. defer func() {
  458. // Update Redis cache asynchronously on successful DB read
  459. if shouldUpdateRedis(fromDB, err) {
  460. gopool.Go(func() {
  461. if err := updateUserQuotaCache(id, quota); err != nil {
  462. common.SysError("failed to update user quota cache: " + err.Error())
  463. }
  464. })
  465. }
  466. }()
  467. if !fromDB && common.RedisEnabled {
  468. quota, err := getUserQuotaCache(id)
  469. if err == nil {
  470. return quota, nil
  471. }
  472. // Don't return error - fall through to DB
  473. //common.SysError("failed to get user quota from cache: " + err.Error())
  474. }
  475. fromDB = true
  476. err = DB.Model(&User{}).Where("id = ?", id).Select("quota").Find(&quota).Error
  477. if err != nil {
  478. return 0, err
  479. }
  480. return quota, nil
  481. }
  482. func GetUserUsedQuota(id int) (quota int, err error) {
  483. err = DB.Model(&User{}).Where("id = ?", id).Select("used_quota").Find(&quota).Error
  484. return quota, err
  485. }
  486. func GetUserEmail(id int) (email string, err error) {
  487. err = DB.Model(&User{}).Where("id = ?", id).Select("email").Find(&email).Error
  488. return email, err
  489. }
  490. // GetUserGroup gets group from Redis first, falls back to DB if needed
  491. func GetUserGroup(id int, fromDB bool) (group string, err error) {
  492. defer func() {
  493. // Update Redis cache asynchronously on successful DB read
  494. if shouldUpdateRedis(fromDB, err) {
  495. gopool.Go(func() {
  496. if err := updateUserGroupCache(id, group); err != nil {
  497. common.SysError("failed to update user group cache: " + err.Error())
  498. }
  499. })
  500. }
  501. }()
  502. if !fromDB && common.RedisEnabled {
  503. group, err := getUserGroupCache(id)
  504. if err == nil {
  505. return group, nil
  506. }
  507. // Don't return error - fall through to DB
  508. }
  509. fromDB = true
  510. err = DB.Model(&User{}).Where("id = ?", id).Select(groupCol).Find(&group).Error
  511. if err != nil {
  512. return "", err
  513. }
  514. return group, nil
  515. }
  516. func IncreaseUserQuota(id int, quota int) (err error) {
  517. if quota < 0 {
  518. return errors.New("quota 不能为负数!")
  519. }
  520. gopool.Go(func() {
  521. err := cacheIncrUserQuota(id, int64(quota))
  522. if err != nil {
  523. common.SysError("failed to increase user quota: " + err.Error())
  524. }
  525. })
  526. if common.BatchUpdateEnabled {
  527. addNewRecord(BatchUpdateTypeUserQuota, id, quota)
  528. return nil
  529. }
  530. return increaseUserQuota(id, quota)
  531. }
  532. func increaseUserQuota(id int, quota int) (err error) {
  533. err = DB.Model(&User{}).Where("id = ?", id).Update("quota", gorm.Expr("quota + ?", quota)).Error
  534. if err != nil {
  535. return err
  536. }
  537. return err
  538. }
  539. func DecreaseUserQuota(id int, quota int) (err error) {
  540. if quota < 0 {
  541. return errors.New("quota 不能为负数!")
  542. }
  543. gopool.Go(func() {
  544. err := cacheDecrUserQuota(id, int64(quota))
  545. if err != nil {
  546. common.SysError("failed to decrease user quota: " + err.Error())
  547. }
  548. })
  549. if common.BatchUpdateEnabled {
  550. addNewRecord(BatchUpdateTypeUserQuota, id, -quota)
  551. return nil
  552. }
  553. return decreaseUserQuota(id, quota)
  554. }
  555. func decreaseUserQuota(id int, quota int) (err error) {
  556. err = DB.Model(&User{}).Where("id = ?", id).Update("quota", gorm.Expr("quota - ?", quota)).Error
  557. if err != nil {
  558. return err
  559. }
  560. return err
  561. }
  562. func DeltaUpdateUserQuota(id int, delta int) (err error) {
  563. if delta == 0 {
  564. return nil
  565. }
  566. if delta > 0 {
  567. return IncreaseUserQuota(id, delta)
  568. } else {
  569. return DecreaseUserQuota(id, -delta)
  570. }
  571. }
  572. func GetRootUserEmail() (email string) {
  573. DB.Model(&User{}).Where("role = ?", common.RoleRootUser).Select("email").Find(&email)
  574. return email
  575. }
  576. func UpdateUserUsedQuotaAndRequestCount(id int, quota int) {
  577. if common.BatchUpdateEnabled {
  578. addNewRecord(BatchUpdateTypeUsedQuota, id, quota)
  579. addNewRecord(BatchUpdateTypeRequestCount, id, 1)
  580. return
  581. }
  582. updateUserUsedQuotaAndRequestCount(id, quota, 1)
  583. }
  584. func updateUserUsedQuotaAndRequestCount(id int, quota int, count int) {
  585. err := DB.Model(&User{}).Where("id = ?", id).Updates(
  586. map[string]interface{}{
  587. "used_quota": gorm.Expr("used_quota + ?", quota),
  588. "request_count": gorm.Expr("request_count + ?", count),
  589. },
  590. ).Error
  591. if err != nil {
  592. common.SysError("failed to update user used quota and request count: " + err.Error())
  593. return
  594. }
  595. //// 更新缓存
  596. //if err := invalidateUserCache(id); err != nil {
  597. // common.SysError("failed to invalidate user cache: " + err.Error())
  598. //}
  599. }
  600. func updateUserUsedQuota(id int, quota int) {
  601. err := DB.Model(&User{}).Where("id = ?", id).Updates(
  602. map[string]interface{}{
  603. "used_quota": gorm.Expr("used_quota + ?", quota),
  604. },
  605. ).Error
  606. if err != nil {
  607. common.SysError("failed to update user used quota: " + err.Error())
  608. }
  609. }
  610. func updateUserRequestCount(id int, count int) {
  611. err := DB.Model(&User{}).Where("id = ?", id).Update("request_count", gorm.Expr("request_count + ?", count)).Error
  612. if err != nil {
  613. common.SysError("failed to update user request count: " + err.Error())
  614. }
  615. }
  616. // GetUsernameById gets username from Redis first, falls back to DB if needed
  617. func GetUsernameById(id int, fromDB bool) (username string, err error) {
  618. defer func() {
  619. // Update Redis cache asynchronously on successful DB read
  620. if shouldUpdateRedis(fromDB, err) {
  621. gopool.Go(func() {
  622. if err := updateUserNameCache(id, username); err != nil {
  623. common.SysError("failed to update user name cache: " + err.Error())
  624. }
  625. })
  626. }
  627. }()
  628. if !fromDB && common.RedisEnabled {
  629. username, err := getUserNameCache(id)
  630. if err == nil {
  631. return username, nil
  632. }
  633. // Don't return error - fall through to DB
  634. }
  635. fromDB = true
  636. err = DB.Model(&User{}).Where("id = ?", id).Select("username").Find(&username).Error
  637. if err != nil {
  638. return "", err
  639. }
  640. return username, nil
  641. }
  642. func IsLinuxDOIdAlreadyTaken(linuxDOId string) bool {
  643. var user User
  644. err := DB.Unscoped().Where("linux_do_id = ?", linuxDOId).First(&user).Error
  645. return !errors.Is(err, gorm.ErrRecordNotFound)
  646. }
  647. func (u *User) FillUserByLinuxDOId() error {
  648. if u.LinuxDOId == "" {
  649. return errors.New("linux do id is empty")
  650. }
  651. err := DB.Where("linux_do_id = ?", u.LinuxDOId).First(u).Error
  652. return err
  653. }