user.go 13 KB

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