user.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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. }
  28. func GetMaxUserId() int {
  29. var user User
  30. DB.Last(&user)
  31. return user.Id
  32. }
  33. func GetAllUsers(startIdx int, num int) (users []*User, err error) {
  34. err = DB.Order("id desc").Limit(num).Offset(startIdx).Omit("password").Find(&users).Error
  35. return users, err
  36. }
  37. func SearchUsers(keyword string) (users []*User, err error) {
  38. err = DB.Omit("password").Where("id = ? or username LIKE ? or email LIKE ? or display_name LIKE ?", keyword, keyword+"%", keyword+"%", keyword+"%").Find(&users).Error
  39. return users, err
  40. }
  41. func GetUserById(id int, selectAll bool) (*User, error) {
  42. if id == 0 {
  43. return nil, errors.New("id 为空!")
  44. }
  45. user := User{Id: id}
  46. var err error = nil
  47. if selectAll {
  48. err = DB.First(&user, "id = ?", id).Error
  49. } else {
  50. err = DB.Omit("password").First(&user, "id = ?", id).Error
  51. }
  52. return &user, err
  53. }
  54. func DeleteUserById(id int) (err error) {
  55. if id == 0 {
  56. return errors.New("id 为空!")
  57. }
  58. user := User{Id: id}
  59. return user.Delete()
  60. }
  61. func (user *User) Insert() error {
  62. var err error
  63. if user.Password != "" {
  64. user.Password, err = common.Password2Hash(user.Password)
  65. if err != nil {
  66. return err
  67. }
  68. }
  69. user.Quota = common.QuotaForNewUser
  70. user.AccessToken = common.GetUUID()
  71. result := DB.Create(user)
  72. if result.Error != nil {
  73. return result.Error
  74. }
  75. if common.QuotaForNewUser > 0 {
  76. RecordLog(user.Id, LogTypeSystem, fmt.Sprintf("新用户注册赠送 %d 点额度", common.QuotaForNewUser))
  77. }
  78. return nil
  79. }
  80. func (user *User) Update(updatePassword bool) error {
  81. var err error
  82. if updatePassword {
  83. user.Password, err = common.Password2Hash(user.Password)
  84. if err != nil {
  85. return err
  86. }
  87. }
  88. err = DB.Model(user).Updates(user).Error
  89. return err
  90. }
  91. func (user *User) Delete() error {
  92. if user.Id == 0 {
  93. return errors.New("id 为空!")
  94. }
  95. err := DB.Delete(user).Error
  96. return err
  97. }
  98. // ValidateAndFill check password & user status
  99. func (user *User) ValidateAndFill() (err error) {
  100. // When querying with struct, GORM will only query with non-zero fields,
  101. // that means if your field’s value is 0, '', false or other zero values,
  102. // it won’t be used to build query conditions
  103. password := user.Password
  104. if user.Username == "" || password == "" {
  105. return errors.New("用户名或密码为空")
  106. }
  107. DB.Where(User{Username: user.Username}).First(user)
  108. okay := common.ValidatePasswordAndHash(password, user.Password)
  109. if !okay || user.Status != common.UserStatusEnabled {
  110. return errors.New("用户名或密码错误,或用户已被封禁")
  111. }
  112. return nil
  113. }
  114. func (user *User) FillUserById() error {
  115. if user.Id == 0 {
  116. return errors.New("id 为空!")
  117. }
  118. DB.Where(User{Id: user.Id}).First(user)
  119. return nil
  120. }
  121. func (user *User) FillUserByEmail() error {
  122. if user.Email == "" {
  123. return errors.New("email 为空!")
  124. }
  125. DB.Where(User{Email: user.Email}).First(user)
  126. return nil
  127. }
  128. func (user *User) FillUserByGitHubId() error {
  129. if user.GitHubId == "" {
  130. return errors.New("GitHub id 为空!")
  131. }
  132. DB.Where(User{GitHubId: user.GitHubId}).First(user)
  133. return nil
  134. }
  135. func (user *User) FillUserByWeChatId() error {
  136. if user.WeChatId == "" {
  137. return errors.New("WeChat id 为空!")
  138. }
  139. DB.Where(User{WeChatId: user.WeChatId}).First(user)
  140. return nil
  141. }
  142. func (user *User) FillUserByUsername() error {
  143. if user.Username == "" {
  144. return errors.New("username 为空!")
  145. }
  146. DB.Where(User{Username: user.Username}).First(user)
  147. return nil
  148. }
  149. func IsEmailAlreadyTaken(email string) bool {
  150. return DB.Where("email = ?", email).Find(&User{}).RowsAffected == 1
  151. }
  152. func IsWeChatIdAlreadyTaken(wechatId string) bool {
  153. return DB.Where("wechat_id = ?", wechatId).Find(&User{}).RowsAffected == 1
  154. }
  155. func IsGitHubIdAlreadyTaken(githubId string) bool {
  156. return DB.Where("github_id = ?", githubId).Find(&User{}).RowsAffected == 1
  157. }
  158. func IsUsernameAlreadyTaken(username string) bool {
  159. return DB.Where("username = ?", username).Find(&User{}).RowsAffected == 1
  160. }
  161. func ResetUserPasswordByEmail(email string, password string) error {
  162. if email == "" || password == "" {
  163. return errors.New("邮箱地址或密码为空!")
  164. }
  165. hashedPassword, err := common.Password2Hash(password)
  166. if err != nil {
  167. return err
  168. }
  169. err = DB.Model(&User{}).Where("email = ?", email).Update("password", hashedPassword).Error
  170. return err
  171. }
  172. func IsAdmin(userId int) bool {
  173. if userId == 0 {
  174. return false
  175. }
  176. var user User
  177. err := DB.Where("id = ?", userId).Select("role").Find(&user).Error
  178. if err != nil {
  179. common.SysError("No such user " + err.Error())
  180. return false
  181. }
  182. return user.Role >= common.RoleAdminUser
  183. }
  184. func IsUserEnabled(userId int) bool {
  185. if userId == 0 {
  186. return false
  187. }
  188. var user User
  189. err := DB.Where("id = ?", userId).Select("status").Find(&user).Error
  190. if err != nil {
  191. common.SysError("No such user " + err.Error())
  192. return false
  193. }
  194. return user.Status == common.UserStatusEnabled
  195. }
  196. func ValidateAccessToken(token string) (user *User) {
  197. if token == "" {
  198. return nil
  199. }
  200. token = strings.Replace(token, "Bearer ", "", 1)
  201. user = &User{}
  202. if DB.Where("access_token = ?", token).First(user).RowsAffected == 1 {
  203. return user
  204. }
  205. return nil
  206. }
  207. func GetUserQuota(id int) (quota int, err error) {
  208. err = DB.Model(&User{}).Where("id = ?", id).Select("quota").Find(&quota).Error
  209. return quota, err
  210. }
  211. func GetUserEmail(id int) (email string, err error) {
  212. err = DB.Model(&User{}).Where("id = ?", id).Select("email").Find(&email).Error
  213. return email, err
  214. }
  215. func GetUserGroup(id int) (group string, err error) {
  216. err = DB.Model(&User{}).Where("id = ?", id).Select("`group`").Find(&group).Error
  217. return group, err
  218. }
  219. func IncreaseUserQuota(id int, quota int) (err error) {
  220. if quota < 0 {
  221. return errors.New("quota 不能为负数!")
  222. }
  223. err = DB.Model(&User{}).Where("id = ?", id).Update("quota", gorm.Expr("quota + ?", quota)).Error
  224. return err
  225. }
  226. func DecreaseUserQuota(id int, quota int) (err error) {
  227. if quota < 0 {
  228. return errors.New("quota 不能为负数!")
  229. }
  230. err = DB.Model(&User{}).Where("id = ?", id).Update("quota", gorm.Expr("quota - ?", quota)).Error
  231. return err
  232. }
  233. func GetRootUserEmail() (email string) {
  234. DB.Model(&User{}).Where("role = ?", common.RoleRootUser).Select("email").Find(&email)
  235. return email
  236. }
  237. func UpdateUserUsedQuotaAndRequestCount(id int, quota int) {
  238. err := DB.Model(&User{}).Where("id = ?", id).Updates(
  239. map[string]interface{}{
  240. "used_quota": gorm.Expr("used_quota + ?", quota),
  241. "request_count": gorm.Expr("request_count + ?", 1),
  242. },
  243. ).Error
  244. if err != nil {
  245. common.SysError("Failed to update user used quota and request count: " + err.Error())
  246. }
  247. }