user.go 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031
  1. package model
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "strconv"
  7. "strings"
  8. "github.com/QuantumNous/new-api/common"
  9. "github.com/QuantumNous/new-api/dto"
  10. "github.com/QuantumNous/new-api/logger"
  11. "github.com/bytedance/gopkg/util/gopool"
  12. "gorm.io/gorm"
  13. )
  14. const UserNameMaxLength = 20
  15. // User if you add sensitive fields, don't forget to clean them in setupLogin function.
  16. // Otherwise, the sensitive information will be saved on local storage in plain text!
  17. type User struct {
  18. Id int `json:"id"`
  19. Username string `json:"username" gorm:"unique;index" validate:"max=20"`
  20. Password string `json:"password" gorm:"not null;" validate:"min=8,max=20"`
  21. OriginalPassword string `json:"original_password" gorm:"-:all"` // this field is only for Password change verification, don't save it to database!
  22. DisplayName string `json:"display_name" gorm:"index" validate:"max=20"`
  23. Role int `json:"role" gorm:"type:int;default:1"` // admin, common
  24. Status int `json:"status" gorm:"type:int;default:1"` // enabled, disabled
  25. Email string `json:"email" gorm:"index" validate:"max=50"`
  26. GitHubId string `json:"github_id" gorm:"column:github_id;index"`
  27. DiscordId string `json:"discord_id" gorm:"column:discord_id;index"`
  28. OidcId string `json:"oidc_id" gorm:"column:oidc_id;index"`
  29. WeChatId string `json:"wechat_id" gorm:"column:wechat_id;index"`
  30. TelegramId string `json:"telegram_id" gorm:"column:telegram_id;index"`
  31. VerificationCode string `json:"verification_code" gorm:"-:all"` // this field is only for Email verification, don't save it to database!
  32. AccessToken *string `json:"access_token" gorm:"type:char(32);column:access_token;uniqueIndex"` // this token is for system management
  33. Quota int `json:"quota" gorm:"type:int;default:0"`
  34. UsedQuota int `json:"used_quota" gorm:"type:int;default:0;column:used_quota"` // used quota
  35. RequestCount int `json:"request_count" gorm:"type:int;default:0;"` // request number
  36. Group string `json:"group" gorm:"type:varchar(64);default:'default'"`
  37. AffCode string `json:"aff_code" gorm:"type:varchar(32);column:aff_code;uniqueIndex"`
  38. AffCount int `json:"aff_count" gorm:"type:int;default:0;column:aff_count"`
  39. AffQuota int `json:"aff_quota" gorm:"type:int;default:0;column:aff_quota"` // 邀请剩余额度
  40. AffHistoryQuota int `json:"aff_history_quota" gorm:"type:int;default:0;column:aff_history"` // 邀请历史额度
  41. InviterId int `json:"inviter_id" gorm:"type:int;column:inviter_id;index"`
  42. DeletedAt gorm.DeletedAt `gorm:"index"`
  43. LinuxDOId string `json:"linux_do_id" gorm:"column:linux_do_id;index"`
  44. Setting string `json:"setting" gorm:"type:text;column:setting"`
  45. Remark string `json:"remark,omitempty" gorm:"type:varchar(255)" validate:"max=255"`
  46. StripeCustomer string `json:"stripe_customer" gorm:"type:varchar(64);column:stripe_customer;index"`
  47. }
  48. func (user *User) ToBaseUser() *UserBase {
  49. cache := &UserBase{
  50. Id: user.Id,
  51. Group: user.Group,
  52. Quota: user.Quota,
  53. Status: user.Status,
  54. Username: user.Username,
  55. Setting: user.Setting,
  56. Email: user.Email,
  57. }
  58. return cache
  59. }
  60. func (user *User) GetAccessToken() string {
  61. if user.AccessToken == nil {
  62. return ""
  63. }
  64. return *user.AccessToken
  65. }
  66. func (user *User) SetAccessToken(token string) {
  67. user.AccessToken = &token
  68. }
  69. func (user *User) GetSetting() dto.UserSetting {
  70. setting := dto.UserSetting{}
  71. if user.Setting != "" {
  72. err := json.Unmarshal([]byte(user.Setting), &setting)
  73. if err != nil {
  74. common.SysLog("failed to unmarshal setting: " + err.Error())
  75. }
  76. }
  77. return setting
  78. }
  79. func (user *User) SetSetting(setting dto.UserSetting) {
  80. settingBytes, err := json.Marshal(setting)
  81. if err != nil {
  82. common.SysLog("failed to marshal setting: " + err.Error())
  83. return
  84. }
  85. user.Setting = string(settingBytes)
  86. }
  87. // 根据用户角色生成默认的边栏配置
  88. func generateDefaultSidebarConfigForRole(userRole int) string {
  89. defaultConfig := map[string]interface{}{}
  90. // 聊天区域 - 所有用户都可以访问
  91. defaultConfig["chat"] = map[string]interface{}{
  92. "enabled": true,
  93. "playground": true,
  94. "chat": true,
  95. }
  96. // 控制台区域 - 所有用户都可以访问
  97. defaultConfig["console"] = map[string]interface{}{
  98. "enabled": true,
  99. "detail": true,
  100. "token": true,
  101. "log": true,
  102. "midjourney": true,
  103. "task": true,
  104. }
  105. // 个人中心区域 - 所有用户都可以访问
  106. defaultConfig["personal"] = map[string]interface{}{
  107. "enabled": true,
  108. "topup": true,
  109. "personal": true,
  110. }
  111. // 管理员区域 - 根据角色决定
  112. if userRole == common.RoleAdminUser {
  113. // 管理员可以访问管理员区域,但不能访问系统设置
  114. defaultConfig["admin"] = map[string]interface{}{
  115. "enabled": true,
  116. "channel": true,
  117. "models": true,
  118. "redemption": true,
  119. "user": true,
  120. "setting": false, // 管理员不能访问系统设置
  121. }
  122. } else if userRole == common.RoleRootUser {
  123. // 超级管理员可以访问所有功能
  124. defaultConfig["admin"] = map[string]interface{}{
  125. "enabled": true,
  126. "channel": true,
  127. "models": true,
  128. "redemption": true,
  129. "user": true,
  130. "setting": true,
  131. }
  132. }
  133. // 普通用户不包含admin区域
  134. // 转换为JSON字符串
  135. configBytes, err := json.Marshal(defaultConfig)
  136. if err != nil {
  137. common.SysLog("生成默认边栏配置失败: " + err.Error())
  138. return ""
  139. }
  140. return string(configBytes)
  141. }
  142. // CheckUserExistOrDeleted check if user exist or deleted, if not exist, return false, nil, if deleted or exist, return true, nil
  143. func CheckUserExistOrDeleted(username string, email string) (bool, error) {
  144. var user User
  145. // err := DB.Unscoped().First(&user, "username = ? or email = ?", username, email).Error
  146. // check email if empty
  147. var err error
  148. if email == "" {
  149. err = DB.Unscoped().First(&user, "username = ?", username).Error
  150. } else {
  151. err = DB.Unscoped().First(&user, "username = ? or email = ?", username, email).Error
  152. }
  153. if err != nil {
  154. if errors.Is(err, gorm.ErrRecordNotFound) {
  155. // not exist, return false, nil
  156. return false, nil
  157. }
  158. // other error, return false, err
  159. return false, err
  160. }
  161. // exist, return true, nil
  162. return true, nil
  163. }
  164. func GetMaxUserId() int {
  165. var user User
  166. DB.Unscoped().Last(&user)
  167. return user.Id
  168. }
  169. func GetAllUsers(pageInfo *common.PageInfo) (users []*User, total int64, err error) {
  170. // Start transaction
  171. tx := DB.Begin()
  172. if tx.Error != nil {
  173. return nil, 0, tx.Error
  174. }
  175. defer func() {
  176. if r := recover(); r != nil {
  177. tx.Rollback()
  178. }
  179. }()
  180. // Get total count within transaction
  181. err = tx.Unscoped().Model(&User{}).Count(&total).Error
  182. if err != nil {
  183. tx.Rollback()
  184. return nil, 0, err
  185. }
  186. // Get paginated users within same transaction
  187. err = tx.Unscoped().Order("id desc").Limit(pageInfo.GetPageSize()).Offset(pageInfo.GetStartIdx()).Omit("password").Find(&users).Error
  188. if err != nil {
  189. tx.Rollback()
  190. return nil, 0, err
  191. }
  192. // Commit transaction
  193. if err = tx.Commit().Error; err != nil {
  194. return nil, 0, err
  195. }
  196. return users, total, nil
  197. }
  198. func SearchUsers(keyword string, group string, startIdx int, num int) ([]*User, int64, error) {
  199. var users []*User
  200. var total int64
  201. var err error
  202. // 开始事务
  203. tx := DB.Begin()
  204. if tx.Error != nil {
  205. return nil, 0, tx.Error
  206. }
  207. defer func() {
  208. if r := recover(); r != nil {
  209. tx.Rollback()
  210. }
  211. }()
  212. // 构建基础查询
  213. query := tx.Unscoped().Model(&User{})
  214. // 构建搜索条件
  215. likeCondition := "username LIKE ? OR email LIKE ? OR display_name LIKE ?"
  216. // 尝试将关键字转换为整数ID
  217. keywordInt, err := strconv.Atoi(keyword)
  218. if err == nil {
  219. // 如果是数字,同时搜索ID和其他字段
  220. likeCondition = "id = ? OR " + likeCondition
  221. if group != "" {
  222. query = query.Where("("+likeCondition+") AND "+commonGroupCol+" = ?",
  223. keywordInt, "%"+keyword+"%", "%"+keyword+"%", "%"+keyword+"%", group)
  224. } else {
  225. query = query.Where(likeCondition,
  226. keywordInt, "%"+keyword+"%", "%"+keyword+"%", "%"+keyword+"%")
  227. }
  228. } else {
  229. // 非数字关键字,只搜索字符串字段
  230. if group != "" {
  231. query = query.Where("("+likeCondition+") AND "+commonGroupCol+" = ?",
  232. "%"+keyword+"%", "%"+keyword+"%", "%"+keyword+"%", group)
  233. } else {
  234. query = query.Where(likeCondition,
  235. "%"+keyword+"%", "%"+keyword+"%", "%"+keyword+"%")
  236. }
  237. }
  238. // 获取总数
  239. err = query.Count(&total).Error
  240. if err != nil {
  241. tx.Rollback()
  242. return nil, 0, err
  243. }
  244. // 获取分页数据
  245. err = query.Omit("password").Order("id desc").Limit(num).Offset(startIdx).Find(&users).Error
  246. if err != nil {
  247. tx.Rollback()
  248. return nil, 0, err
  249. }
  250. // 提交事务
  251. if err = tx.Commit().Error; err != nil {
  252. return nil, 0, err
  253. }
  254. return users, total, nil
  255. }
  256. func GetUserById(id int, selectAll bool) (*User, error) {
  257. if id == 0 {
  258. return nil, errors.New("id 为空!")
  259. }
  260. user := User{Id: id}
  261. var err error = nil
  262. if selectAll {
  263. err = DB.First(&user, "id = ?", id).Error
  264. } else {
  265. err = DB.Omit("password").First(&user, "id = ?", id).Error
  266. }
  267. return &user, err
  268. }
  269. func GetUserIdByAffCode(affCode string) (int, error) {
  270. if affCode == "" {
  271. return 0, errors.New("affCode 为空!")
  272. }
  273. var user User
  274. err := DB.Select("id").First(&user, "aff_code = ?", affCode).Error
  275. return user.Id, err
  276. }
  277. func DeleteUserById(id int) (err error) {
  278. if id == 0 {
  279. return errors.New("id 为空!")
  280. }
  281. user := User{Id: id}
  282. return user.Delete()
  283. }
  284. func HardDeleteUserById(id int) error {
  285. if id == 0 {
  286. return errors.New("id 为空!")
  287. }
  288. err := DB.Unscoped().Delete(&User{}, "id = ?", id).Error
  289. return err
  290. }
  291. func inviteUser(inviterId int) (err error) {
  292. user, err := GetUserById(inviterId, true)
  293. if err != nil {
  294. return err
  295. }
  296. user.AffCount++
  297. user.AffQuota += common.QuotaForInviter
  298. user.AffHistoryQuota += common.QuotaForInviter
  299. return DB.Save(user).Error
  300. }
  301. func (user *User) TransferAffQuotaToQuota(quota int) error {
  302. // 检查quota是否小于最小额度
  303. if float64(quota) < common.QuotaPerUnit {
  304. return fmt.Errorf("转移额度最小为%s!", logger.LogQuota(int(common.QuotaPerUnit)))
  305. }
  306. // 开始数据库事务
  307. tx := DB.Begin()
  308. if tx.Error != nil {
  309. return tx.Error
  310. }
  311. defer tx.Rollback() // 确保在函数退出时事务能回滚
  312. // 加锁查询用户以确保数据一致性
  313. err := tx.Set("gorm:query_option", "FOR UPDATE").First(&user, user.Id).Error
  314. if err != nil {
  315. return err
  316. }
  317. // 再次检查用户的AffQuota是否足够
  318. if user.AffQuota < quota {
  319. return errors.New("邀请额度不足!")
  320. }
  321. // 更新用户额度
  322. user.AffQuota -= quota
  323. user.Quota += quota
  324. // 保存用户状态
  325. if err := tx.Save(user).Error; err != nil {
  326. return err
  327. }
  328. // 提交事务
  329. return tx.Commit().Error
  330. }
  331. func (user *User) Insert(inviterId int) error {
  332. var err error
  333. if user.Password != "" {
  334. user.Password, err = common.Password2Hash(user.Password)
  335. if err != nil {
  336. return err
  337. }
  338. }
  339. user.Quota = common.QuotaForNewUser
  340. //user.SetAccessToken(common.GetUUID())
  341. user.AffCode = common.GetRandomString(4)
  342. // 初始化用户设置,包括默认的边栏配置
  343. if user.Setting == "" {
  344. defaultSetting := dto.UserSetting{}
  345. // 这里暂时不设置SidebarModules,因为需要在用户创建后根据角色设置
  346. user.SetSetting(defaultSetting)
  347. }
  348. result := DB.Create(user)
  349. if result.Error != nil {
  350. return result.Error
  351. }
  352. // 用户创建成功后,根据角色初始化边栏配置
  353. // 需要重新获取用户以确保有正确的ID和Role
  354. var createdUser User
  355. if err := DB.Where("username = ?", user.Username).First(&createdUser).Error; err == nil {
  356. // 生成基于角色的默认边栏配置
  357. defaultSidebarConfig := generateDefaultSidebarConfigForRole(createdUser.Role)
  358. if defaultSidebarConfig != "" {
  359. currentSetting := createdUser.GetSetting()
  360. currentSetting.SidebarModules = defaultSidebarConfig
  361. createdUser.SetSetting(currentSetting)
  362. createdUser.Update(false)
  363. common.SysLog(fmt.Sprintf("为新用户 %s (角色: %d) 初始化边栏配置", createdUser.Username, createdUser.Role))
  364. }
  365. }
  366. if common.QuotaForNewUser > 0 {
  367. RecordLog(user.Id, LogTypeSystem, fmt.Sprintf("新用户注册赠送 %s", logger.LogQuota(common.QuotaForNewUser)))
  368. }
  369. if inviterId != 0 {
  370. if common.QuotaForInvitee > 0 {
  371. _ = IncreaseUserQuota(user.Id, common.QuotaForInvitee, true)
  372. RecordLog(user.Id, LogTypeSystem, fmt.Sprintf("使用邀请码赠送 %s", logger.LogQuota(common.QuotaForInvitee)))
  373. }
  374. if common.QuotaForInviter > 0 {
  375. //_ = IncreaseUserQuota(inviterId, common.QuotaForInviter)
  376. RecordLog(inviterId, LogTypeSystem, fmt.Sprintf("邀请用户赠送 %s", logger.LogQuota(common.QuotaForInviter)))
  377. _ = inviteUser(inviterId)
  378. }
  379. }
  380. return nil
  381. }
  382. // InsertWithTx inserts a new user within an existing transaction.
  383. // This is used for OAuth registration where user creation and binding need to be atomic.
  384. // Post-creation tasks (sidebar config, logs, inviter rewards) are handled after the transaction commits.
  385. func (user *User) InsertWithTx(tx *gorm.DB, inviterId int) error {
  386. var err error
  387. if user.Password != "" {
  388. user.Password, err = common.Password2Hash(user.Password)
  389. if err != nil {
  390. return err
  391. }
  392. }
  393. user.Quota = common.QuotaForNewUser
  394. user.AffCode = common.GetRandomString(4)
  395. // 初始化用户设置
  396. if user.Setting == "" {
  397. defaultSetting := dto.UserSetting{}
  398. user.SetSetting(defaultSetting)
  399. }
  400. result := tx.Create(user)
  401. if result.Error != nil {
  402. return result.Error
  403. }
  404. return nil
  405. }
  406. // FinalizeOAuthUserCreation performs post-transaction tasks for OAuth user creation.
  407. // This should be called after the transaction commits successfully.
  408. func (user *User) FinalizeOAuthUserCreation(inviterId int) {
  409. // 用户创建成功后,根据角色初始化边栏配置
  410. var createdUser User
  411. if err := DB.Where("id = ?", user.Id).First(&createdUser).Error; err == nil {
  412. defaultSidebarConfig := generateDefaultSidebarConfigForRole(createdUser.Role)
  413. if defaultSidebarConfig != "" {
  414. currentSetting := createdUser.GetSetting()
  415. currentSetting.SidebarModules = defaultSidebarConfig
  416. createdUser.SetSetting(currentSetting)
  417. createdUser.Update(false)
  418. common.SysLog(fmt.Sprintf("为新用户 %s (角色: %d) 初始化边栏配置", createdUser.Username, createdUser.Role))
  419. }
  420. }
  421. if common.QuotaForNewUser > 0 {
  422. RecordLog(user.Id, LogTypeSystem, fmt.Sprintf("新用户注册赠送 %s", logger.LogQuota(common.QuotaForNewUser)))
  423. }
  424. if inviterId != 0 {
  425. if common.QuotaForInvitee > 0 {
  426. _ = IncreaseUserQuota(user.Id, common.QuotaForInvitee, true)
  427. RecordLog(user.Id, LogTypeSystem, fmt.Sprintf("使用邀请码赠送 %s", logger.LogQuota(common.QuotaForInvitee)))
  428. }
  429. if common.QuotaForInviter > 0 {
  430. RecordLog(inviterId, LogTypeSystem, fmt.Sprintf("邀请用户赠送 %s", logger.LogQuota(common.QuotaForInviter)))
  431. _ = inviteUser(inviterId)
  432. }
  433. }
  434. }
  435. func (user *User) Update(updatePassword bool) error {
  436. var err error
  437. if updatePassword {
  438. user.Password, err = common.Password2Hash(user.Password)
  439. if err != nil {
  440. return err
  441. }
  442. }
  443. newUser := *user
  444. DB.First(&user, user.Id)
  445. if err = DB.Model(user).Updates(newUser).Error; err != nil {
  446. return err
  447. }
  448. // Update cache
  449. return updateUserCache(*user)
  450. }
  451. func (user *User) Edit(updatePassword bool) error {
  452. var err error
  453. if updatePassword {
  454. user.Password, err = common.Password2Hash(user.Password)
  455. if err != nil {
  456. return err
  457. }
  458. }
  459. newUser := *user
  460. updates := map[string]interface{}{
  461. "username": newUser.Username,
  462. "display_name": newUser.DisplayName,
  463. "group": newUser.Group,
  464. "quota": newUser.Quota,
  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. err = DB.Model(&User{}).Where("id = ?", id).Select("setting").Find(&setting).Error
  759. if err != nil {
  760. return settingMap, err
  761. }
  762. userBase := &UserBase{
  763. Setting: setting,
  764. }
  765. return userBase.GetSetting(), nil
  766. }
  767. func IncreaseUserQuota(id int, quota int, db bool) (err error) {
  768. if quota < 0 {
  769. return errors.New("quota 不能为负数!")
  770. }
  771. gopool.Go(func() {
  772. err := cacheIncrUserQuota(id, int64(quota))
  773. if err != nil {
  774. common.SysLog("failed to increase user quota: " + err.Error())
  775. }
  776. })
  777. if !db && common.BatchUpdateEnabled {
  778. addNewRecord(BatchUpdateTypeUserQuota, id, quota)
  779. return nil
  780. }
  781. return increaseUserQuota(id, quota)
  782. }
  783. func increaseUserQuota(id int, quota int) (err error) {
  784. err = DB.Model(&User{}).Where("id = ?", id).Update("quota", gorm.Expr("quota + ?", quota)).Error
  785. if err != nil {
  786. return err
  787. }
  788. return err
  789. }
  790. func DecreaseUserQuota(id int, quota int) (err error) {
  791. if quota < 0 {
  792. return errors.New("quota 不能为负数!")
  793. }
  794. gopool.Go(func() {
  795. err := cacheDecrUserQuota(id, int64(quota))
  796. if err != nil {
  797. common.SysLog("failed to decrease user quota: " + err.Error())
  798. }
  799. })
  800. if common.BatchUpdateEnabled {
  801. addNewRecord(BatchUpdateTypeUserQuota, id, -quota)
  802. return nil
  803. }
  804. return decreaseUserQuota(id, quota)
  805. }
  806. func decreaseUserQuota(id int, quota int) (err error) {
  807. err = DB.Model(&User{}).Where("id = ?", id).Update("quota", gorm.Expr("quota - ?", quota)).Error
  808. if err != nil {
  809. return err
  810. }
  811. return err
  812. }
  813. func DeltaUpdateUserQuota(id int, delta int) (err error) {
  814. if delta == 0 {
  815. return nil
  816. }
  817. if delta > 0 {
  818. return IncreaseUserQuota(id, delta, false)
  819. } else {
  820. return DecreaseUserQuota(id, -delta)
  821. }
  822. }
  823. //func GetRootUserEmail() (email string) {
  824. // DB.Model(&User{}).Where("role = ?", common.RoleRootUser).Select("email").Find(&email)
  825. // return email
  826. //}
  827. func GetRootUser() (user *User) {
  828. DB.Where("role = ?", common.RoleRootUser).First(&user)
  829. return user
  830. }
  831. func UpdateUserUsedQuotaAndRequestCount(id int, quota int) {
  832. if common.BatchUpdateEnabled {
  833. addNewRecord(BatchUpdateTypeUsedQuota, id, quota)
  834. addNewRecord(BatchUpdateTypeRequestCount, id, 1)
  835. return
  836. }
  837. updateUserUsedQuotaAndRequestCount(id, quota, 1)
  838. }
  839. func updateUserUsedQuotaAndRequestCount(id int, quota int, count int) {
  840. err := DB.Model(&User{}).Where("id = ?", id).Updates(
  841. map[string]interface{}{
  842. "used_quota": gorm.Expr("used_quota + ?", quota),
  843. "request_count": gorm.Expr("request_count + ?", count),
  844. },
  845. ).Error
  846. if err != nil {
  847. common.SysLog("failed to update user used quota and request count: " + err.Error())
  848. return
  849. }
  850. //// 更新缓存
  851. //if err := invalidateUserCache(id); err != nil {
  852. // common.SysError("failed to invalidate user cache: " + err.Error())
  853. //}
  854. }
  855. func updateUserUsedQuota(id int, quota int) {
  856. err := DB.Model(&User{}).Where("id = ?", id).Updates(
  857. map[string]interface{}{
  858. "used_quota": gorm.Expr("used_quota + ?", quota),
  859. },
  860. ).Error
  861. if err != nil {
  862. common.SysLog("failed to update user used quota: " + err.Error())
  863. }
  864. }
  865. func updateUserRequestCount(id int, count int) {
  866. err := DB.Model(&User{}).Where("id = ?", id).Update("request_count", gorm.Expr("request_count + ?", count)).Error
  867. if err != nil {
  868. common.SysLog("failed to update user request count: " + err.Error())
  869. }
  870. }
  871. // GetUsernameById gets username from Redis first, falls back to DB if needed
  872. func GetUsernameById(id int, fromDB bool) (username string, err error) {
  873. defer func() {
  874. // Update Redis cache asynchronously on successful DB read
  875. if shouldUpdateRedis(fromDB, err) {
  876. gopool.Go(func() {
  877. if err := updateUserNameCache(id, username); err != nil {
  878. common.SysLog("failed to update user name cache: " + err.Error())
  879. }
  880. })
  881. }
  882. }()
  883. if !fromDB && common.RedisEnabled {
  884. username, err := getUserNameCache(id)
  885. if err == nil {
  886. return username, nil
  887. }
  888. // Don't return error - fall through to DB
  889. }
  890. fromDB = true
  891. err = DB.Model(&User{}).Where("id = ?", id).Select("username").Find(&username).Error
  892. if err != nil {
  893. return "", err
  894. }
  895. return username, nil
  896. }
  897. func IsLinuxDOIdAlreadyTaken(linuxDOId string) bool {
  898. var user User
  899. err := DB.Unscoped().Where("linux_do_id = ?", linuxDOId).First(&user).Error
  900. return !errors.Is(err, gorm.ErrRecordNotFound)
  901. }
  902. func (user *User) FillUserByLinuxDOId() error {
  903. if user.LinuxDOId == "" {
  904. return errors.New("linux do id is empty")
  905. }
  906. err := DB.Where("linux_do_id = ?", user.LinuxDOId).First(user).Error
  907. return err
  908. }
  909. func RootUserExists() bool {
  910. var user User
  911. err := DB.Where("role = ?", common.RoleRootUser).First(&user).Error
  912. if err != nil {
  913. return false
  914. }
  915. return true
  916. }