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.
 
 
 

1357 lines
39 KiB

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