user.go 16 KB

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