Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 

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