user.go 22 KB

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