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)
  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. return user.Status == common.UserStatusEnabled, nil
  471. }
  472. func ValidateAccessToken(token string) (user *User) {
  473. if token == "" {
  474. return nil
  475. }
  476. token = strings.Replace(token, "Bearer ", "", 1)
  477. user = &User{}
  478. if DB.Where("access_token = ?", token).First(user).RowsAffected == 1 {
  479. return user
  480. }
  481. return nil
  482. }
  483. // GetUserQuota gets quota from Redis first, falls back to DB if needed
  484. func GetUserQuota(id int, fromDB bool) (quota int, err error) {
  485. defer func() {
  486. // Update Redis cache asynchronously on successful DB read
  487. if shouldUpdateRedis(fromDB, err) {
  488. gopool.Go(func() {
  489. if err := updateUserQuotaCache(id, quota); err != nil {
  490. common.SysError("failed to update user quota cache: " + err.Error())
  491. }
  492. })
  493. }
  494. }()
  495. if !fromDB && common.RedisEnabled {
  496. quota, err := getUserQuotaCache(id)
  497. if err == nil {
  498. return quota, nil
  499. }
  500. // Don't return error - fall through to DB
  501. }
  502. fromDB = true
  503. err = DB.Model(&User{}).Where("id = ?", id).Select("quota").Find(&quota).Error
  504. if err != nil {
  505. return 0, err
  506. }
  507. return quota, nil
  508. }
  509. func GetUserUsedQuota(id int) (quota int, err error) {
  510. err = DB.Model(&User{}).Where("id = ?", id).Select("used_quota").Find(&quota).Error
  511. return quota, err
  512. }
  513. func GetUserEmail(id int) (email string, err error) {
  514. err = DB.Model(&User{}).Where("id = ?", id).Select("email").Find(&email).Error
  515. return email, err
  516. }
  517. // GetUserGroup gets group from Redis first, falls back to DB if needed
  518. func GetUserGroup(id int, fromDB bool) (group string, err error) {
  519. defer func() {
  520. // Update Redis cache asynchronously on successful DB read
  521. if shouldUpdateRedis(fromDB, err) {
  522. gopool.Go(func() {
  523. if err := updateUserGroupCache(id, group); err != nil {
  524. common.SysError("failed to update user group cache: " + err.Error())
  525. }
  526. })
  527. }
  528. }()
  529. if !fromDB && common.RedisEnabled {
  530. group, err := getUserGroupCache(id)
  531. if err == nil {
  532. return group, nil
  533. }
  534. // Don't return error - fall through to DB
  535. }
  536. fromDB = true
  537. err = DB.Model(&User{}).Where("id = ?", id).Select(groupCol).Find(&group).Error
  538. if err != nil {
  539. return "", err
  540. }
  541. return group, nil
  542. }
  543. // GetUserSetting gets setting from Redis first, falls back to DB if needed
  544. func GetUserSetting(id int, fromDB bool) (settingMap map[string]interface{}, err error) {
  545. var setting string
  546. defer func() {
  547. // Update Redis cache asynchronously on successful DB read
  548. if shouldUpdateRedis(fromDB, err) {
  549. gopool.Go(func() {
  550. if err := updateUserSettingCache(id, setting); err != nil {
  551. common.SysError("failed to update user setting cache: " + err.Error())
  552. }
  553. })
  554. }
  555. }()
  556. if !fromDB && common.RedisEnabled {
  557. setting, err := getUserSettingCache(id)
  558. if err == nil {
  559. return setting, nil
  560. }
  561. // Don't return error - fall through to DB
  562. }
  563. fromDB = true
  564. err = DB.Model(&User{}).Where("id = ?", id).Select("setting").Find(&setting).Error
  565. if err != nil {
  566. return map[string]interface{}{}, err
  567. }
  568. return common.StrToMap(setting), nil
  569. }
  570. func IncreaseUserQuota(id int, quota int) (err error) {
  571. if quota < 0 {
  572. return errors.New("quota 不能为负数!")
  573. }
  574. gopool.Go(func() {
  575. err := cacheIncrUserQuota(id, int64(quota))
  576. if err != nil {
  577. common.SysError("failed to increase user quota: " + err.Error())
  578. }
  579. })
  580. if common.BatchUpdateEnabled {
  581. addNewRecord(BatchUpdateTypeUserQuota, id, quota)
  582. return nil
  583. }
  584. return increaseUserQuota(id, quota)
  585. }
  586. func increaseUserQuota(id int, quota int) (err error) {
  587. err = DB.Model(&User{}).Where("id = ?", id).Update("quota", gorm.Expr("quota + ?", quota)).Error
  588. if err != nil {
  589. return err
  590. }
  591. return err
  592. }
  593. func DecreaseUserQuota(id int, quota int) (err error) {
  594. if quota < 0 {
  595. return errors.New("quota 不能为负数!")
  596. }
  597. gopool.Go(func() {
  598. err := cacheDecrUserQuota(id, int64(quota))
  599. if err != nil {
  600. common.SysError("failed to decrease user quota: " + err.Error())
  601. }
  602. })
  603. if common.BatchUpdateEnabled {
  604. addNewRecord(BatchUpdateTypeUserQuota, id, -quota)
  605. return nil
  606. }
  607. return decreaseUserQuota(id, quota)
  608. }
  609. func decreaseUserQuota(id int, quota int) (err error) {
  610. err = DB.Model(&User{}).Where("id = ?", id).Update("quota", gorm.Expr("quota - ?", quota)).Error
  611. if err != nil {
  612. return err
  613. }
  614. return err
  615. }
  616. func DeltaUpdateUserQuota(id int, delta int) (err error) {
  617. if delta == 0 {
  618. return nil
  619. }
  620. if delta > 0 {
  621. return IncreaseUserQuota(id, delta)
  622. } else {
  623. return DecreaseUserQuota(id, -delta)
  624. }
  625. }
  626. //func GetRootUserEmail() (email string) {
  627. // DB.Model(&User{}).Where("role = ?", common.RoleRootUser).Select("email").Find(&email)
  628. // return email
  629. //}
  630. func GetRootUser() (user *User) {
  631. DB.Where("role = ?", common.RoleRootUser).First(&user)
  632. return user
  633. }
  634. func UpdateUserUsedQuotaAndRequestCount(id int, quota int) {
  635. if common.BatchUpdateEnabled {
  636. addNewRecord(BatchUpdateTypeUsedQuota, id, quota)
  637. addNewRecord(BatchUpdateTypeRequestCount, id, 1)
  638. return
  639. }
  640. updateUserUsedQuotaAndRequestCount(id, quota, 1)
  641. }
  642. func updateUserUsedQuotaAndRequestCount(id int, quota int, count int) {
  643. err := DB.Model(&User{}).Where("id = ?", id).Updates(
  644. map[string]interface{}{
  645. "used_quota": gorm.Expr("used_quota + ?", quota),
  646. "request_count": gorm.Expr("request_count + ?", count),
  647. },
  648. ).Error
  649. if err != nil {
  650. common.SysError("failed to update user used quota and request count: " + err.Error())
  651. return
  652. }
  653. //// 更新缓存
  654. //if err := invalidateUserCache(id); err != nil {
  655. // common.SysError("failed to invalidate user cache: " + err.Error())
  656. //}
  657. }
  658. func updateUserUsedQuota(id int, quota int) {
  659. err := DB.Model(&User{}).Where("id = ?", id).Updates(
  660. map[string]interface{}{
  661. "used_quota": gorm.Expr("used_quota + ?", quota),
  662. },
  663. ).Error
  664. if err != nil {
  665. common.SysError("failed to update user used quota: " + err.Error())
  666. }
  667. }
  668. func updateUserRequestCount(id int, count int) {
  669. err := DB.Model(&User{}).Where("id = ?", id).Update("request_count", gorm.Expr("request_count + ?", count)).Error
  670. if err != nil {
  671. common.SysError("failed to update user request count: " + err.Error())
  672. }
  673. }
  674. // GetUsernameById gets username from Redis first, falls back to DB if needed
  675. func GetUsernameById(id int, fromDB bool) (username string, err error) {
  676. defer func() {
  677. // Update Redis cache asynchronously on successful DB read
  678. if shouldUpdateRedis(fromDB, err) {
  679. gopool.Go(func() {
  680. if err := updateUserNameCache(id, username); err != nil {
  681. common.SysError("failed to update user name cache: " + err.Error())
  682. }
  683. })
  684. }
  685. }()
  686. if !fromDB && common.RedisEnabled {
  687. username, err := getUserNameCache(id)
  688. if err == nil {
  689. return username, nil
  690. }
  691. // Don't return error - fall through to DB
  692. }
  693. fromDB = true
  694. err = DB.Model(&User{}).Where("id = ?", id).Select("username").Find(&username).Error
  695. if err != nil {
  696. return "", err
  697. }
  698. return username, nil
  699. }
  700. func IsLinuxDOIdAlreadyTaken(linuxDOId string) bool {
  701. var user User
  702. err := DB.Unscoped().Where("linux_do_id = ?", linuxDOId).First(&user).Error
  703. return !errors.Is(err, gorm.ErrRecordNotFound)
  704. }
  705. func (user *User) FillUserByLinuxDOId() error {
  706. if user.LinuxDOId == "" {
  707. return errors.New("linux do id is empty")
  708. }
  709. err := DB.Where("linux_do_id = ?", user.LinuxDOId).First(user).Error
  710. return err
  711. }