user.go 9.2 KB

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