user.go 10 KB

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