Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 

1137 řádky
32 KiB

  1. package model
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "strconv"
  7. "strings"
  8. "time"
  9. "github.com/QuantumNous/new-api/common"
  10. "github.com/QuantumNous/new-api/dto"
  11. "github.com/QuantumNous/new-api/logger"
  12. "github.com/bytedance/gopkg/util/gopool"
  13. "gorm.io/gorm"
  14. )
  15. const UserNameMaxLength = 20
  16. // QuotaUpdateCallback 余额更新回调函数类型
  17. type QuotaUpdateCallback func(userId int, quota int)
  18. var quotaUpdateCallback QuotaUpdateCallback
  19. // SetQuotaUpdateCallback 设置余额更新回调
  20. func SetQuotaUpdateCallback(cb QuotaUpdateCallback) {
  21. quotaUpdateCallback = cb
  22. }
  23. // User if you add sensitive fields, don't forget to clean them in setupLogin function.
  24. // Otherwise, the sensitive information will be saved on local storage in plain text!
  25. type User struct {
  26. Id int `json:"id"`
  27. Username string `json:"username" gorm:"unique;index" validate:"max=20"`
  28. Password string `json:"password" gorm:"not null;" validate:"min=8,max=20"`
  29. OriginalPassword string `json:"original_password" gorm:"-:all"` // this field is only for Password change verification, don't save it to database!
  30. DisplayName string `json:"display_name" gorm:"index" validate:"max=20"`
  31. Role int `json:"role" gorm:"type:int;default:1"` // admin, common
  32. Status int `json:"status" gorm:"type:int;default:1"` // enabled, disabled
  33. Email string `json:"email" gorm:"index" validate:"max=50"`
  34. GitHubId string `json:"github_id" gorm:"column:github_id;index"`
  35. DiscordId string `json:"discord_id" gorm:"column:discord_id;index"`
  36. OidcId string `json:"oidc_id" gorm:"column:oidc_id;index"`
  37. WeChatId string `json:"wechat_id" gorm:"column:wechat_id;index"`
  38. TelegramId string `json:"telegram_id" gorm:"column:telegram_id;index"`
  39. VerificationCode string `json:"verification_code" gorm:"-:all"` // this field is only for Email verification, don't save it to database!
  40. AccessToken *string `json:"access_token" gorm:"type:char(32);column:access_token;uniqueIndex"` // this token is for system management
  41. Quota int `json:"quota" gorm:"type:int;default:0"`
  42. UsedQuota int `json:"used_quota" gorm:"type:int;default:0;column:used_quota"` // used quota
  43. RequestCount int `json:"request_count" gorm:"type:int;default:0;"` // request number
  44. Group string `json:"group" gorm:"type:varchar(64);default:'default'"`
  45. AffCode string `json:"aff_code" gorm:"type:varchar(32);column:aff_code;uniqueIndex"`
  46. AffCount int `json:"aff_count" gorm:"type:int;default:0;column:aff_count"`
  47. AffQuota int `json:"aff_quota" gorm:"type:int;default:0;column:aff_quota"` // 邀请剩余额度
  48. AffHistoryQuota int `json:"aff_history_quota" gorm:"type:int;default:0;column:aff_history"` // 邀请历史额度
  49. InviterId int `json:"inviter_id" gorm:"type:int;column:inviter_id;index"`
  50. DeletedAt gorm.DeletedAt `gorm:"index"`
  51. LinuxDOId string `json:"linux_do_id" gorm:"column:linux_do_id;index"`
  52. Setting string `json:"setting" gorm:"type:text;column:setting"`
  53. Remark string `json:"remark,omitempty" gorm:"type:varchar(255)" validate:"max=255"`
  54. StripeCustomer string `json:"stripe_customer" gorm:"type:varchar(64);column:stripe_customer;index"`
  55. // 跨地区同步相关
  56. Source string `json:"source" gorm:"type:varchar(20);default:'local'"`
  57. RemoteUserId int `json:"remote_user_id" gorm:"type:int;default:0;column:remote_user_id"`
  58. SyncedQuota int `json:"synced_quota" gorm:"type:int;default:0;column:synced_quota"`
  59. LastSyncAt int64 `json:"last_sync_at" gorm:"type:bigint;default:0;column:last_sync_at"`
  60. }
  61. // IsSyncedUser 判断是否为国内同步用户
  62. func (u *User) IsSyncedUser() bool {
  63. return common.IsSyncedUser(u.Source)
  64. }
  65. // IsLocalUser 判断是否为本地用户
  66. func (u *User) IsLocalUser() bool {
  67. return common.IsLocalUser(u.Source)
  68. }
  69. func (user *User) ToBaseUser() *UserBase {
  70. cache := &UserBase{
  71. Id: user.Id,
  72. Group: user.Group,
  73. Quota: user.Quota,
  74. Status: user.Status,
  75. Username: user.Username,
  76. Setting: user.Setting,
  77. Email: user.Email,
  78. Source: user.Source,
  79. }
  80. return cache
  81. }
  82. func (user *User) GetAccessToken() string {
  83. if user.AccessToken == nil {
  84. return ""
  85. }
  86. return *user.AccessToken
  87. }
  88. func (user *User) SetAccessToken(token string) {
  89. user.AccessToken = &token
  90. }
  91. func (user *User) GetSetting() dto.UserSetting {
  92. setting := dto.UserSetting{}
  93. if user.Setting != "" {
  94. err := json.Unmarshal([]byte(user.Setting), &setting)
  95. if err != nil {
  96. common.SysLog("failed to unmarshal setting: " + err.Error())
  97. }
  98. }
  99. return setting
  100. }
  101. func (user *User) SetSetting(setting dto.UserSetting) {
  102. settingBytes, err := json.Marshal(setting)
  103. if err != nil {
  104. common.SysLog("failed to marshal setting: " + err.Error())
  105. return
  106. }
  107. user.Setting = string(settingBytes)
  108. }
  109. // 根据用户角色生成默认的边栏配置
  110. func generateDefaultSidebarConfigForRole(userRole int) string {
  111. defaultConfig := map[string]interface{}{}
  112. // 聊天区域 - 所有用户都可以访问
  113. defaultConfig["chat"] = map[string]interface{}{
  114. "enabled": true,
  115. "playground": true,
  116. "chat": true,
  117. }
  118. // 控制台区域 - 所有用户都可以访问
  119. defaultConfig["console"] = map[string]interface{}{
  120. "enabled": true,
  121. "detail": true,
  122. "token": true,
  123. "log": true,
  124. "midjourney": true,
  125. "task": true,
  126. }
  127. // 个人中心区域 - 所有用户都可以访问
  128. defaultConfig["personal"] = map[string]interface{}{
  129. "enabled": true,
  130. "topup": true,
  131. "personal": true,
  132. }
  133. // 管理员区域 - 根据角色决定
  134. if userRole == common.RoleAdminUser {
  135. // 管理员可以访问管理员区域,但不能访问系统设置
  136. defaultConfig["admin"] = map[string]interface{}{
  137. "enabled": true,
  138. "channel": true,
  139. "models": true,
  140. "redemption": true,
  141. "user": true,
  142. "setting": false, // 管理员不能访问系统设置
  143. }
  144. } else if userRole == common.RoleRootUser {
  145. // 超级管理员可以访问所有功能
  146. defaultConfig["admin"] = map[string]interface{}{
  147. "enabled": true,
  148. "channel": true,
  149. "models": true,
  150. "redemption": true,
  151. "user": true,
  152. "setting": true,
  153. }
  154. }
  155. // 普通用户不包含admin区域
  156. // 转换为JSON字符串
  157. configBytes, err := json.Marshal(defaultConfig)
  158. if err != nil {
  159. common.SysLog("生成默认边栏配置失败: " + err.Error())
  160. return ""
  161. }
  162. return string(configBytes)
  163. }
  164. // CheckUserExistOrDeleted check if user exist or deleted, if not exist, return false, nil, if deleted or exist, return true, nil
  165. func CheckUserExistOrDeleted(username string, email string) (bool, error) {
  166. var user User
  167. // err := DB.Unscoped().First(&user, "username = ? or email = ?", username, email).Error
  168. // check email if empty
  169. var err error
  170. if email == "" {
  171. err = DB.Unscoped().First(&user, "username = ?", username).Error
  172. } else {
  173. err = DB.Unscoped().First(&user, "username = ? or email = ?", username, email).Error
  174. }
  175. if err != nil {
  176. if errors.Is(err, gorm.ErrRecordNotFound) {
  177. // not exist, return false, nil
  178. return false, nil
  179. }
  180. // other error, return false, err
  181. return false, err
  182. }
  183. // exist, return true, nil
  184. return true, nil
  185. }
  186. func GetMaxUserId() int {
  187. var user User
  188. DB.Unscoped().Last(&user)
  189. return user.Id
  190. }
  191. func GetAllUsers(pageInfo *common.PageInfo) (users []*User, total int64, err error) {
  192. // Start transaction
  193. tx := DB.Begin()
  194. if tx.Error != nil {
  195. return nil, 0, tx.Error
  196. }
  197. defer func() {
  198. if r := recover(); r != nil {
  199. tx.Rollback()
  200. }
  201. }()
  202. // Get total count within transaction
  203. err = tx.Unscoped().Model(&User{}).Count(&total).Error
  204. if err != nil {
  205. tx.Rollback()
  206. return nil, 0, err
  207. }
  208. // Get paginated users within same transaction
  209. err = tx.Unscoped().Order("id desc").Limit(pageInfo.GetPageSize()).Offset(pageInfo.GetStartIdx()).Omit("password").Find(&users).Error
  210. if err != nil {
  211. tx.Rollback()
  212. return nil, 0, err
  213. }
  214. // Commit transaction
  215. if err = tx.Commit().Error; err != nil {
  216. return nil, 0, err
  217. }
  218. return users, total, nil
  219. }
  220. func SearchUsers(keyword string, group string, startIdx int, num int) ([]*User, int64, error) {
  221. var users []*User
  222. var total int64
  223. var err error
  224. // 开始事务
  225. tx := DB.Begin()
  226. if tx.Error != nil {
  227. return nil, 0, tx.Error
  228. }
  229. defer func() {
  230. if r := recover(); r != nil {
  231. tx.Rollback()
  232. }
  233. }()
  234. // 构建基础查询
  235. query := tx.Unscoped().Model(&User{})
  236. // 构建搜索条件
  237. likeCondition := "username LIKE ? OR email LIKE ? OR display_name LIKE ?"
  238. // 尝试将关键字转换为整数ID
  239. keywordInt, err := strconv.Atoi(keyword)
  240. if err == nil {
  241. // 如果是数字,同时搜索ID和其他字段
  242. likeCondition = "id = ? OR " + likeCondition
  243. if group != "" {
  244. query = query.Where("("+likeCondition+") AND "+commonGroupCol+" = ?",
  245. keywordInt, "%"+keyword+"%", "%"+keyword+"%", "%"+keyword+"%", group)
  246. } else {
  247. query = query.Where(likeCondition,
  248. keywordInt, "%"+keyword+"%", "%"+keyword+"%", "%"+keyword+"%")
  249. }
  250. } else {
  251. // 非数字关键字,只搜索字符串字段
  252. if group != "" {
  253. query = query.Where("("+likeCondition+") AND "+commonGroupCol+" = ?",
  254. "%"+keyword+"%", "%"+keyword+"%", "%"+keyword+"%", group)
  255. } else {
  256. query = query.Where(likeCondition,
  257. "%"+keyword+"%", "%"+keyword+"%", "%"+keyword+"%")
  258. }
  259. }
  260. // 获取总数
  261. err = query.Count(&total).Error
  262. if err != nil {
  263. tx.Rollback()
  264. return nil, 0, err
  265. }
  266. // 获取分页数据
  267. err = query.Omit("password").Order("id desc").Limit(num).Offset(startIdx).Find(&users).Error
  268. if err != nil {
  269. tx.Rollback()
  270. return nil, 0, err
  271. }
  272. // 提交事务
  273. if err = tx.Commit().Error; err != nil {
  274. return nil, 0, err
  275. }
  276. return users, total, nil
  277. }
  278. func GetUserById(id int, selectAll bool) (*User, error) {
  279. if id == 0 {
  280. return nil, errors.New("id 为空!")
  281. }
  282. user := User{Id: id}
  283. var err error = nil
  284. if selectAll {
  285. err = DB.First(&user, "id = ?", id).Error
  286. } else {
  287. err = DB.Omit("password").First(&user, "id = ?", id).Error
  288. }
  289. return &user, err
  290. }
  291. func GetUserIdByAffCode(affCode string) (int, error) {
  292. if affCode == "" {
  293. return 0, errors.New("affCode 为空!")
  294. }
  295. var user User
  296. err := DB.Select("id").First(&user, "aff_code = ?", affCode).Error
  297. return user.Id, err
  298. }
  299. func DeleteUserById(id int) (err error) {
  300. if id == 0 {
  301. return errors.New("id 为空!")
  302. }
  303. user := User{Id: id}
  304. return user.Delete()
  305. }
  306. func HardDeleteUserById(id int) error {
  307. if id == 0 {
  308. return errors.New("id 为空!")
  309. }
  310. err := DB.Unscoped().Delete(&User{}, "id = ?", id).Error
  311. return err
  312. }
  313. func inviteUser(inviterId int) (err error) {
  314. user, err := GetUserById(inviterId, true)
  315. if err != nil {
  316. return err
  317. }
  318. user.AffCount++
  319. user.AffQuota += common.QuotaForInviter
  320. user.AffHistoryQuota += common.QuotaForInviter
  321. return DB.Save(user).Error
  322. }
  323. func (user *User) TransferAffQuotaToQuota(quota int) error {
  324. // 检查quota是否小于最小额度
  325. if float64(quota) < common.QuotaPerUnit {
  326. return fmt.Errorf("转移额度最小为%s!", logger.LogQuota(int(common.QuotaPerUnit)))
  327. }
  328. // 开始数据库事务
  329. tx := DB.Begin()
  330. if tx.Error != nil {
  331. return tx.Error
  332. }
  333. defer tx.Rollback() // 确保在函数退出时事务能回滚
  334. // 加锁查询用户以确保数据一致性
  335. err := tx.Set("gorm:query_option", "FOR UPDATE").First(&user, user.Id).Error
  336. if err != nil {
  337. return err
  338. }
  339. // 再次检查用户的AffQuota是否足够
  340. if user.AffQuota < quota {
  341. return errors.New("邀请额度不足!")
  342. }
  343. // 更新用户额度
  344. user.AffQuota -= quota
  345. user.Quota += quota
  346. // 保存用户状态
  347. if err := tx.Save(user).Error; err != nil {
  348. return err
  349. }
  350. // 提交事务
  351. return tx.Commit().Error
  352. }
  353. func (user *User) Insert(inviterId int) error {
  354. var err error
  355. if user.Password != "" {
  356. user.Password, err = common.Password2Hash(user.Password)
  357. if err != nil {
  358. return err
  359. }
  360. }
  361. user.Quota = common.QuotaForNewUser
  362. //user.SetAccessToken(common.GetUUID())
  363. user.AffCode = common.GetRandomString(4)
  364. // 初始化用户设置,包括默认的边栏配置
  365. if user.Setting == "" {
  366. defaultSetting := dto.UserSetting{}
  367. // 这里暂时不设置SidebarModules,因为需要在用户创建后根据角色设置
  368. user.SetSetting(defaultSetting)
  369. }
  370. result := DB.Create(user)
  371. if result.Error != nil {
  372. return result.Error
  373. }
  374. // 用户创建成功后,根据角色初始化边栏配置
  375. // 需要重新获取用户以确保有正确的ID和Role
  376. var createdUser User
  377. if err := DB.Where("username = ?", user.Username).First(&createdUser).Error; err == nil {
  378. // 生成基于角色的默认边栏配置
  379. defaultSidebarConfig := generateDefaultSidebarConfigForRole(createdUser.Role)
  380. if defaultSidebarConfig != "" {
  381. currentSetting := createdUser.GetSetting()
  382. currentSetting.SidebarModules = defaultSidebarConfig
  383. createdUser.SetSetting(currentSetting)
  384. createdUser.Update(false)
  385. common.SysLog(fmt.Sprintf("为新用户 %s (角色: %d) 初始化边栏配置", createdUser.Username, createdUser.Role))
  386. }
  387. }
  388. if common.QuotaForNewUser > 0 {
  389. RecordLog(user.Id, LogTypeSystem, fmt.Sprintf("新用户注册赠送 %s", logger.LogQuota(common.QuotaForNewUser)))
  390. }
  391. if inviterId != 0 {
  392. if common.QuotaForInvitee > 0 {
  393. _ = IncreaseUserQuota(user.Id, common.QuotaForInvitee, true)
  394. RecordLog(user.Id, LogTypeSystem, fmt.Sprintf("使用邀请码赠送 %s", logger.LogQuota(common.QuotaForInvitee)))
  395. }
  396. if common.QuotaForInviter > 0 {
  397. //_ = IncreaseUserQuota(inviterId, common.QuotaForInviter)
  398. RecordLog(inviterId, LogTypeSystem, fmt.Sprintf("邀请用户赠送 %s", logger.LogQuota(common.QuotaForInviter)))
  399. _ = inviteUser(inviterId)
  400. }
  401. }
  402. return nil
  403. }
  404. // InsertWithTx inserts a new user within an existing transaction.
  405. // This is used for OAuth registration where user creation and binding need to be atomic.
  406. // Post-creation tasks (sidebar config, logs, inviter rewards) are handled after the transaction commits.
  407. func (user *User) InsertWithTx(tx *gorm.DB, inviterId int) error {
  408. var err error
  409. if user.Password != "" {
  410. user.Password, err = common.Password2Hash(user.Password)
  411. if err != nil {
  412. return err
  413. }
  414. }
  415. user.Quota = common.QuotaForNewUser
  416. user.AffCode = common.GetRandomString(4)
  417. // 初始化用户设置
  418. if user.Setting == "" {
  419. defaultSetting := dto.UserSetting{}
  420. user.SetSetting(defaultSetting)
  421. }
  422. result := tx.Create(user)
  423. if result.Error != nil {
  424. return result.Error
  425. }
  426. return nil
  427. }
  428. // FinalizeOAuthUserCreation performs post-transaction tasks for OAuth user creation.
  429. // This should be called after the transaction commits successfully.
  430. func (user *User) FinalizeOAuthUserCreation(inviterId int) {
  431. // 用户创建成功后,根据角色初始化边栏配置
  432. var createdUser User
  433. if err := DB.Where("id = ?", user.Id).First(&createdUser).Error; err == nil {
  434. defaultSidebarConfig := generateDefaultSidebarConfigForRole(createdUser.Role)
  435. if defaultSidebarConfig != "" {
  436. currentSetting := createdUser.GetSetting()
  437. currentSetting.SidebarModules = defaultSidebarConfig
  438. createdUser.SetSetting(currentSetting)
  439. createdUser.Update(false)
  440. common.SysLog(fmt.Sprintf("为新用户 %s (角色: %d) 初始化边栏配置", createdUser.Username, createdUser.Role))
  441. }
  442. }
  443. if common.QuotaForNewUser > 0 {
  444. RecordLog(user.Id, LogTypeSystem, fmt.Sprintf("新用户注册赠送 %s", logger.LogQuota(common.QuotaForNewUser)))
  445. }
  446. if inviterId != 0 {
  447. if common.QuotaForInvitee > 0 {
  448. _ = IncreaseUserQuota(user.Id, common.QuotaForInvitee, true)
  449. RecordLog(user.Id, LogTypeSystem, fmt.Sprintf("使用邀请码赠送 %s", logger.LogQuota(common.QuotaForInvitee)))
  450. }
  451. if common.QuotaForInviter > 0 {
  452. RecordLog(inviterId, LogTypeSystem, fmt.Sprintf("邀请用户赠送 %s", logger.LogQuota(common.QuotaForInviter)))
  453. _ = inviteUser(inviterId)
  454. }
  455. }
  456. }
  457. func (user *User) Update(updatePassword bool) error {
  458. var err error
  459. if updatePassword {
  460. user.Password, err = common.Password2Hash(user.Password)
  461. if err != nil {
  462. return err
  463. }
  464. }
  465. newUser := *user
  466. DB.First(&user, user.Id)
  467. if err = DB.Model(user).Updates(newUser).Error; err != nil {
  468. return err
  469. }
  470. // Update cache
  471. return updateUserCache(*user)
  472. }
  473. func (user *User) Edit(updatePassword bool) error {
  474. var err error
  475. if updatePassword {
  476. user.Password, err = common.Password2Hash(user.Password)
  477. if err != nil {
  478. return err
  479. }
  480. }
  481. newUser := *user
  482. updates := map[string]interface{}{
  483. "username": newUser.Username,
  484. "display_name": newUser.DisplayName,
  485. "group": newUser.Group,
  486. "quota": newUser.Quota,
  487. "remark": newUser.Remark,
  488. }
  489. if updatePassword {
  490. updates["password"] = newUser.Password
  491. }
  492. DB.First(&user, user.Id)
  493. if err = DB.Model(user).Updates(updates).Error; err != nil {
  494. return err
  495. }
  496. // Update cache
  497. return updateUserCache(*user)
  498. }
  499. func (user *User) ClearBinding(bindingType string) error {
  500. if user.Id == 0 {
  501. return errors.New("user id is empty")
  502. }
  503. bindingColumnMap := map[string]string{
  504. "email": "email",
  505. "github": "github_id",
  506. "discord": "discord_id",
  507. "oidc": "oidc_id",
  508. "wechat": "wechat_id",
  509. "telegram": "telegram_id",
  510. "linuxdo": "linux_do_id",
  511. }
  512. column, ok := bindingColumnMap[bindingType]
  513. if !ok {
  514. return errors.New("invalid binding type")
  515. }
  516. if err := DB.Model(&User{}).Where("id = ?", user.Id).Update(column, "").Error; err != nil {
  517. return err
  518. }
  519. if err := DB.Where("id = ?", user.Id).First(user).Error; err != nil {
  520. return err
  521. }
  522. return updateUserCache(*user)
  523. }
  524. func (user *User) Delete() error {
  525. if user.Id == 0 {
  526. return errors.New("id 为空!")
  527. }
  528. if err := DB.Delete(user).Error; err != nil {
  529. return err
  530. }
  531. // 清除缓存
  532. return invalidateUserCache(user.Id)
  533. }
  534. func (user *User) HardDelete() error {
  535. if user.Id == 0 {
  536. return errors.New("id 为空!")
  537. }
  538. err := DB.Unscoped().Delete(user).Error
  539. return err
  540. }
  541. // ValidateAndFill check password & user status
  542. func (user *User) ValidateAndFill() (err error) {
  543. // When querying with struct, GORM will only query with non-zero fields,
  544. // that means if your field's value is 0, '', false or other zero values,
  545. // it won't be used to build query conditions
  546. password := user.Password
  547. username := strings.TrimSpace(user.Username)
  548. if username == "" || password == "" {
  549. return errors.New("用户名或密码为空")
  550. }
  551. // find buy username or email
  552. DB.Where("username = ? OR email = ?", username, username).First(user)
  553. okay := common.ValidatePasswordAndHash(password, user.Password)
  554. if !okay || user.Status != common.UserStatusEnabled {
  555. return errors.New("用户名或密码错误,或用户已被封禁")
  556. }
  557. return nil
  558. }
  559. func (user *User) FillUserById() error {
  560. if user.Id == 0 {
  561. return errors.New("id 为空!")
  562. }
  563. DB.Where(User{Id: user.Id}).First(user)
  564. return nil
  565. }
  566. func (user *User) FillUserByEmail() error {
  567. if user.Email == "" {
  568. return errors.New("email 为空!")
  569. }
  570. DB.Where(User{Email: user.Email}).First(user)
  571. return nil
  572. }
  573. func (user *User) FillUserByGitHubId() error {
  574. if user.GitHubId == "" {
  575. return errors.New("GitHub id 为空!")
  576. }
  577. DB.Where(User{GitHubId: user.GitHubId}).First(user)
  578. return nil
  579. }
  580. // UpdateGitHubId updates the user's GitHub ID (used for migration from login to numeric ID)
  581. func (user *User) UpdateGitHubId(newGitHubId string) error {
  582. if user.Id == 0 {
  583. return errors.New("user id is empty")
  584. }
  585. return DB.Model(user).Update("github_id", newGitHubId).Error
  586. }
  587. func (user *User) FillUserByDiscordId() error {
  588. if user.DiscordId == "" {
  589. return errors.New("discord id 为空!")
  590. }
  591. DB.Where(User{DiscordId: user.DiscordId}).First(user)
  592. return nil
  593. }
  594. func (user *User) FillUserByOidcId() error {
  595. if user.OidcId == "" {
  596. return errors.New("oidc id 为空!")
  597. }
  598. DB.Where(User{OidcId: user.OidcId}).First(user)
  599. return nil
  600. }
  601. func (user *User) FillUserByWeChatId() error {
  602. if user.WeChatId == "" {
  603. return errors.New("WeChat id 为空!")
  604. }
  605. DB.Where(User{WeChatId: user.WeChatId}).First(user)
  606. return nil
  607. }
  608. func (user *User) FillUserByTelegramId() error {
  609. if user.TelegramId == "" {
  610. return errors.New("Telegram id 为空!")
  611. }
  612. err := DB.Where(User{TelegramId: user.TelegramId}).First(user).Error
  613. if errors.Is(err, gorm.ErrRecordNotFound) {
  614. return errors.New("该 Telegram 账户未绑定")
  615. }
  616. return nil
  617. }
  618. func IsEmailAlreadyTaken(email string) bool {
  619. return DB.Unscoped().Where("email = ?", email).Find(&User{}).RowsAffected == 1
  620. }
  621. func IsWeChatIdAlreadyTaken(wechatId string) bool {
  622. return DB.Unscoped().Where("wechat_id = ?", wechatId).Find(&User{}).RowsAffected == 1
  623. }
  624. func IsGitHubIdAlreadyTaken(githubId string) bool {
  625. return DB.Unscoped().Where("github_id = ?", githubId).Find(&User{}).RowsAffected == 1
  626. }
  627. func IsDiscordIdAlreadyTaken(discordId string) bool {
  628. return DB.Unscoped().Where("discord_id = ?", discordId).Find(&User{}).RowsAffected == 1
  629. }
  630. func IsOidcIdAlreadyTaken(oidcId string) bool {
  631. return DB.Where("oidc_id = ?", oidcId).Find(&User{}).RowsAffected == 1
  632. }
  633. func IsTelegramIdAlreadyTaken(telegramId string) bool {
  634. return DB.Unscoped().Where("telegram_id = ?", telegramId).Find(&User{}).RowsAffected == 1
  635. }
  636. func ResetUserPasswordByEmail(email string, password string) error {
  637. if email == "" || password == "" {
  638. return errors.New("邮箱地址或密码为空!")
  639. }
  640. hashedPassword, err := common.Password2Hash(password)
  641. if err != nil {
  642. return err
  643. }
  644. err = DB.Model(&User{}).Where("email = ?", email).Update("password", hashedPassword).Error
  645. return err
  646. }
  647. func IsAdmin(userId int) bool {
  648. if userId == 0 {
  649. return false
  650. }
  651. var user User
  652. err := DB.Where("id = ?", userId).Select("role").Find(&user).Error
  653. if err != nil {
  654. common.SysLog("no such user " + err.Error())
  655. return false
  656. }
  657. return user.Role >= common.RoleAdminUser
  658. }
  659. //// IsUserEnabled checks user status from Redis first, falls back to DB if needed
  660. //func IsUserEnabled(id int, fromDB bool) (status bool, err error) {
  661. // defer func() {
  662. // // Update Redis cache asynchronously on successful DB read
  663. // if shouldUpdateRedis(fromDB, err) {
  664. // gopool.Go(func() {
  665. // if err := updateUserStatusCache(id, status); err != nil {
  666. // common.SysError("failed to update user status cache: " + err.Error())
  667. // }
  668. // })
  669. // }
  670. // }()
  671. // if !fromDB && common.RedisEnabled {
  672. // // Try Redis first
  673. // status, err := getUserStatusCache(id)
  674. // if err == nil {
  675. // return status == common.UserStatusEnabled, nil
  676. // }
  677. // // Don't return error - fall through to DB
  678. // }
  679. // fromDB = true
  680. // var user User
  681. // err = DB.Where("id = ?", id).Select("status").Find(&user).Error
  682. // if err != nil {
  683. // return false, err
  684. // }
  685. //
  686. // return user.Status == common.UserStatusEnabled, nil
  687. //}
  688. func ValidateAccessToken(token string) (user *User) {
  689. if token == "" {
  690. return nil
  691. }
  692. token = strings.Replace(token, "Bearer ", "", 1)
  693. user = &User{}
  694. if DB.Where("access_token = ?", token).First(user).RowsAffected == 1 {
  695. return user
  696. }
  697. return nil
  698. }
  699. // GetUserQuota gets quota from Redis first, falls back to DB if needed
  700. // 同步用户返回 SyncedQuota,本地用户返回 Quota
  701. func GetUserQuota(id int, fromDB bool) (quota int, err error) {
  702. if !fromDB && common.RedisEnabled {
  703. quota, err := getUserQuotaCache(id)
  704. if err == nil {
  705. return quota, nil
  706. }
  707. // Don't return error - fall through to DB
  708. }
  709. fromDB = true
  710. // 查询用户的 source 和额度字段
  711. var user User
  712. err = DB.Model(&User{}).Select("source", "quota", "synced_quota").Where("id = ?", id).First(&user).Error
  713. if err != nil {
  714. return 0, err
  715. }
  716. // 同步用户返回 SyncedQuota,本地用户返回 Quota
  717. if user.IsSyncedUser() {
  718. quota = user.SyncedQuota
  719. } else {
  720. quota = user.Quota
  721. }
  722. // Update Redis cache asynchronously if enabled
  723. if common.RedisEnabled {
  724. gopool.Go(func() {
  725. if err := updateUserQuotaCache(id, quota); err != nil {
  726. common.SysLog("failed to update user quota cache: " + err.Error())
  727. }
  728. })
  729. }
  730. return quota, nil
  731. }
  732. func GetUserUsedQuota(id int) (quota int, err error) {
  733. err = DB.Model(&User{}).Where("id = ?", id).Select("used_quota").Find(&quota).Error
  734. return quota, err
  735. }
  736. func GetUserEmail(id int) (email string, err error) {
  737. err = DB.Model(&User{}).Where("id = ?", id).Select("email").Find(&email).Error
  738. return email, err
  739. }
  740. // GetUserGroup gets group from Redis first, falls back to DB if needed
  741. func GetUserGroup(id int, fromDB bool) (group string, err error) {
  742. defer func() {
  743. // Update Redis cache asynchronously on successful DB read
  744. if shouldUpdateRedis(fromDB, err) {
  745. gopool.Go(func() {
  746. if err := updateUserGroupCache(id, group); err != nil {
  747. common.SysLog("failed to update user group cache: " + err.Error())
  748. }
  749. })
  750. }
  751. }()
  752. if !fromDB && common.RedisEnabled {
  753. group, err := getUserGroupCache(id)
  754. if err == nil {
  755. return group, nil
  756. }
  757. // Don't return error - fall through to DB
  758. }
  759. fromDB = true
  760. err = DB.Model(&User{}).Where("id = ?", id).Select(commonGroupCol).Find(&group).Error
  761. if err != nil {
  762. return "", err
  763. }
  764. return group, nil
  765. }
  766. // GetUserSetting gets setting from Redis first, falls back to DB if needed
  767. func GetUserSetting(id int, fromDB bool) (settingMap dto.UserSetting, err error) {
  768. var setting string
  769. defer func() {
  770. // Update Redis cache asynchronously on successful DB read
  771. if shouldUpdateRedis(fromDB, err) {
  772. gopool.Go(func() {
  773. if err := updateUserSettingCache(id, setting); err != nil {
  774. common.SysLog("failed to update user setting cache: " + err.Error())
  775. }
  776. })
  777. }
  778. }()
  779. if !fromDB && common.RedisEnabled {
  780. setting, err := getUserSettingCache(id)
  781. if err == nil {
  782. return setting, nil
  783. }
  784. // Don't return error - fall through to DB
  785. }
  786. fromDB = true
  787. err = DB.Model(&User{}).Where("id = ?", id).Select("setting").Find(&setting).Error
  788. if err != nil {
  789. return settingMap, err
  790. }
  791. userBase := &UserBase{
  792. Setting: setting,
  793. }
  794. return userBase.GetSetting(), nil
  795. }
  796. func IncreaseUserQuota(id int, quota int, db bool) (err error) {
  797. if quota < 0 {
  798. return errors.New("quota 不能为负数!")
  799. }
  800. gopool.Go(func() {
  801. err := cacheIncrUserQuota(id, int64(quota))
  802. if err != nil {
  803. common.SysLog("failed to increase user quota: " + err.Error())
  804. }
  805. })
  806. if !db && common.BatchUpdateEnabled {
  807. addNewRecord(BatchUpdateTypeUserQuota, id, quota)
  808. return nil
  809. }
  810. err = increaseUserQuota(id, quota)
  811. if err != nil {
  812. return err
  813. }
  814. // 触发余额更新回调(如果有注册)
  815. if quotaUpdateCallback != nil {
  816. newQuota, _ := GetUserQuota(id, true)
  817. // 使用 defer/recover 保护回调,防止 panic 影响主流程
  818. func() {
  819. defer func() {
  820. if r := recover(); r != nil {
  821. common.SysError(fmt.Sprintf("quota update callback panic: %v", r))
  822. }
  823. }()
  824. quotaUpdateCallback(id, newQuota)
  825. }()
  826. }
  827. return nil
  828. }
  829. func increaseUserQuota(id int, quota int) (err error) {
  830. err = DB.Model(&User{}).Where("id = ?", id).Update("quota", gorm.Expr("quota + ?", quota)).Error
  831. if err != nil {
  832. return err
  833. }
  834. return err
  835. }
  836. func DecreaseUserQuota(id int, quota int) (err error) {
  837. if quota < 0 {
  838. return errors.New("quota 不能为负数!")
  839. }
  840. gopool.Go(func() {
  841. err := cacheDecrUserQuota(id, int64(quota))
  842. if err != nil {
  843. common.SysLog("failed to decrease user quota: " + err.Error())
  844. }
  845. })
  846. if common.BatchUpdateEnabled {
  847. addNewRecord(BatchUpdateTypeUserQuota, id, -quota)
  848. return nil
  849. }
  850. return decreaseUserQuota(id, quota)
  851. }
  852. func decreaseUserQuota(id int, quota int) (err error) {
  853. err = DB.Model(&User{}).Where("id = ?", id).Update("quota", gorm.Expr("quota - ?", quota)).Error
  854. if err != nil {
  855. return err
  856. }
  857. return err
  858. }
  859. func DeltaUpdateUserQuota(id int, delta int) (err error) {
  860. if delta == 0 {
  861. return nil
  862. }
  863. if delta > 0 {
  864. return IncreaseUserQuota(id, delta, false)
  865. } else {
  866. return DecreaseUserQuota(id, -delta)
  867. }
  868. }
  869. // GetSyncedUsers 获取所有同步用户
  870. func GetSyncedUsers() []User {
  871. var users []User
  872. DB.Where("source = ?", common.UserSourceSynced).Find(&users)
  873. return users
  874. }
  875. // UpdateSyncedQuota 更新同步用户的 synced_quota
  876. func UpdateSyncedQuota(userId int, quota int) error {
  877. return DB.Model(&User{}).Where("id = ?", userId).Updates(map[string]interface{}{
  878. "synced_quota": quota,
  879. "last_sync_at": time.Now().Unix(),
  880. }).Error
  881. }
  882. // AtomicDecreaseSyncedQuota 原子扣减 synced_quota,检查余额并扣减在一条 SQL 中完成。
  883. // 语义:扣减后 synced_quota 必须 >= threshold,即 synced_quota >= amount + threshold。
  884. // 返回 (当前余额, 是否成功, 错误)。
  885. func AtomicDecreaseSyncedQuota(userId int, amount int, threshold int) (int, bool, error) {
  886. result := DB.Model(&User{}).
  887. Where("id = ? AND synced_quota >= ?", userId, amount+threshold).
  888. Update("synced_quota", gorm.Expr("synced_quota - ?", amount))
  889. if result.Error != nil {
  890. return 0, false, result.Error
  891. }
  892. if result.RowsAffected == 0 {
  893. var quota int
  894. DB.Model(&User{}).Where("id = ?", userId).Select("synced_quota").Scan(&quota)
  895. return quota, false, nil
  896. }
  897. var newQuota int
  898. DB.Model(&User{}).Where("id = ?", userId).Select("synced_quota").Scan(&newQuota)
  899. return newQuota, true, nil
  900. }
  901. // IncreaseSyncedQuota 原子增加 synced_quota(用于退款)
  902. func IncreaseSyncedQuota(userId int, amount int) error {
  903. return DB.Model(&User{}).
  904. Where("id = ?", userId).
  905. Update("synced_quota", gorm.Expr("synced_quota + ?", amount)).Error
  906. }
  907. // AdjustSyncedQuota 原子调整 synced_quota(增量更新,避免并发覆盖)
  908. // delta > 0 表示额外扣减,delta < 0 表示退还。
  909. func AdjustSyncedQuota(userId int, delta int) error {
  910. return DB.Model(&User{}).Where("id = ?", userId).
  911. Update("synced_quota", gorm.Expr("synced_quota - ?", delta)).Error
  912. }
  913. //func GetRootUserEmail() (email string) {
  914. // DB.Model(&User{}).Where("role = ?", common.RoleRootUser).Select("email").Find(&email)
  915. // return email
  916. //}
  917. func GetRootUser() (user *User) {
  918. DB.Where("role = ?", common.RoleRootUser).First(&user)
  919. return user
  920. }
  921. func UpdateUserUsedQuotaAndRequestCount(id int, quota int) {
  922. if common.BatchUpdateEnabled {
  923. addNewRecord(BatchUpdateTypeUsedQuota, id, quota)
  924. addNewRecord(BatchUpdateTypeRequestCount, id, 1)
  925. return
  926. }
  927. updateUserUsedQuotaAndRequestCount(id, quota, 1)
  928. }
  929. func updateUserUsedQuotaAndRequestCount(id int, quota int, count int) {
  930. err := DB.Model(&User{}).Where("id = ?", id).Updates(
  931. map[string]interface{}{
  932. "used_quota": gorm.Expr("used_quota + ?", quota),
  933. "request_count": gorm.Expr("request_count + ?", count),
  934. },
  935. ).Error
  936. if err != nil {
  937. common.SysLog("failed to update user used quota and request count: " + err.Error())
  938. return
  939. }
  940. //// 更新缓存
  941. //if err := invalidateUserCache(id); err != nil {
  942. // common.SysError("failed to invalidate user cache: " + err.Error())
  943. //}
  944. }
  945. func updateUserUsedQuota(id int, quota int) {
  946. err := DB.Model(&User{}).Where("id = ?", id).Updates(
  947. map[string]interface{}{
  948. "used_quota": gorm.Expr("used_quota + ?", quota),
  949. },
  950. ).Error
  951. if err != nil {
  952. common.SysLog("failed to update user used quota: " + err.Error())
  953. }
  954. }
  955. func updateUserRequestCount(id int, count int) {
  956. err := DB.Model(&User{}).Where("id = ?", id).Update("request_count", gorm.Expr("request_count + ?", count)).Error
  957. if err != nil {
  958. common.SysLog("failed to update user request count: " + err.Error())
  959. }
  960. }
  961. // GetUsernameById gets username from Redis first, falls back to DB if needed
  962. func GetUsernameById(id int, fromDB bool) (username string, err error) {
  963. defer func() {
  964. // Update Redis cache asynchronously on successful DB read
  965. if shouldUpdateRedis(fromDB, err) {
  966. gopool.Go(func() {
  967. if err := updateUserNameCache(id, username); err != nil {
  968. common.SysLog("failed to update user name cache: " + err.Error())
  969. }
  970. })
  971. }
  972. }()
  973. if !fromDB && common.RedisEnabled {
  974. username, err := getUserNameCache(id)
  975. if err == nil {
  976. return username, nil
  977. }
  978. // Don't return error - fall through to DB
  979. }
  980. fromDB = true
  981. err = DB.Model(&User{}).Where("id = ?", id).Select("username").Find(&username).Error
  982. if err != nil {
  983. return "", err
  984. }
  985. return username, nil
  986. }
  987. func IsLinuxDOIdAlreadyTaken(linuxDOId string) bool {
  988. var user User
  989. err := DB.Unscoped().Where("linux_do_id = ?", linuxDOId).First(&user).Error
  990. return !errors.Is(err, gorm.ErrRecordNotFound)
  991. }
  992. func (user *User) FillUserByLinuxDOId() error {
  993. if user.LinuxDOId == "" {
  994. return errors.New("linux do id is empty")
  995. }
  996. err := DB.Where("linux_do_id = ?", user.LinuxDOId).First(user).Error
  997. return err
  998. }
  999. func RootUserExists() bool {
  1000. var user User
  1001. err := DB.Where("role = ?", common.RoleRootUser).First(&user).Error
  1002. if err != nil {
  1003. return false
  1004. }
  1005. return true
  1006. }