user.go 29 KB

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