user.go 13 KB

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