user.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. package model
  2. import (
  3. "errors"
  4. "fmt"
  5. "one-api/common"
  6. "strconv"
  7. "strings"
  8. "time"
  9. "gorm.io/gorm"
  10. )
  11. // User if you add sensitive fields, don't forget to clean them in setupLogin function.
  12. // Otherwise, the sensitive information will be saved on local storage in plain text!
  13. type User struct {
  14. Id int `json:"id"`
  15. Username string `json:"username" gorm:"unique;index" validate:"max=12"`
  16. Password string `json:"password" gorm:"not null;" validate:"min=8,max=20"`
  17. DisplayName string `json:"display_name" gorm:"index" validate:"max=20"`
  18. Role int `json:"role" gorm:"type:int;default:1"` // admin, common
  19. Status int `json:"status" gorm:"type:int;default:1"` // enabled, disabled
  20. Email string `json:"email" gorm:"index" validate:"max=50"`
  21. GitHubId string `json:"github_id" gorm:"column:github_id;index"`
  22. WeChatId string `json:"wechat_id" gorm:"column:wechat_id;index"`
  23. TelegramId string `json:"telegram_id" gorm:"column:telegram_id;index"`
  24. VerificationCode string `json:"verification_code" gorm:"-:all"` // this field is only for Email verification, don't save it to database!
  25. AccessToken *string `json:"access_token" gorm:"type:char(32);column:access_token;uniqueIndex"` // this token is for system management
  26. Quota int `json:"quota" gorm:"type:int;default:0"`
  27. UsedQuota int `json:"used_quota" gorm:"type:int;default:0;column:used_quota"` // used quota
  28. RequestCount int `json:"request_count" gorm:"type:int;default:0;"` // request number
  29. Group string `json:"group" gorm:"type:varchar(64);default:'default'"`
  30. AffCode string `json:"aff_code" gorm:"type:varchar(32);column:aff_code;uniqueIndex"`
  31. AffCount int `json:"aff_count" gorm:"type:int;default:0;column:aff_count"`
  32. AffQuota int `json:"aff_quota" gorm:"type:int;default:0;column:aff_quota"` // 邀请剩余额度
  33. AffHistoryQuota int `json:"aff_history_quota" gorm:"type:int;default:0;column:aff_history"` // 邀请历史额度
  34. InviterId int `json:"inviter_id" gorm:"type:int;column:inviter_id;index"`
  35. DeletedAt gorm.DeletedAt `gorm:"index"`
  36. LinuxDOId string `json:"linux_do_id" gorm:"column:linux_do_id;index"`
  37. }
  38. func (user *User) GetAccessToken() string {
  39. if user.AccessToken == nil {
  40. return ""
  41. }
  42. return *user.AccessToken
  43. }
  44. func (user *User) SetAccessToken(token string) {
  45. user.AccessToken = &token
  46. }
  47. // CheckUserExistOrDeleted check if user exist or deleted, if not exist, return false, nil, if deleted or exist, return true, nil
  48. func CheckUserExistOrDeleted(username string, email string) (bool, error) {
  49. var user User
  50. // err := DB.Unscoped().First(&user, "username = ? or email = ?", username, email).Error
  51. // check email if empty
  52. var err error
  53. if email == "" {
  54. err = DB.Unscoped().First(&user, "username = ?", username).Error
  55. } else {
  56. err = DB.Unscoped().First(&user, "username = ? or email = ?", username, email).Error
  57. }
  58. if err != nil {
  59. if errors.Is(err, gorm.ErrRecordNotFound) {
  60. // not exist, return false, nil
  61. return false, nil
  62. }
  63. // other error, return false, err
  64. return false, err
  65. }
  66. // exist, return true, nil
  67. return true, nil
  68. }
  69. func GetMaxUserId() int {
  70. var user User
  71. DB.Last(&user)
  72. return user.Id
  73. }
  74. func GetAllUsers(startIdx int, num int) (users []*User, err error) {
  75. err = DB.Unscoped().Order("id desc").Limit(num).Offset(startIdx).Omit("password").Find(&users).Error
  76. return users, err
  77. }
  78. func SearchUsers(keyword string, group string) ([]*User, error) {
  79. var users []*User
  80. var err error
  81. groupCol := "`group`"
  82. if common.UsingPostgreSQL {
  83. groupCol = `"group"`
  84. }
  85. // 尝试将关键字转换为整数ID
  86. keywordInt, err := strconv.Atoi(keyword)
  87. if err == nil {
  88. // 如果转换成功,按照ID和可选的组别搜索用户
  89. query := DB.Unscoped().Omit("password").Where("id = ?", keywordInt)
  90. if group != "" {
  91. query = query.Where(groupCol+" = ?", group) // 使用反引号包围group
  92. }
  93. err = query.Find(&users).Error
  94. if err != nil || len(users) > 0 {
  95. return users, err
  96. }
  97. }
  98. err = nil
  99. query := DB.Unscoped().Omit("password")
  100. likeCondition := "username LIKE ? OR email LIKE ? OR display_name LIKE ?"
  101. if group != "" {
  102. query = query.Where("("+likeCondition+") AND "+groupCol+" = ?", "%"+keyword+"%", "%"+keyword+"%", "%"+keyword+"%", group)
  103. } else {
  104. query = query.Where(likeCondition, "%"+keyword+"%", "%"+keyword+"%", "%"+keyword+"%")
  105. }
  106. err = query.Find(&users).Error
  107. return users, err
  108. }
  109. func GetUserById(id int, selectAll bool) (*User, error) {
  110. if id == 0 {
  111. return nil, errors.New("id 为空!")
  112. }
  113. user := User{Id: id}
  114. var err error = nil
  115. if selectAll {
  116. err = DB.First(&user, "id = ?", id).Error
  117. } else {
  118. err = DB.Omit("password").First(&user, "id = ?", id).Error
  119. }
  120. return &user, err
  121. }
  122. func GetUserIdByAffCode(affCode string) (int, error) {
  123. if affCode == "" {
  124. return 0, errors.New("affCode 为空!")
  125. }
  126. var user User
  127. err := DB.Select("id").First(&user, "aff_code = ?", affCode).Error
  128. return user.Id, err
  129. }
  130. func DeleteUserById(id int) (err error) {
  131. if id == 0 {
  132. return errors.New("id 为空!")
  133. }
  134. user := User{Id: id}
  135. return user.Delete()
  136. }
  137. func HardDeleteUserById(id int) error {
  138. if id == 0 {
  139. return errors.New("id 为空!")
  140. }
  141. err := DB.Unscoped().Delete(&User{}, "id = ?", id).Error
  142. return err
  143. }
  144. func inviteUser(inviterId int) (err error) {
  145. user, err := GetUserById(inviterId, true)
  146. if err != nil {
  147. return err
  148. }
  149. user.AffCount++
  150. user.AffQuota += common.QuotaForInviter
  151. user.AffHistoryQuota += common.QuotaForInviter
  152. return DB.Save(user).Error
  153. }
  154. func (user *User) TransferAffQuotaToQuota(quota int) error {
  155. // 检查quota是否小于最小额度
  156. if float64(quota) < common.QuotaPerUnit {
  157. return fmt.Errorf("转移额度最小为%s!", common.LogQuota(int(common.QuotaPerUnit)))
  158. }
  159. // 开始数据库事务
  160. tx := DB.Begin()
  161. if tx.Error != nil {
  162. return tx.Error
  163. }
  164. defer tx.Rollback() // 确保在函数退出时事务能回滚
  165. // 加锁查询用户以确保数据一致性
  166. err := tx.Set("gorm:query_option", "FOR UPDATE").First(&user, user.Id).Error
  167. if err != nil {
  168. return err
  169. }
  170. // 再次检查用户的AffQuota是否足够
  171. if user.AffQuota < quota {
  172. return errors.New("邀请额度不足!")
  173. }
  174. // 更新用户额度
  175. user.AffQuota -= quota
  176. user.Quota += quota
  177. // 保存用户状态
  178. if err := tx.Save(user).Error; err != nil {
  179. return err
  180. }
  181. // 提交事务
  182. return tx.Commit().Error
  183. }
  184. func (user *User) Insert(inviterId int) error {
  185. var err error
  186. if user.Password != "" {
  187. user.Password, err = common.Password2Hash(user.Password)
  188. if err != nil {
  189. return err
  190. }
  191. }
  192. user.Quota = common.QuotaForNewUser
  193. //user.SetAccessToken(common.GetUUID())
  194. user.AffCode = common.GetRandomString(4)
  195. result := DB.Create(user)
  196. if result.Error != nil {
  197. return result.Error
  198. }
  199. if common.QuotaForNewUser > 0 {
  200. RecordLog(user.Id, LogTypeSystem, fmt.Sprintf("新用户注册赠送 %s", common.LogQuota(common.QuotaForNewUser)))
  201. }
  202. if inviterId != 0 {
  203. if common.QuotaForInvitee > 0 {
  204. _ = IncreaseUserQuota(user.Id, common.QuotaForInvitee)
  205. RecordLog(user.Id, LogTypeSystem, fmt.Sprintf("使用邀请码赠送 %s", common.LogQuota(common.QuotaForInvitee)))
  206. }
  207. if common.QuotaForInviter > 0 {
  208. //_ = IncreaseUserQuota(inviterId, common.QuotaForInviter)
  209. RecordLog(inviterId, LogTypeSystem, fmt.Sprintf("邀请用户赠送 %s", common.LogQuota(common.QuotaForInviter)))
  210. _ = inviteUser(inviterId)
  211. }
  212. }
  213. return nil
  214. }
  215. func (user *User) Update(updatePassword bool) error {
  216. var err error
  217. if updatePassword {
  218. user.Password, err = common.Password2Hash(user.Password)
  219. if err != nil {
  220. return err
  221. }
  222. }
  223. newUser := *user
  224. DB.First(&user, user.Id)
  225. err = DB.Model(user).Updates(newUser).Error
  226. if err == nil {
  227. if common.RedisEnabled {
  228. _ = common.RedisSet(fmt.Sprintf("user_group:%d", user.Id), user.Group, time.Duration(UserId2GroupCacheSeconds)*time.Second)
  229. _ = common.RedisSet(fmt.Sprintf("user_quota:%d", user.Id), strconv.Itoa(user.Quota), time.Duration(UserId2QuotaCacheSeconds)*time.Second)
  230. }
  231. }
  232. return err
  233. }
  234. func (user *User) Edit(updatePassword bool) error {
  235. var err error
  236. if updatePassword {
  237. user.Password, err = common.Password2Hash(user.Password)
  238. if err != nil {
  239. return err
  240. }
  241. }
  242. newUser := *user
  243. updates := map[string]interface{}{
  244. "username": newUser.Username,
  245. "display_name": newUser.DisplayName,
  246. "group": newUser.Group,
  247. "quota": newUser.Quota,
  248. }
  249. if updatePassword {
  250. updates["password"] = newUser.Password
  251. }
  252. DB.First(&user, user.Id)
  253. err = DB.Model(user).Updates(updates).Error
  254. if err == nil {
  255. if common.RedisEnabled {
  256. _ = common.RedisSet(fmt.Sprintf("user_group:%d", user.Id), user.Group, time.Duration(UserId2GroupCacheSeconds)*time.Second)
  257. _ = common.RedisSet(fmt.Sprintf("user_quota:%d", user.Id), strconv.Itoa(user.Quota), time.Duration(UserId2QuotaCacheSeconds)*time.Second)
  258. }
  259. }
  260. return err
  261. }
  262. func (user *User) Delete() error {
  263. if user.Id == 0 {
  264. return errors.New("id 为空!")
  265. }
  266. err := DB.Delete(user).Error
  267. return err
  268. }
  269. func (user *User) HardDelete() error {
  270. if user.Id == 0 {
  271. return errors.New("id 为空!")
  272. }
  273. err := DB.Unscoped().Delete(user).Error
  274. return err
  275. }
  276. // ValidateAndFill check password & user status
  277. func (user *User) ValidateAndFill() (err error) {
  278. // When querying with struct, GORM will only query with non-zero fields,
  279. // that means if your field’s value is 0, '', false or other zero values,
  280. // it won’t be used to build query conditions
  281. password := user.Password
  282. username := strings.TrimSpace(user.Username)
  283. if username == "" || password == "" {
  284. return errors.New("用户名或密码为空")
  285. }
  286. // find buy username or email
  287. DB.Where("username = ? OR email = ?", username, username).First(user)
  288. okay := common.ValidatePasswordAndHash(password, user.Password)
  289. if !okay || user.Status != common.UserStatusEnabled {
  290. return errors.New("用户名或密码错误,或用户已被封禁")
  291. }
  292. return nil
  293. }
  294. func (user *User) FillUserById() error {
  295. if user.Id == 0 {
  296. return errors.New("id 为空!")
  297. }
  298. DB.Where(User{Id: user.Id}).First(user)
  299. return nil
  300. }
  301. func (user *User) FillUserByEmail() error {
  302. if user.Email == "" {
  303. return errors.New("email 为空!")
  304. }
  305. DB.Where(User{Email: user.Email}).First(user)
  306. return nil
  307. }
  308. func (user *User) FillUserByGitHubId() error {
  309. if user.GitHubId == "" {
  310. return errors.New("GitHub id 为空!")
  311. }
  312. DB.Where(User{GitHubId: user.GitHubId}).First(user)
  313. return nil
  314. }
  315. func (user *User) FillUserByWeChatId() error {
  316. if user.WeChatId == "" {
  317. return errors.New("WeChat id 为空!")
  318. }
  319. DB.Where(User{WeChatId: user.WeChatId}).First(user)
  320. return nil
  321. }
  322. func (user *User) FillUserByTelegramId() error {
  323. if user.TelegramId == "" {
  324. return errors.New("Telegram id 为空!")
  325. }
  326. err := DB.Where(User{TelegramId: user.TelegramId}).First(user).Error
  327. if errors.Is(err, gorm.ErrRecordNotFound) {
  328. return errors.New("该 Telegram 账户未绑定")
  329. }
  330. return nil
  331. }
  332. func IsEmailAlreadyTaken(email string) bool {
  333. return DB.Unscoped().Where("email = ?", email).Find(&User{}).RowsAffected == 1
  334. }
  335. func IsWeChatIdAlreadyTaken(wechatId string) bool {
  336. return DB.Unscoped().Where("wechat_id = ?", wechatId).Find(&User{}).RowsAffected == 1
  337. }
  338. func IsGitHubIdAlreadyTaken(githubId string) bool {
  339. return DB.Unscoped().Where("github_id = ?", githubId).Find(&User{}).RowsAffected == 1
  340. }
  341. func IsTelegramIdAlreadyTaken(telegramId string) bool {
  342. return DB.Unscoped().Where("telegram_id = ?", telegramId).Find(&User{}).RowsAffected == 1
  343. }
  344. func ResetUserPasswordByEmail(email string, password string) error {
  345. if email == "" || password == "" {
  346. return errors.New("邮箱地址或密码为空!")
  347. }
  348. hashedPassword, err := common.Password2Hash(password)
  349. if err != nil {
  350. return err
  351. }
  352. err = DB.Model(&User{}).Where("email = ?", email).Update("password", hashedPassword).Error
  353. return err
  354. }
  355. func IsAdmin(userId int) bool {
  356. if userId == 0 {
  357. return false
  358. }
  359. var user User
  360. err := DB.Where("id = ?", userId).Select("role").Find(&user).Error
  361. if err != nil {
  362. common.SysError("no such user " + err.Error())
  363. return false
  364. }
  365. return user.Role >= common.RoleAdminUser
  366. }
  367. func IsUserEnabled(userId int) (bool, error) {
  368. if userId == 0 {
  369. return false, errors.New("user id is empty")
  370. }
  371. var user User
  372. err := DB.Where("id = ?", userId).Select("status").Find(&user).Error
  373. if err != nil {
  374. return false, err
  375. }
  376. return user.Status == common.UserStatusEnabled, nil
  377. }
  378. func ValidateAccessToken(token string) (user *User) {
  379. if token == "" {
  380. return nil
  381. }
  382. token = strings.Replace(token, "Bearer ", "", 1)
  383. user = &User{}
  384. if DB.Where("access_token = ?", token).First(user).RowsAffected == 1 {
  385. return user
  386. }
  387. return nil
  388. }
  389. func GetUserQuota(id int) (quota int, err error) {
  390. err = DB.Model(&User{}).Where("id = ?", id).Select("quota").Find(&quota).Error
  391. if err != nil {
  392. if common.RedisEnabled {
  393. go cacheSetUserQuota(id, quota)
  394. }
  395. }
  396. return quota, err
  397. }
  398. func GetUserUsedQuota(id int) (quota int, err error) {
  399. err = DB.Model(&User{}).Where("id = ?", id).Select("used_quota").Find(&quota).Error
  400. return quota, err
  401. }
  402. func GetUserEmail(id int) (email string, err error) {
  403. err = DB.Model(&User{}).Where("id = ?", id).Select("email").Find(&email).Error
  404. return email, err
  405. }
  406. func GetUserGroup(id int) (group string, err error) {
  407. groupCol := "`group`"
  408. if common.UsingPostgreSQL {
  409. groupCol = `"group"`
  410. }
  411. err = DB.Model(&User{}).Where("id = ?", id).Select(groupCol).Find(&group).Error
  412. return group, err
  413. }
  414. func IncreaseUserQuota(id int, quota int) (err error) {
  415. if quota < 0 {
  416. return errors.New("quota 不能为负数!")
  417. }
  418. if common.BatchUpdateEnabled {
  419. addNewRecord(BatchUpdateTypeUserQuota, id, quota)
  420. return nil
  421. }
  422. return increaseUserQuota(id, quota)
  423. }
  424. func increaseUserQuota(id int, quota int) (err error) {
  425. err = DB.Model(&User{}).Where("id = ?", id).Update("quota", gorm.Expr("quota + ?", quota)).Error
  426. return err
  427. }
  428. func DecreaseUserQuota(id int, quota int) (err error) {
  429. if quota < 0 {
  430. return errors.New("quota 不能为负数!")
  431. }
  432. if common.BatchUpdateEnabled {
  433. addNewRecord(BatchUpdateTypeUserQuota, id, -quota)
  434. return nil
  435. }
  436. return decreaseUserQuota(id, quota)
  437. }
  438. func decreaseUserQuota(id int, quota int) (err error) {
  439. err = DB.Model(&User{}).Where("id = ?", id).Update("quota", gorm.Expr("quota - ?", quota)).Error
  440. return err
  441. }
  442. func GetRootUserEmail() (email string) {
  443. DB.Model(&User{}).Where("role = ?", common.RoleRootUser).Select("email").Find(&email)
  444. return email
  445. }
  446. func UpdateUserUsedQuotaAndRequestCount(id int, quota int) {
  447. if common.BatchUpdateEnabled {
  448. addNewRecord(BatchUpdateTypeUsedQuota, id, quota)
  449. addNewRecord(BatchUpdateTypeRequestCount, id, 1)
  450. return
  451. }
  452. updateUserUsedQuotaAndRequestCount(id, quota, 1)
  453. }
  454. func updateUserUsedQuotaAndRequestCount(id int, quota int, count int) {
  455. err := DB.Model(&User{}).Where("id = ?", id).Updates(
  456. map[string]interface{}{
  457. "used_quota": gorm.Expr("used_quota + ?", quota),
  458. "request_count": gorm.Expr("request_count + ?", count),
  459. },
  460. ).Error
  461. if err != nil {
  462. common.SysError("failed to update user used quota and request count: " + err.Error())
  463. }
  464. }
  465. func updateUserUsedQuota(id int, quota int) {
  466. err := DB.Model(&User{}).Where("id = ?", id).Updates(
  467. map[string]interface{}{
  468. "used_quota": gorm.Expr("used_quota + ?", quota),
  469. },
  470. ).Error
  471. if err != nil {
  472. common.SysError("failed to update user used quota: " + err.Error())
  473. }
  474. }
  475. func updateUserRequestCount(id int, count int) {
  476. err := DB.Model(&User{}).Where("id = ?", id).Update("request_count", gorm.Expr("request_count + ?", count)).Error
  477. if err != nil {
  478. common.SysError("failed to update user request count: " + err.Error())
  479. }
  480. }
  481. func GetUsernameById(id int) (username string, err error) {
  482. err = DB.Model(&User{}).Where("id = ?", id).Select("username").Find(&username).Error
  483. return username, err
  484. }
  485. func IsLinuxDOIdAlreadyTaken(linuxDOId string) bool {
  486. var user User
  487. err := DB.Unscoped().Where("linux_do_id = ?", linuxDOId).First(&user).Error
  488. return !errors.Is(err, gorm.ErrRecordNotFound)
  489. }
  490. func (u *User) FillUserByLinuxDOId() error {
  491. if u.LinuxDOId == "" {
  492. return errors.New("linux do id is empty")
  493. }
  494. err := DB.Where("linux_do_id = ?", u.LinuxDOId).First(u).Error
  495. return err
  496. }