2
0

user.go 27 KB

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