user.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729
  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. // 尝试将关键字转换为整数ID
  120. keywordInt, err := strconv.Atoi(keyword)
  121. if err == nil {
  122. // 如果转换成功,按照ID和可选的组别搜索用户
  123. if group != "" {
  124. query = query.Where("id = ? AND "+groupCol+" = ?", keywordInt, group)
  125. } else {
  126. query = query.Where("id = ?", keywordInt)
  127. }
  128. } else {
  129. // 如果不是ID搜索,则使用模糊匹配
  130. likeCondition := "username LIKE ? OR email LIKE ? OR display_name LIKE ?"
  131. if group != "" {
  132. query = query.Where("("+likeCondition+") AND "+groupCol+" = ?",
  133. "%"+keyword+"%", "%"+keyword+"%", "%"+keyword+"%", group)
  134. } else {
  135. query = query.Where(likeCondition,
  136. "%"+keyword+"%", "%"+keyword+"%", "%"+keyword+"%")
  137. }
  138. }
  139. // 获取总数
  140. err = query.Count(&total).Error
  141. if err != nil {
  142. tx.Rollback()
  143. return nil, 0, err
  144. }
  145. // 获取分页数据
  146. err = query.Omit("password").Order("id desc").Limit(num).Offset(startIdx).Find(&users).Error
  147. if err != nil {
  148. tx.Rollback()
  149. return nil, 0, err
  150. }
  151. // 提交事务
  152. if err = tx.Commit().Error; err != nil {
  153. return nil, 0, err
  154. }
  155. return users, total, nil
  156. }
  157. func GetUserById(id int, selectAll bool) (*User, error) {
  158. if id == 0 {
  159. return nil, errors.New("id 为空!")
  160. }
  161. user := User{Id: id}
  162. var err error = nil
  163. if selectAll {
  164. err = DB.First(&user, "id = ?", id).Error
  165. } else {
  166. err = DB.Omit("password").First(&user, "id = ?", id).Error
  167. }
  168. return &user, err
  169. }
  170. func GetUserIdByAffCode(affCode string) (int, error) {
  171. if affCode == "" {
  172. return 0, errors.New("affCode 为空!")
  173. }
  174. var user User
  175. err := DB.Select("id").First(&user, "aff_code = ?", affCode).Error
  176. return user.Id, err
  177. }
  178. func DeleteUserById(id int) (err error) {
  179. if id == 0 {
  180. return errors.New("id 为空!")
  181. }
  182. user := User{Id: id}
  183. return user.Delete()
  184. }
  185. func HardDeleteUserById(id int) error {
  186. if id == 0 {
  187. return errors.New("id 为空!")
  188. }
  189. err := DB.Unscoped().Delete(&User{}, "id = ?", id).Error
  190. return err
  191. }
  192. func inviteUser(inviterId int) (err error) {
  193. user, err := GetUserById(inviterId, true)
  194. if err != nil {
  195. return err
  196. }
  197. user.AffCount++
  198. user.AffQuota += common.QuotaForInviter
  199. user.AffHistoryQuota += common.QuotaForInviter
  200. return DB.Save(user).Error
  201. }
  202. func (user *User) TransferAffQuotaToQuota(quota int) error {
  203. // 检查quota是否小于最小额度
  204. if float64(quota) < common.QuotaPerUnit {
  205. return fmt.Errorf("转移额度最小为%s!", common.LogQuota(int(common.QuotaPerUnit)))
  206. }
  207. // 开始数据库事务
  208. tx := DB.Begin()
  209. if tx.Error != nil {
  210. return tx.Error
  211. }
  212. defer tx.Rollback() // 确保在函数退出时事务能回滚
  213. // 加锁查询用户以确保数据一致性
  214. err := tx.Set("gorm:query_option", "FOR UPDATE").First(&user, user.Id).Error
  215. if err != nil {
  216. return err
  217. }
  218. // 再次检查用户的AffQuota是否足够
  219. if user.AffQuota < quota {
  220. return errors.New("邀请额度不足!")
  221. }
  222. // 更新用户额度
  223. user.AffQuota -= quota
  224. user.Quota += quota
  225. // 保存用户状态
  226. if err := tx.Save(user).Error; err != nil {
  227. return err
  228. }
  229. // 提交事务
  230. return tx.Commit().Error
  231. }
  232. func (user *User) Insert(inviterId int) error {
  233. var err error
  234. if user.Password != "" {
  235. user.Password, err = common.Password2Hash(user.Password)
  236. if err != nil {
  237. return err
  238. }
  239. }
  240. user.Quota = common.QuotaForNewUser
  241. //user.SetAccessToken(common.GetUUID())
  242. user.AffCode = common.GetRandomString(4)
  243. result := DB.Create(user)
  244. if result.Error != nil {
  245. return result.Error
  246. }
  247. if common.QuotaForNewUser > 0 {
  248. RecordLog(user.Id, LogTypeSystem, fmt.Sprintf("新用户注册赠送 %s", common.LogQuota(common.QuotaForNewUser)))
  249. }
  250. if inviterId != 0 {
  251. if common.QuotaForInvitee > 0 {
  252. _ = IncreaseUserQuota(user.Id, common.QuotaForInvitee)
  253. RecordLog(user.Id, LogTypeSystem, fmt.Sprintf("使用邀请码赠送 %s", common.LogQuota(common.QuotaForInvitee)))
  254. }
  255. if common.QuotaForInviter > 0 {
  256. //_ = IncreaseUserQuota(inviterId, common.QuotaForInviter)
  257. RecordLog(inviterId, LogTypeSystem, fmt.Sprintf("邀请用户赠送 %s", common.LogQuota(common.QuotaForInviter)))
  258. _ = inviteUser(inviterId)
  259. }
  260. }
  261. return nil
  262. }
  263. func (user *User) Update(updatePassword bool) error {
  264. var err error
  265. if updatePassword {
  266. user.Password, err = common.Password2Hash(user.Password)
  267. if err != nil {
  268. return err
  269. }
  270. }
  271. newUser := *user
  272. DB.First(&user, user.Id)
  273. if err = DB.Model(user).Updates(newUser).Error; err != nil {
  274. return err
  275. }
  276. // 更新缓存
  277. return updateUserCache(user.Id, user.Username, user.Group, user.Quota, user.Status)
  278. }
  279. func (user *User) Edit(updatePassword bool) error {
  280. var err error
  281. if updatePassword {
  282. user.Password, err = common.Password2Hash(user.Password)
  283. if err != nil {
  284. return err
  285. }
  286. }
  287. newUser := *user
  288. updates := map[string]interface{}{
  289. "username": newUser.Username,
  290. "display_name": newUser.DisplayName,
  291. "group": newUser.Group,
  292. "quota": newUser.Quota,
  293. }
  294. if updatePassword {
  295. updates["password"] = newUser.Password
  296. }
  297. DB.First(&user, user.Id)
  298. if err = DB.Model(user).Updates(updates).Error; err != nil {
  299. return err
  300. }
  301. // 更新缓存
  302. return updateUserCache(user.Id, user.Username, user.Group, user.Quota, user.Status)
  303. }
  304. func (user *User) Delete() error {
  305. if user.Id == 0 {
  306. return errors.New("id 为空!")
  307. }
  308. if err := DB.Delete(user).Error; err != nil {
  309. return err
  310. }
  311. // 清除缓存
  312. return invalidateUserCache(user.Id)
  313. }
  314. func (user *User) HardDelete() error {
  315. if user.Id == 0 {
  316. return errors.New("id 为空!")
  317. }
  318. err := DB.Unscoped().Delete(user).Error
  319. return err
  320. }
  321. // ValidateAndFill check password & user status
  322. func (user *User) ValidateAndFill() (err error) {
  323. // When querying with struct, GORM will only query with non-zero fields,
  324. // that means if your field’s value is 0, '', false or other zero values,
  325. // it won’t be used to build query conditions
  326. password := user.Password
  327. username := strings.TrimSpace(user.Username)
  328. if username == "" || password == "" {
  329. return errors.New("用户名或密码为空")
  330. }
  331. // find buy username or email
  332. DB.Where("username = ? OR email = ?", username, username).First(user)
  333. okay := common.ValidatePasswordAndHash(password, user.Password)
  334. if !okay || user.Status != common.UserStatusEnabled {
  335. return errors.New("用户名或密码错误,或用户已被封禁")
  336. }
  337. return nil
  338. }
  339. func (user *User) FillUserById() error {
  340. if user.Id == 0 {
  341. return errors.New("id 为空!")
  342. }
  343. DB.Where(User{Id: user.Id}).First(user)
  344. return nil
  345. }
  346. func (user *User) FillUserByEmail() error {
  347. if user.Email == "" {
  348. return errors.New("email 为空!")
  349. }
  350. DB.Where(User{Email: user.Email}).First(user)
  351. return nil
  352. }
  353. func (user *User) FillUserByGitHubId() error {
  354. if user.GitHubId == "" {
  355. return errors.New("GitHub id 为空!")
  356. }
  357. DB.Where(User{GitHubId: user.GitHubId}).First(user)
  358. return nil
  359. }
  360. func (user *User) FillUserByWeChatId() error {
  361. if user.WeChatId == "" {
  362. return errors.New("WeChat id 为空!")
  363. }
  364. DB.Where(User{WeChatId: user.WeChatId}).First(user)
  365. return nil
  366. }
  367. func (user *User) FillUserByTelegramId() error {
  368. if user.TelegramId == "" {
  369. return errors.New("Telegram id 为空!")
  370. }
  371. err := DB.Where(User{TelegramId: user.TelegramId}).First(user).Error
  372. if errors.Is(err, gorm.ErrRecordNotFound) {
  373. return errors.New("该 Telegram 账户未绑定")
  374. }
  375. return nil
  376. }
  377. func IsEmailAlreadyTaken(email string) bool {
  378. return DB.Unscoped().Where("email = ?", email).Find(&User{}).RowsAffected == 1
  379. }
  380. func IsWeChatIdAlreadyTaken(wechatId string) bool {
  381. return DB.Unscoped().Where("wechat_id = ?", wechatId).Find(&User{}).RowsAffected == 1
  382. }
  383. func IsGitHubIdAlreadyTaken(githubId string) bool {
  384. return DB.Unscoped().Where("github_id = ?", githubId).Find(&User{}).RowsAffected == 1
  385. }
  386. func IsTelegramIdAlreadyTaken(telegramId string) bool {
  387. return DB.Unscoped().Where("telegram_id = ?", telegramId).Find(&User{}).RowsAffected == 1
  388. }
  389. func ResetUserPasswordByEmail(email string, password string) error {
  390. if email == "" || password == "" {
  391. return errors.New("邮箱地址或密码为空!")
  392. }
  393. hashedPassword, err := common.Password2Hash(password)
  394. if err != nil {
  395. return err
  396. }
  397. err = DB.Model(&User{}).Where("email = ?", email).Update("password", hashedPassword).Error
  398. return err
  399. }
  400. func IsAdmin(userId int) bool {
  401. if userId == 0 {
  402. return false
  403. }
  404. var user User
  405. err := DB.Where("id = ?", userId).Select("role").Find(&user).Error
  406. if err != nil {
  407. common.SysError("no such user " + err.Error())
  408. return false
  409. }
  410. return user.Role >= common.RoleAdminUser
  411. }
  412. // IsUserEnabled checks user status from Redis first, falls back to DB if needed
  413. func IsUserEnabled(id int, fromDB bool) (status bool, err error) {
  414. defer func() {
  415. // Update Redis cache asynchronously on successful DB read
  416. if shouldUpdateRedis(fromDB, err) {
  417. gopool.Go(func() {
  418. if err := updateUserStatusCache(id, status); err != nil {
  419. common.SysError("failed to update user status cache: " + err.Error())
  420. }
  421. })
  422. }
  423. }()
  424. if !fromDB && common.RedisEnabled {
  425. // Try Redis first
  426. status, err := getUserStatusCache(id)
  427. if err == nil {
  428. return status == common.UserStatusEnabled, nil
  429. }
  430. // Don't return error - fall through to DB
  431. }
  432. fromDB = true
  433. var user User
  434. err = DB.Where("id = ?", id).Select("status").Find(&user).Error
  435. if err != nil {
  436. return false, err
  437. }
  438. return user.Status == common.UserStatusEnabled, nil
  439. }
  440. func ValidateAccessToken(token string) (user *User) {
  441. if token == "" {
  442. return nil
  443. }
  444. token = strings.Replace(token, "Bearer ", "", 1)
  445. user = &User{}
  446. if DB.Where("access_token = ?", token).First(user).RowsAffected == 1 {
  447. return user
  448. }
  449. return nil
  450. }
  451. // GetUserQuota gets quota from Redis first, falls back to DB if needed
  452. func GetUserQuota(id int, fromDB bool) (quota int, err error) {
  453. defer func() {
  454. // Update Redis cache asynchronously on successful DB read
  455. if shouldUpdateRedis(fromDB, err) {
  456. gopool.Go(func() {
  457. if err := updateUserQuotaCache(id, quota); err != nil {
  458. common.SysError("failed to update user quota cache: " + err.Error())
  459. }
  460. })
  461. }
  462. }()
  463. if !fromDB && common.RedisEnabled {
  464. quota, err := getUserQuotaCache(id)
  465. if err == nil {
  466. return quota, nil
  467. }
  468. // Don't return error - fall through to DB
  469. //common.SysError("failed to get user quota from cache: " + err.Error())
  470. }
  471. fromDB = true
  472. err = DB.Model(&User{}).Where("id = ?", id).Select("quota").Find(&quota).Error
  473. if err != nil {
  474. return 0, err
  475. }
  476. return quota, nil
  477. }
  478. func GetUserUsedQuota(id int) (quota int, err error) {
  479. err = DB.Model(&User{}).Where("id = ?", id).Select("used_quota").Find(&quota).Error
  480. return quota, err
  481. }
  482. func GetUserEmail(id int) (email string, err error) {
  483. err = DB.Model(&User{}).Where("id = ?", id).Select("email").Find(&email).Error
  484. return email, err
  485. }
  486. // GetUserGroup gets group from Redis first, falls back to DB if needed
  487. func GetUserGroup(id int, fromDB bool) (group string, err error) {
  488. defer func() {
  489. // Update Redis cache asynchronously on successful DB read
  490. if shouldUpdateRedis(fromDB, err) {
  491. gopool.Go(func() {
  492. if err := updateUserGroupCache(id, group); err != nil {
  493. common.SysError("failed to update user group cache: " + err.Error())
  494. }
  495. })
  496. }
  497. }()
  498. if !fromDB && common.RedisEnabled {
  499. group, err := getUserGroupCache(id)
  500. if err == nil {
  501. return group, nil
  502. }
  503. // Don't return error - fall through to DB
  504. }
  505. fromDB = true
  506. err = DB.Model(&User{}).Where("id = ?", id).Select(groupCol).Find(&group).Error
  507. if err != nil {
  508. return "", err
  509. }
  510. return group, nil
  511. }
  512. func IncreaseUserQuota(id int, quota int) (err error) {
  513. if quota < 0 {
  514. return errors.New("quota 不能为负数!")
  515. }
  516. gopool.Go(func() {
  517. err := cacheIncrUserQuota(id, int64(quota))
  518. if err != nil {
  519. common.SysError("failed to increase user quota: " + err.Error())
  520. }
  521. })
  522. if common.BatchUpdateEnabled {
  523. addNewRecord(BatchUpdateTypeUserQuota, id, quota)
  524. return nil
  525. }
  526. return increaseUserQuota(id, quota)
  527. }
  528. func increaseUserQuota(id int, quota int) (err error) {
  529. err = DB.Model(&User{}).Where("id = ?", id).Update("quota", gorm.Expr("quota + ?", quota)).Error
  530. if err != nil {
  531. return err
  532. }
  533. return err
  534. }
  535. func DecreaseUserQuota(id int, quota int) (err error) {
  536. if quota < 0 {
  537. return errors.New("quota 不能为负数!")
  538. }
  539. gopool.Go(func() {
  540. err := cacheDecrUserQuota(id, int64(quota))
  541. if err != nil {
  542. common.SysError("failed to decrease user quota: " + err.Error())
  543. }
  544. })
  545. if common.BatchUpdateEnabled {
  546. addNewRecord(BatchUpdateTypeUserQuota, id, -quota)
  547. return nil
  548. }
  549. return decreaseUserQuota(id, quota)
  550. }
  551. func decreaseUserQuota(id int, quota int) (err error) {
  552. err = DB.Model(&User{}).Where("id = ?", id).Update("quota", gorm.Expr("quota - ?", quota)).Error
  553. if err != nil {
  554. return err
  555. }
  556. return err
  557. }
  558. func DeltaUpdateUserQuota(id int, delta int) (err error) {
  559. if delta == 0 {
  560. return nil
  561. }
  562. if delta > 0 {
  563. return IncreaseUserQuota(id, delta)
  564. } else {
  565. return DecreaseUserQuota(id, -delta)
  566. }
  567. }
  568. func GetRootUserEmail() (email string) {
  569. DB.Model(&User{}).Where("role = ?", common.RoleRootUser).Select("email").Find(&email)
  570. return email
  571. }
  572. func UpdateUserUsedQuotaAndRequestCount(id int, quota int) {
  573. if common.BatchUpdateEnabled {
  574. addNewRecord(BatchUpdateTypeUsedQuota, id, quota)
  575. addNewRecord(BatchUpdateTypeRequestCount, id, 1)
  576. return
  577. }
  578. updateUserUsedQuotaAndRequestCount(id, quota, 1)
  579. }
  580. func updateUserUsedQuotaAndRequestCount(id int, quota int, count int) {
  581. err := DB.Model(&User{}).Where("id = ?", id).Updates(
  582. map[string]interface{}{
  583. "used_quota": gorm.Expr("used_quota + ?", quota),
  584. "request_count": gorm.Expr("request_count + ?", count),
  585. },
  586. ).Error
  587. if err != nil {
  588. common.SysError("failed to update user used quota and request count: " + err.Error())
  589. return
  590. }
  591. //// 更新缓存
  592. //if err := invalidateUserCache(id); err != nil {
  593. // common.SysError("failed to invalidate user cache: " + err.Error())
  594. //}
  595. }
  596. func updateUserUsedQuota(id int, quota int) {
  597. err := DB.Model(&User{}).Where("id = ?", id).Updates(
  598. map[string]interface{}{
  599. "used_quota": gorm.Expr("used_quota + ?", quota),
  600. },
  601. ).Error
  602. if err != nil {
  603. common.SysError("failed to update user used quota: " + err.Error())
  604. }
  605. }
  606. func updateUserRequestCount(id int, count int) {
  607. err := DB.Model(&User{}).Where("id = ?", id).Update("request_count", gorm.Expr("request_count + ?", count)).Error
  608. if err != nil {
  609. common.SysError("failed to update user request count: " + err.Error())
  610. }
  611. }
  612. // GetUsernameById gets username from Redis first, falls back to DB if needed
  613. func GetUsernameById(id int, fromDB bool) (username string, err error) {
  614. defer func() {
  615. // Update Redis cache asynchronously on successful DB read
  616. if shouldUpdateRedis(fromDB, err) {
  617. gopool.Go(func() {
  618. if err := updateUserNameCache(id, username); err != nil {
  619. common.SysError("failed to update user name cache: " + err.Error())
  620. }
  621. })
  622. }
  623. }()
  624. if !fromDB && common.RedisEnabled {
  625. username, err := getUserNameCache(id)
  626. if err == nil {
  627. return username, nil
  628. }
  629. // Don't return error - fall through to DB
  630. }
  631. fromDB = true
  632. err = DB.Model(&User{}).Where("id = ?", id).Select("username").Find(&username).Error
  633. if err != nil {
  634. return "", err
  635. }
  636. return username, nil
  637. }
  638. func IsLinuxDOIdAlreadyTaken(linuxDOId string) bool {
  639. var user User
  640. err := DB.Unscoped().Where("linux_do_id = ?", linuxDOId).First(&user).Error
  641. return !errors.Is(err, gorm.ErrRecordNotFound)
  642. }
  643. func (u *User) FillUserByLinuxDOId() error {
  644. if u.LinuxDOId == "" {
  645. return errors.New("linux do id is empty")
  646. }
  647. err := DB.Where("linux_do_id = ?", u.LinuxDOId).First(u).Error
  648. return err
  649. }