user.go 14 KB

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