user.go 16 KB

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