user.go 22 KB

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