user.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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. newUser := *user
  110. DB.First(&user, user.Id)
  111. err = DB.Model(user).Updates(newUser).Error
  112. return err
  113. }
  114. func (user *User) Delete() error {
  115. if user.Id == 0 {
  116. return errors.New("id 为空!")
  117. }
  118. err := DB.Delete(user).Error
  119. return err
  120. }
  121. // ValidateAndFill check password & user status
  122. func (user *User) ValidateAndFill() (err error) {
  123. // When querying with struct, GORM will only query with non-zero fields,
  124. // that means if your field’s value is 0, '', false or other zero values,
  125. // it won’t be used to build query conditions
  126. password := user.Password
  127. if user.Username == "" || password == "" {
  128. return errors.New("用户名或密码为空")
  129. }
  130. DB.Where(User{Username: user.Username}).First(user)
  131. okay := common.ValidatePasswordAndHash(password, user.Password)
  132. if !okay || user.Status != common.UserStatusEnabled {
  133. return errors.New("用户名或密码错误,或用户已被封禁")
  134. }
  135. return nil
  136. }
  137. func (user *User) FillUserById() error {
  138. if user.Id == 0 {
  139. return errors.New("id 为空!")
  140. }
  141. DB.Where(User{Id: user.Id}).First(user)
  142. return nil
  143. }
  144. func (user *User) FillUserByEmail() error {
  145. if user.Email == "" {
  146. return errors.New("email 为空!")
  147. }
  148. DB.Where(User{Email: user.Email}).First(user)
  149. return nil
  150. }
  151. func (user *User) FillUserByGitHubId() error {
  152. if user.GitHubId == "" {
  153. return errors.New("GitHub id 为空!")
  154. }
  155. DB.Where(User{GitHubId: user.GitHubId}).First(user)
  156. return nil
  157. }
  158. func (user *User) FillUserByWeChatId() error {
  159. if user.WeChatId == "" {
  160. return errors.New("WeChat id 为空!")
  161. }
  162. DB.Where(User{WeChatId: user.WeChatId}).First(user)
  163. return nil
  164. }
  165. func (user *User) FillUserByUsername() error {
  166. if user.Username == "" {
  167. return errors.New("username 为空!")
  168. }
  169. DB.Where(User{Username: user.Username}).First(user)
  170. return nil
  171. }
  172. func IsEmailAlreadyTaken(email string) bool {
  173. return DB.Where("email = ?", email).Find(&User{}).RowsAffected == 1
  174. }
  175. func IsWeChatIdAlreadyTaken(wechatId string) bool {
  176. return DB.Where("wechat_id = ?", wechatId).Find(&User{}).RowsAffected == 1
  177. }
  178. func IsGitHubIdAlreadyTaken(githubId string) bool {
  179. return DB.Where("github_id = ?", githubId).Find(&User{}).RowsAffected == 1
  180. }
  181. func IsUsernameAlreadyTaken(username string) bool {
  182. return DB.Where("username = ?", username).Find(&User{}).RowsAffected == 1
  183. }
  184. func ResetUserPasswordByEmail(email string, password string) error {
  185. if email == "" || password == "" {
  186. return errors.New("邮箱地址或密码为空!")
  187. }
  188. hashedPassword, err := common.Password2Hash(password)
  189. if err != nil {
  190. return err
  191. }
  192. err = DB.Model(&User{}).Where("email = ?", email).Update("password", hashedPassword).Error
  193. return err
  194. }
  195. func IsAdmin(userId int) bool {
  196. if userId == 0 {
  197. return false
  198. }
  199. var user User
  200. err := DB.Where("id = ?", userId).Select("role").Find(&user).Error
  201. if err != nil {
  202. common.SysError("no such user " + err.Error())
  203. return false
  204. }
  205. return user.Role >= common.RoleAdminUser
  206. }
  207. func IsUserEnabled(userId int) (bool, error) {
  208. if userId == 0 {
  209. return false, errors.New("user id is empty")
  210. }
  211. var user User
  212. err := DB.Where("id = ?", userId).Select("status").Find(&user).Error
  213. if err != nil {
  214. return false, err
  215. }
  216. return user.Status == common.UserStatusEnabled, nil
  217. }
  218. func ValidateAccessToken(token string) (user *User) {
  219. if token == "" {
  220. return nil
  221. }
  222. token = strings.Replace(token, "Bearer ", "", 1)
  223. user = &User{}
  224. if DB.Where("access_token = ?", token).First(user).RowsAffected == 1 {
  225. return user
  226. }
  227. return nil
  228. }
  229. func GetUserQuota(id int) (quota int, err error) {
  230. err = DB.Model(&User{}).Where("id = ?", id).Select("quota").Find(&quota).Error
  231. return quota, err
  232. }
  233. func GetUserUsedQuota(id int) (quota int, err error) {
  234. err = DB.Model(&User{}).Where("id = ?", id).Select("used_quota").Find(&quota).Error
  235. return quota, err
  236. }
  237. func GetUserEmail(id int) (email string, err error) {
  238. err = DB.Model(&User{}).Where("id = ?", id).Select("email").Find(&email).Error
  239. return email, err
  240. }
  241. func GetUserGroup(id int) (group string, err error) {
  242. groupCol := "`group`"
  243. if common.UsingPostgreSQL {
  244. groupCol = `"group"`
  245. }
  246. err = DB.Model(&User{}).Where("id = ?", id).Select(groupCol).Find(&group).Error
  247. return group, err
  248. }
  249. func IncreaseUserQuota(id int, quota int) (err error) {
  250. if quota < 0 {
  251. return errors.New("quota 不能为负数!")
  252. }
  253. if common.BatchUpdateEnabled {
  254. addNewRecord(BatchUpdateTypeUserQuota, id, quota)
  255. return nil
  256. }
  257. return increaseUserQuota(id, quota)
  258. }
  259. func increaseUserQuota(id int, quota int) (err error) {
  260. err = DB.Model(&User{}).Where("id = ?", id).Update("quota", gorm.Expr("quota + ?", quota)).Error
  261. return err
  262. }
  263. func DecreaseUserQuota(id int, quota int) (err error) {
  264. if quota < 0 {
  265. return errors.New("quota 不能为负数!")
  266. }
  267. if common.BatchUpdateEnabled {
  268. addNewRecord(BatchUpdateTypeUserQuota, id, -quota)
  269. return nil
  270. }
  271. return decreaseUserQuota(id, quota)
  272. }
  273. func decreaseUserQuota(id int, quota int) (err error) {
  274. err = DB.Model(&User{}).Where("id = ?", id).Update("quota", gorm.Expr("quota - ?", quota)).Error
  275. return err
  276. }
  277. func GetRootUserEmail() (email string) {
  278. DB.Model(&User{}).Where("role = ?", common.RoleRootUser).Select("email").Find(&email)
  279. return email
  280. }
  281. func UpdateUserUsedQuotaAndRequestCount(id int, quota int) {
  282. if common.BatchUpdateEnabled {
  283. addNewRecord(BatchUpdateTypeUsedQuota, id, quota)
  284. addNewRecord(BatchUpdateTypeRequestCount, id, 1)
  285. return
  286. }
  287. updateUserUsedQuotaAndRequestCount(id, quota, 1)
  288. }
  289. func updateUserUsedQuotaAndRequestCount(id int, quota int, count int) {
  290. err := DB.Model(&User{}).Where("id = ?", id).Updates(
  291. map[string]interface{}{
  292. "used_quota": gorm.Expr("used_quota + ?", quota),
  293. "request_count": gorm.Expr("request_count + ?", count),
  294. },
  295. ).Error
  296. if err != nil {
  297. common.SysError("failed to update user used quota and request count: " + err.Error())
  298. }
  299. }
  300. func updateUserUsedQuota(id int, quota int) {
  301. err := DB.Model(&User{}).Where("id = ?", id).Updates(
  302. map[string]interface{}{
  303. "used_quota": gorm.Expr("used_quota + ?", quota),
  304. },
  305. ).Error
  306. if err != nil {
  307. common.SysError("failed to update user used quota: " + err.Error())
  308. }
  309. }
  310. func updateUserRequestCount(id int, count int) {
  311. err := DB.Model(&User{}).Where("id = ?", id).Update("request_count", gorm.Expr("request_count + ?", count)).Error
  312. if err != nil {
  313. common.SysError("failed to update user request count: " + err.Error())
  314. }
  315. }
  316. func GetUsernameById(id int) (username string) {
  317. DB.Model(&User{}).Where("id = ?", id).Select("username").Find(&username)
  318. return username
  319. }