user.go 16 KB

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