user.go 12 KB

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