user.go 7.0 KB

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