user.go 21 KB

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