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.
 
 
 

1155 rivejä
33 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. matchedQuota := MatchEmailQuotaRule(user.Email)
  362. if matchedQuota >= 0 {
  363. user.Quota = int(matchedQuota)
  364. } else {
  365. user.Quota = common.QuotaForNewUser
  366. }
  367. //user.SetAccessToken(common.GetUUID())
  368. user.AffCode = common.GetRandomString(4)
  369. // 初始化用户设置,包括默认的边栏配置
  370. if user.Setting == "" {
  371. defaultSetting := dto.UserSetting{}
  372. // 这里暂时不设置SidebarModules,因为需要在用户创建后根据角色设置
  373. user.SetSetting(defaultSetting)
  374. }
  375. result := DB.Create(user)
  376. if result.Error != nil {
  377. return result.Error
  378. }
  379. // 用户创建成功后,根据角色初始化边栏配置
  380. // 需要重新获取用户以确保有正确的ID和Role
  381. var createdUser User
  382. if err := DB.Where("username = ?", user.Username).First(&createdUser).Error; err == nil {
  383. // 生成基于角色的默认边栏配置
  384. defaultSidebarConfig := generateDefaultSidebarConfigForRole(createdUser.Role)
  385. if defaultSidebarConfig != "" {
  386. currentSetting := createdUser.GetSetting()
  387. currentSetting.SidebarModules = defaultSidebarConfig
  388. createdUser.SetSetting(currentSetting)
  389. createdUser.Update(false)
  390. common.SysLog(fmt.Sprintf("为新用户 %s (角色: %d) 初始化边栏配置", createdUser.Username, createdUser.Role))
  391. }
  392. }
  393. if user.Quota > 0 {
  394. if MatchEmailQuotaRule(user.Email) >= 0 {
  395. RecordLog(user.Id, LogTypeSystem, fmt.Sprintf("新用户注册赠送 %s(邮箱后缀规则匹配)", logger.LogQuota(user.Quota)))
  396. } else {
  397. RecordLog(user.Id, LogTypeSystem, fmt.Sprintf("新用户注册赠送 %s", logger.LogQuota(user.Quota)))
  398. }
  399. }
  400. if inviterId != 0 {
  401. if common.QuotaForInvitee > 0 {
  402. _ = IncreaseUserQuota(user.Id, common.QuotaForInvitee, true)
  403. RecordLog(user.Id, LogTypeSystem, fmt.Sprintf("使用邀请码赠送 %s", logger.LogQuota(common.QuotaForInvitee)))
  404. }
  405. if common.QuotaForInviter > 0 {
  406. //_ = IncreaseUserQuota(inviterId, common.QuotaForInviter)
  407. RecordLog(inviterId, LogTypeSystem, fmt.Sprintf("邀请用户赠送 %s", logger.LogQuota(common.QuotaForInviter)))
  408. _ = inviteUser(inviterId)
  409. }
  410. }
  411. return nil
  412. }
  413. // InsertWithTx inserts a new user within an existing transaction.
  414. // This is used for OAuth registration where user creation and binding need to be atomic.
  415. // Post-creation tasks (sidebar config, logs, inviter rewards) are handled after the transaction commits.
  416. func (user *User) InsertWithTx(tx *gorm.DB, inviterId int) error {
  417. var err error
  418. if user.Password != "" {
  419. user.Password, err = common.Password2Hash(user.Password)
  420. if err != nil {
  421. return err
  422. }
  423. }
  424. matchedQuota := MatchEmailQuotaRule(user.Email)
  425. if matchedQuota >= 0 {
  426. user.Quota = int(matchedQuota)
  427. } else {
  428. user.Quota = common.QuotaForNewUser
  429. }
  430. user.AffCode = common.GetRandomString(4)
  431. // 初始化用户设置
  432. if user.Setting == "" {
  433. defaultSetting := dto.UserSetting{}
  434. user.SetSetting(defaultSetting)
  435. }
  436. result := tx.Create(user)
  437. if result.Error != nil {
  438. return result.Error
  439. }
  440. return nil
  441. }
  442. // FinalizeOAuthUserCreation performs post-transaction tasks for OAuth user creation.
  443. // This should be called after the transaction commits successfully.
  444. func (user *User) FinalizeOAuthUserCreation(inviterId int) {
  445. // 用户创建成功后,根据角色初始化边栏配置
  446. var createdUser User
  447. if err := DB.Where("id = ?", user.Id).First(&createdUser).Error; err == nil {
  448. defaultSidebarConfig := generateDefaultSidebarConfigForRole(createdUser.Role)
  449. if defaultSidebarConfig != "" {
  450. currentSetting := createdUser.GetSetting()
  451. currentSetting.SidebarModules = defaultSidebarConfig
  452. createdUser.SetSetting(currentSetting)
  453. createdUser.Update(false)
  454. common.SysLog(fmt.Sprintf("为新用户 %s (角色: %d) 初始化边栏配置", createdUser.Username, createdUser.Role))
  455. }
  456. }
  457. if user.Quota > 0 {
  458. if matchedQuota := MatchEmailQuotaRule(user.Email); matchedQuota >= 0 {
  459. RecordLog(user.Id, LogTypeSystem, fmt.Sprintf("新用户注册赠送 %s(邮箱后缀规则匹配)", logger.LogQuota(user.Quota)))
  460. } else {
  461. RecordLog(user.Id, LogTypeSystem, fmt.Sprintf("新用户注册赠送 %s", logger.LogQuota(user.Quota)))
  462. }
  463. }
  464. if inviterId != 0 {
  465. if common.QuotaForInvitee > 0 {
  466. _ = IncreaseUserQuota(user.Id, common.QuotaForInvitee, true)
  467. RecordLog(user.Id, LogTypeSystem, fmt.Sprintf("使用邀请码赠送 %s", logger.LogQuota(common.QuotaForInvitee)))
  468. }
  469. if common.QuotaForInviter > 0 {
  470. RecordLog(inviterId, LogTypeSystem, fmt.Sprintf("邀请用户赠送 %s", logger.LogQuota(common.QuotaForInviter)))
  471. _ = inviteUser(inviterId)
  472. }
  473. }
  474. }
  475. func (user *User) Update(updatePassword bool) error {
  476. var err error
  477. if updatePassword {
  478. user.Password, err = common.Password2Hash(user.Password)
  479. if err != nil {
  480. return err
  481. }
  482. }
  483. newUser := *user
  484. DB.First(&user, user.Id)
  485. if err = DB.Model(user).Updates(newUser).Error; err != nil {
  486. return err
  487. }
  488. // Update cache
  489. return updateUserCache(*user)
  490. }
  491. func (user *User) Edit(updatePassword bool) error {
  492. var err error
  493. if updatePassword {
  494. user.Password, err = common.Password2Hash(user.Password)
  495. if err != nil {
  496. return err
  497. }
  498. }
  499. newUser := *user
  500. updates := map[string]interface{}{
  501. "username": newUser.Username,
  502. "display_name": newUser.DisplayName,
  503. "group": newUser.Group,
  504. "quota": newUser.Quota,
  505. "remark": newUser.Remark,
  506. }
  507. if updatePassword {
  508. updates["password"] = newUser.Password
  509. }
  510. DB.First(&user, user.Id)
  511. if err = DB.Model(user).Updates(updates).Error; err != nil {
  512. return err
  513. }
  514. // Update cache
  515. return updateUserCache(*user)
  516. }
  517. func (user *User) ClearBinding(bindingType string) error {
  518. if user.Id == 0 {
  519. return errors.New("user id is empty")
  520. }
  521. bindingColumnMap := map[string]string{
  522. "email": "email",
  523. "github": "github_id",
  524. "discord": "discord_id",
  525. "oidc": "oidc_id",
  526. "wechat": "wechat_id",
  527. "telegram": "telegram_id",
  528. "linuxdo": "linux_do_id",
  529. }
  530. column, ok := bindingColumnMap[bindingType]
  531. if !ok {
  532. return errors.New("invalid binding type")
  533. }
  534. if err := DB.Model(&User{}).Where("id = ?", user.Id).Update(column, "").Error; err != nil {
  535. return err
  536. }
  537. if err := DB.Where("id = ?", user.Id).First(user).Error; err != nil {
  538. return err
  539. }
  540. return updateUserCache(*user)
  541. }
  542. func (user *User) Delete() error {
  543. if user.Id == 0 {
  544. return errors.New("id 为空!")
  545. }
  546. if err := DB.Delete(user).Error; err != nil {
  547. return err
  548. }
  549. // 清除缓存
  550. return invalidateUserCache(user.Id)
  551. }
  552. func (user *User) HardDelete() error {
  553. if user.Id == 0 {
  554. return errors.New("id 为空!")
  555. }
  556. err := DB.Unscoped().Delete(user).Error
  557. return err
  558. }
  559. // ValidateAndFill check password & user status
  560. func (user *User) ValidateAndFill() (err error) {
  561. // When querying with struct, GORM will only query with non-zero fields,
  562. // that means if your field's value is 0, '', false or other zero values,
  563. // it won't be used to build query conditions
  564. password := user.Password
  565. username := strings.TrimSpace(user.Username)
  566. if username == "" || password == "" {
  567. return errors.New("用户名或密码为空")
  568. }
  569. // find buy username or email
  570. DB.Where("username = ? OR email = ?", username, username).First(user)
  571. okay := common.ValidatePasswordAndHash(password, user.Password)
  572. if !okay || user.Status != common.UserStatusEnabled {
  573. return errors.New("用户名或密码错误,或用户已被封禁")
  574. }
  575. return nil
  576. }
  577. func (user *User) FillUserById() error {
  578. if user.Id == 0 {
  579. return errors.New("id 为空!")
  580. }
  581. DB.Where(User{Id: user.Id}).First(user)
  582. return nil
  583. }
  584. func (user *User) FillUserByEmail() error {
  585. if user.Email == "" {
  586. return errors.New("email 为空!")
  587. }
  588. DB.Where(User{Email: user.Email}).First(user)
  589. return nil
  590. }
  591. func (user *User) FillUserByGitHubId() error {
  592. if user.GitHubId == "" {
  593. return errors.New("GitHub id 为空!")
  594. }
  595. DB.Where(User{GitHubId: user.GitHubId}).First(user)
  596. return nil
  597. }
  598. // UpdateGitHubId updates the user's GitHub ID (used for migration from login to numeric ID)
  599. func (user *User) UpdateGitHubId(newGitHubId string) error {
  600. if user.Id == 0 {
  601. return errors.New("user id is empty")
  602. }
  603. return DB.Model(user).Update("github_id", newGitHubId).Error
  604. }
  605. func (user *User) FillUserByDiscordId() error {
  606. if user.DiscordId == "" {
  607. return errors.New("discord id 为空!")
  608. }
  609. DB.Where(User{DiscordId: user.DiscordId}).First(user)
  610. return nil
  611. }
  612. func (user *User) FillUserByOidcId() error {
  613. if user.OidcId == "" {
  614. return errors.New("oidc id 为空!")
  615. }
  616. DB.Where(User{OidcId: user.OidcId}).First(user)
  617. return nil
  618. }
  619. func (user *User) FillUserByWeChatId() error {
  620. if user.WeChatId == "" {
  621. return errors.New("WeChat id 为空!")
  622. }
  623. DB.Where(User{WeChatId: user.WeChatId}).First(user)
  624. return nil
  625. }
  626. func (user *User) FillUserByTelegramId() error {
  627. if user.TelegramId == "" {
  628. return errors.New("Telegram id 为空!")
  629. }
  630. err := DB.Where(User{TelegramId: user.TelegramId}).First(user).Error
  631. if errors.Is(err, gorm.ErrRecordNotFound) {
  632. return errors.New("该 Telegram 账户未绑定")
  633. }
  634. return nil
  635. }
  636. func IsEmailAlreadyTaken(email string) bool {
  637. return DB.Unscoped().Where("email = ?", email).Find(&User{}).RowsAffected == 1
  638. }
  639. func IsWeChatIdAlreadyTaken(wechatId string) bool {
  640. return DB.Unscoped().Where("wechat_id = ?", wechatId).Find(&User{}).RowsAffected == 1
  641. }
  642. func IsGitHubIdAlreadyTaken(githubId string) bool {
  643. return DB.Unscoped().Where("github_id = ?", githubId).Find(&User{}).RowsAffected == 1
  644. }
  645. func IsDiscordIdAlreadyTaken(discordId string) bool {
  646. return DB.Unscoped().Where("discord_id = ?", discordId).Find(&User{}).RowsAffected == 1
  647. }
  648. func IsOidcIdAlreadyTaken(oidcId string) bool {
  649. return DB.Where("oidc_id = ?", oidcId).Find(&User{}).RowsAffected == 1
  650. }
  651. func IsTelegramIdAlreadyTaken(telegramId string) bool {
  652. return DB.Unscoped().Where("telegram_id = ?", telegramId).Find(&User{}).RowsAffected == 1
  653. }
  654. func ResetUserPasswordByEmail(email string, password string) error {
  655. if email == "" || password == "" {
  656. return errors.New("邮箱地址或密码为空!")
  657. }
  658. hashedPassword, err := common.Password2Hash(password)
  659. if err != nil {
  660. return err
  661. }
  662. err = DB.Model(&User{}).Where("email = ?", email).Update("password", hashedPassword).Error
  663. return err
  664. }
  665. func IsAdmin(userId int) bool {
  666. if userId == 0 {
  667. return false
  668. }
  669. var user User
  670. err := DB.Where("id = ?", userId).Select("role").Find(&user).Error
  671. if err != nil {
  672. common.SysLog("no such user " + err.Error())
  673. return false
  674. }
  675. return user.Role >= common.RoleAdminUser
  676. }
  677. //// IsUserEnabled checks user status from Redis first, falls back to DB if needed
  678. //func IsUserEnabled(id int, fromDB bool) (status bool, err error) {
  679. // defer func() {
  680. // // Update Redis cache asynchronously on successful DB read
  681. // if shouldUpdateRedis(fromDB, err) {
  682. // gopool.Go(func() {
  683. // if err := updateUserStatusCache(id, status); err != nil {
  684. // common.SysError("failed to update user status cache: " + err.Error())
  685. // }
  686. // })
  687. // }
  688. // }()
  689. // if !fromDB && common.RedisEnabled {
  690. // // Try Redis first
  691. // status, err := getUserStatusCache(id)
  692. // if err == nil {
  693. // return status == common.UserStatusEnabled, nil
  694. // }
  695. // // Don't return error - fall through to DB
  696. // }
  697. // fromDB = true
  698. // var user User
  699. // err = DB.Where("id = ?", id).Select("status").Find(&user).Error
  700. // if err != nil {
  701. // return false, err
  702. // }
  703. //
  704. // return user.Status == common.UserStatusEnabled, nil
  705. //}
  706. func ValidateAccessToken(token string) (user *User) {
  707. if token == "" {
  708. return nil
  709. }
  710. token = strings.Replace(token, "Bearer ", "", 1)
  711. user = &User{}
  712. if DB.Where("access_token = ?", token).First(user).RowsAffected == 1 {
  713. return user
  714. }
  715. return nil
  716. }
  717. // GetUserQuota gets quota from Redis first, falls back to DB if needed
  718. // 同步用户返回 SyncedQuota,本地用户返回 Quota
  719. func GetUserQuota(id int, fromDB bool) (quota int, err error) {
  720. if !fromDB && common.RedisEnabled {
  721. quota, err := getUserQuotaCache(id)
  722. if err == nil {
  723. return quota, nil
  724. }
  725. // Don't return error - fall through to DB
  726. }
  727. fromDB = true
  728. // 查询用户的 source 和额度字段
  729. var user User
  730. err = DB.Model(&User{}).Select("source", "quota", "synced_quota").Where("id = ?", id).First(&user).Error
  731. if err != nil {
  732. return 0, err
  733. }
  734. // 同步用户返回 SyncedQuota,本地用户返回 Quota
  735. if user.IsSyncedUser() {
  736. quota = user.SyncedQuota
  737. } else {
  738. quota = user.Quota
  739. }
  740. // Update Redis cache asynchronously if enabled
  741. if common.RedisEnabled {
  742. gopool.Go(func() {
  743. if err := updateUserQuotaCache(id, quota); err != nil {
  744. common.SysLog("failed to update user quota cache: " + err.Error())
  745. }
  746. })
  747. }
  748. return quota, nil
  749. }
  750. func GetUserUsedQuota(id int) (quota int, err error) {
  751. err = DB.Model(&User{}).Where("id = ?", id).Select("used_quota").Find(&quota).Error
  752. return quota, err
  753. }
  754. func GetUserEmail(id int) (email string, err error) {
  755. err = DB.Model(&User{}).Where("id = ?", id).Select("email").Find(&email).Error
  756. return email, err
  757. }
  758. // GetUserGroup gets group from Redis first, falls back to DB if needed
  759. func GetUserGroup(id int, fromDB bool) (group string, err error) {
  760. defer func() {
  761. // Update Redis cache asynchronously on successful DB read
  762. if shouldUpdateRedis(fromDB, err) {
  763. gopool.Go(func() {
  764. if err := updateUserGroupCache(id, group); err != nil {
  765. common.SysLog("failed to update user group cache: " + err.Error())
  766. }
  767. })
  768. }
  769. }()
  770. if !fromDB && common.RedisEnabled {
  771. group, err := getUserGroupCache(id)
  772. if err == nil {
  773. return group, nil
  774. }
  775. // Don't return error - fall through to DB
  776. }
  777. fromDB = true
  778. err = DB.Model(&User{}).Where("id = ?", id).Select(commonGroupCol).Find(&group).Error
  779. if err != nil {
  780. return "", err
  781. }
  782. return group, nil
  783. }
  784. // GetUserSetting gets setting from Redis first, falls back to DB if needed
  785. func GetUserSetting(id int, fromDB bool) (settingMap dto.UserSetting, err error) {
  786. var setting string
  787. defer func() {
  788. // Update Redis cache asynchronously on successful DB read
  789. if shouldUpdateRedis(fromDB, err) {
  790. gopool.Go(func() {
  791. if err := updateUserSettingCache(id, setting); err != nil {
  792. common.SysLog("failed to update user setting cache: " + err.Error())
  793. }
  794. })
  795. }
  796. }()
  797. if !fromDB && common.RedisEnabled {
  798. setting, err := getUserSettingCache(id)
  799. if err == nil {
  800. return setting, nil
  801. }
  802. // Don't return error - fall through to DB
  803. }
  804. fromDB = true
  805. err = DB.Model(&User{}).Where("id = ?", id).Select("setting").Find(&setting).Error
  806. if err != nil {
  807. return settingMap, err
  808. }
  809. userBase := &UserBase{
  810. Setting: setting,
  811. }
  812. return userBase.GetSetting(), nil
  813. }
  814. func IncreaseUserQuota(id int, quota int, db bool) (err error) {
  815. if quota < 0 {
  816. return errors.New("quota 不能为负数!")
  817. }
  818. gopool.Go(func() {
  819. err := cacheIncrUserQuota(id, int64(quota))
  820. if err != nil {
  821. common.SysLog("failed to increase user quota: " + err.Error())
  822. }
  823. })
  824. if !db && common.BatchUpdateEnabled {
  825. addNewRecord(BatchUpdateTypeUserQuota, id, quota)
  826. return nil
  827. }
  828. err = increaseUserQuota(id, quota)
  829. if err != nil {
  830. return err
  831. }
  832. // 触发余额更新回调(如果有注册)
  833. if quotaUpdateCallback != nil {
  834. newQuota, _ := GetUserQuota(id, true)
  835. // 使用 defer/recover 保护回调,防止 panic 影响主流程
  836. func() {
  837. defer func() {
  838. if r := recover(); r != nil {
  839. common.SysError(fmt.Sprintf("quota update callback panic: %v", r))
  840. }
  841. }()
  842. quotaUpdateCallback(id, newQuota)
  843. }()
  844. }
  845. return nil
  846. }
  847. func increaseUserQuota(id int, quota int) (err error) {
  848. err = DB.Model(&User{}).Where("id = ?", id).Update("quota", gorm.Expr("quota + ?", quota)).Error
  849. if err != nil {
  850. return err
  851. }
  852. return err
  853. }
  854. func DecreaseUserQuota(id int, quota int) (err error) {
  855. if quota < 0 {
  856. return errors.New("quota 不能为负数!")
  857. }
  858. gopool.Go(func() {
  859. err := cacheDecrUserQuota(id, int64(quota))
  860. if err != nil {
  861. common.SysLog("failed to decrease user quota: " + err.Error())
  862. }
  863. })
  864. if common.BatchUpdateEnabled {
  865. addNewRecord(BatchUpdateTypeUserQuota, id, -quota)
  866. return nil
  867. }
  868. return decreaseUserQuota(id, quota)
  869. }
  870. func decreaseUserQuota(id int, quota int) (err error) {
  871. err = DB.Model(&User{}).Where("id = ?", id).Update("quota", gorm.Expr("quota - ?", quota)).Error
  872. if err != nil {
  873. return err
  874. }
  875. return err
  876. }
  877. func DeltaUpdateUserQuota(id int, delta int) (err error) {
  878. if delta == 0 {
  879. return nil
  880. }
  881. if delta > 0 {
  882. return IncreaseUserQuota(id, delta, false)
  883. } else {
  884. return DecreaseUserQuota(id, -delta)
  885. }
  886. }
  887. // GetSyncedUsers 获取所有同步用户
  888. func GetSyncedUsers() []User {
  889. var users []User
  890. DB.Where("source = ?", common.UserSourceSynced).Find(&users)
  891. return users
  892. }
  893. // UpdateSyncedQuota 更新同步用户的 synced_quota
  894. func UpdateSyncedQuota(userId int, quota int) error {
  895. return DB.Model(&User{}).Where("id = ?", userId).Updates(map[string]interface{}{
  896. "synced_quota": quota,
  897. "last_sync_at": time.Now().Unix(),
  898. }).Error
  899. }
  900. // AtomicDecreaseSyncedQuota 原子扣减 synced_quota,检查余额并扣减在一条 SQL 中完成。
  901. // 语义:扣减后 synced_quota 必须 >= threshold,即 synced_quota >= amount + threshold。
  902. // 返回 (当前余额, 是否成功, 错误)。
  903. func AtomicDecreaseSyncedQuota(userId int, amount int, threshold int) (int, bool, error) {
  904. result := DB.Model(&User{}).
  905. Where("id = ? AND synced_quota >= ?", userId, amount+threshold).
  906. Update("synced_quota", gorm.Expr("synced_quota - ?", amount))
  907. if result.Error != nil {
  908. return 0, false, result.Error
  909. }
  910. if result.RowsAffected == 0 {
  911. var quota int
  912. DB.Model(&User{}).Where("id = ?", userId).Select("synced_quota").Scan(&quota)
  913. return quota, false, nil
  914. }
  915. var newQuota int
  916. DB.Model(&User{}).Where("id = ?", userId).Select("synced_quota").Scan(&newQuota)
  917. return newQuota, true, nil
  918. }
  919. // IncreaseSyncedQuota 原子增加 synced_quota(用于退款)
  920. func IncreaseSyncedQuota(userId int, amount int) error {
  921. return DB.Model(&User{}).
  922. Where("id = ?", userId).
  923. Update("synced_quota", gorm.Expr("synced_quota + ?", amount)).Error
  924. }
  925. // AdjustSyncedQuota 原子调整 synced_quota(增量更新,避免并发覆盖)
  926. // delta > 0 表示额外扣减,delta < 0 表示退还。
  927. func AdjustSyncedQuota(userId int, delta int) error {
  928. return DB.Model(&User{}).Where("id = ?", userId).
  929. Update("synced_quota", gorm.Expr("synced_quota - ?", delta)).Error
  930. }
  931. //func GetRootUserEmail() (email string) {
  932. // DB.Model(&User{}).Where("role = ?", common.RoleRootUser).Select("email").Find(&email)
  933. // return email
  934. //}
  935. func GetRootUser() (user *User) {
  936. DB.Where("role = ?", common.RoleRootUser).First(&user)
  937. return user
  938. }
  939. func UpdateUserUsedQuotaAndRequestCount(id int, quota int) {
  940. if common.BatchUpdateEnabled {
  941. addNewRecord(BatchUpdateTypeUsedQuota, id, quota)
  942. addNewRecord(BatchUpdateTypeRequestCount, id, 1)
  943. return
  944. }
  945. updateUserUsedQuotaAndRequestCount(id, quota, 1)
  946. }
  947. func updateUserUsedQuotaAndRequestCount(id int, quota int, count int) {
  948. err := DB.Model(&User{}).Where("id = ?", id).Updates(
  949. map[string]interface{}{
  950. "used_quota": gorm.Expr("used_quota + ?", quota),
  951. "request_count": gorm.Expr("request_count + ?", count),
  952. },
  953. ).Error
  954. if err != nil {
  955. common.SysLog("failed to update user used quota and request count: " + err.Error())
  956. return
  957. }
  958. //// 更新缓存
  959. //if err := invalidateUserCache(id); err != nil {
  960. // common.SysError("failed to invalidate user cache: " + err.Error())
  961. //}
  962. }
  963. func updateUserUsedQuota(id int, quota int) {
  964. err := DB.Model(&User{}).Where("id = ?", id).Updates(
  965. map[string]interface{}{
  966. "used_quota": gorm.Expr("used_quota + ?", quota),
  967. },
  968. ).Error
  969. if err != nil {
  970. common.SysLog("failed to update user used quota: " + err.Error())
  971. }
  972. }
  973. func updateUserRequestCount(id int, count int) {
  974. err := DB.Model(&User{}).Where("id = ?", id).Update("request_count", gorm.Expr("request_count + ?", count)).Error
  975. if err != nil {
  976. common.SysLog("failed to update user request count: " + err.Error())
  977. }
  978. }
  979. // GetUsernameById gets username from Redis first, falls back to DB if needed
  980. func GetUsernameById(id int, fromDB bool) (username string, err error) {
  981. defer func() {
  982. // Update Redis cache asynchronously on successful DB read
  983. if shouldUpdateRedis(fromDB, err) {
  984. gopool.Go(func() {
  985. if err := updateUserNameCache(id, username); err != nil {
  986. common.SysLog("failed to update user name cache: " + err.Error())
  987. }
  988. })
  989. }
  990. }()
  991. if !fromDB && common.RedisEnabled {
  992. username, err := getUserNameCache(id)
  993. if err == nil {
  994. return username, nil
  995. }
  996. // Don't return error - fall through to DB
  997. }
  998. fromDB = true
  999. err = DB.Model(&User{}).Where("id = ?", id).Select("username").Find(&username).Error
  1000. if err != nil {
  1001. return "", err
  1002. }
  1003. return username, nil
  1004. }
  1005. func IsLinuxDOIdAlreadyTaken(linuxDOId string) bool {
  1006. var user User
  1007. err := DB.Unscoped().Where("linux_do_id = ?", linuxDOId).First(&user).Error
  1008. return !errors.Is(err, gorm.ErrRecordNotFound)
  1009. }
  1010. func (user *User) FillUserByLinuxDOId() error {
  1011. if user.LinuxDOId == "" {
  1012. return errors.New("linux do id is empty")
  1013. }
  1014. err := DB.Where("linux_do_id = ?", user.LinuxDOId).First(user).Error
  1015. return err
  1016. }
  1017. func RootUserExists() bool {
  1018. var user User
  1019. err := DB.Where("role = ?", common.RoleRootUser).First(&user).Error
  1020. if err != nil {
  1021. return false
  1022. }
  1023. return true
  1024. }