You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

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