user.go 13 KB

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