user.go 19 KB

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