user.go 13 KB

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