user.go 14 KB

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