user.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. package model
  2. import (
  3. "errors"
  4. "one-api/common"
  5. "strings"
  6. )
  7. // User if you add sensitive fields, don't forget to clean them in setupLogin function.
  8. // Otherwise, the sensitive information will be saved on local storage in plain text!
  9. type User struct {
  10. Id int `json:"id"`
  11. Username string `json:"username" gorm:"unique;index" validate:"max=12"`
  12. Password string `json:"password" gorm:"not null;" validate:"min=8,max=20"`
  13. DisplayName string `json:"display_name" gorm:"index" validate:"max=20"`
  14. Role int `json:"role" gorm:"type:int;default:1"` // admin, common
  15. Status int `json:"status" gorm:"type:int;default:1"` // enabled, disabled
  16. Email string `json:"email" gorm:"index" validate:"max=50"`
  17. GitHubId string `json:"github_id" gorm:"column:github_id;index"`
  18. WeChatId string `json:"wechat_id" gorm:"column:wechat_id;index"`
  19. VerificationCode string `json:"verification_code" gorm:"-:all"` // this field is only for Email verification, don't save it to database!
  20. Balance int `json:"balance" gorm:"type:int;default:0"`
  21. AccessToken string `json:"access_token" gorm:"column:access_token;uniqueIndex"` // this token is for system management
  22. }
  23. func GetMaxUserId() int {
  24. var user User
  25. DB.Last(&user)
  26. return user.Id
  27. }
  28. func GetAllUsers(startIdx int, num int) (users []*User, err error) {
  29. err = DB.Order("id desc").Limit(num).Offset(startIdx).Omit("password").Find(&users).Error
  30. return users, err
  31. }
  32. func SearchUsers(keyword string) (users []*User, err error) {
  33. err = DB.Omit("password").Where("id = ? or username LIKE ? or email LIKE ? or display_name LIKE ?", keyword, keyword+"%", keyword+"%", keyword+"%").Find(&users).Error
  34. return users, err
  35. }
  36. func GetUserById(id int, selectAll bool) (*User, error) {
  37. if id == 0 {
  38. return nil, errors.New("id 为空!")
  39. }
  40. user := User{Id: id}
  41. var err error = nil
  42. if selectAll {
  43. err = DB.First(&user, "id = ?", id).Error
  44. } else {
  45. err = DB.Omit("password").First(&user, "id = ?", id).Error
  46. }
  47. return &user, err
  48. }
  49. func DeleteUserById(id int) (err error) {
  50. if id == 0 {
  51. return errors.New("id 为空!")
  52. }
  53. user := User{Id: id}
  54. return user.Delete()
  55. }
  56. func (user *User) Insert() error {
  57. var err error
  58. if user.Password != "" {
  59. user.Password, err = common.Password2Hash(user.Password)
  60. if err != nil {
  61. return err
  62. }
  63. }
  64. err = DB.Create(user).Error
  65. return err
  66. }
  67. func (user *User) Update(updatePassword bool) error {
  68. var err error
  69. if updatePassword {
  70. user.Password, err = common.Password2Hash(user.Password)
  71. if err != nil {
  72. return err
  73. }
  74. }
  75. err = DB.Model(user).Updates(user).Error
  76. return err
  77. }
  78. func (user *User) Delete() error {
  79. if user.Id == 0 {
  80. return errors.New("id 为空!")
  81. }
  82. err := DB.Delete(user).Error
  83. return err
  84. }
  85. // ValidateAndFill check password & user status
  86. func (user *User) ValidateAndFill() (err error) {
  87. // When querying with struct, GORM will only query with non-zero fields,
  88. // that means if your field’s value is 0, '', false or other zero values,
  89. // it won’t be used to build query conditions
  90. password := user.Password
  91. if user.Username == "" || password == "" {
  92. return errors.New("用户名或密码为空")
  93. }
  94. DB.Where(User{Username: user.Username}).First(user)
  95. okay := common.ValidatePasswordAndHash(password, user.Password)
  96. if !okay || user.Status != common.UserStatusEnabled {
  97. return errors.New("用户名或密码错误,或用户已被封禁")
  98. }
  99. return nil
  100. }
  101. func (user *User) FillUserById() error {
  102. if user.Id == 0 {
  103. return errors.New("id 为空!")
  104. }
  105. DB.Where(User{Id: user.Id}).First(user)
  106. return nil
  107. }
  108. func (user *User) FillUserByEmail() error {
  109. if user.Email == "" {
  110. return errors.New("email 为空!")
  111. }
  112. DB.Where(User{Email: user.Email}).First(user)
  113. return nil
  114. }
  115. func (user *User) FillUserByGitHubId() error {
  116. if user.GitHubId == "" {
  117. return errors.New("GitHub id 为空!")
  118. }
  119. DB.Where(User{GitHubId: user.GitHubId}).First(user)
  120. return nil
  121. }
  122. func (user *User) FillUserByWeChatId() error {
  123. if user.WeChatId == "" {
  124. return errors.New("WeChat id 为空!")
  125. }
  126. DB.Where(User{WeChatId: user.WeChatId}).First(user)
  127. return nil
  128. }
  129. func (user *User) FillUserByUsername() error {
  130. if user.Username == "" {
  131. return errors.New("username 为空!")
  132. }
  133. DB.Where(User{Username: user.Username}).First(user)
  134. return nil
  135. }
  136. func IsEmailAlreadyTaken(email string) bool {
  137. return DB.Where("email = ?", email).Find(&User{}).RowsAffected == 1
  138. }
  139. func IsWeChatIdAlreadyTaken(wechatId string) bool {
  140. return DB.Where("wechat_id = ?", wechatId).Find(&User{}).RowsAffected == 1
  141. }
  142. func IsGitHubIdAlreadyTaken(githubId string) bool {
  143. return DB.Where("github_id = ?", githubId).Find(&User{}).RowsAffected == 1
  144. }
  145. func IsUsernameAlreadyTaken(username string) bool {
  146. return DB.Where("username = ?", username).Find(&User{}).RowsAffected == 1
  147. }
  148. func ResetUserPasswordByEmail(email string, password string) error {
  149. if email == "" || password == "" {
  150. return errors.New("邮箱地址或密码为空!")
  151. }
  152. hashedPassword, err := common.Password2Hash(password)
  153. if err != nil {
  154. return err
  155. }
  156. err = DB.Model(&User{}).Where("email = ?", email).Update("password", hashedPassword).Error
  157. return err
  158. }
  159. func IsAdmin(userId int) bool {
  160. if userId == 0 {
  161. return false
  162. }
  163. var user User
  164. err := DB.Where("id = ?", userId).Select("role").Find(&user).Error
  165. if err != nil {
  166. common.SysError("No such user " + err.Error())
  167. return false
  168. }
  169. return user.Role >= common.RoleAdminUser
  170. }
  171. func ValidateAccessToken(token string) (user *User) {
  172. if token == "" {
  173. return nil
  174. }
  175. token = strings.Replace(token, "Bearer ", "", 1)
  176. user = &User{}
  177. if DB.Where("access_token = ?", token).First(user).RowsAffected == 1 {
  178. return user
  179. }
  180. return nil
  181. }